|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242 |
- /* Version: 1.0.0 - September 29, 2021 19:31:21 */
- 'use strict';
-
- var path$1 = require('path');
- var childProcess = require('child_process');
- var fs$1 = require('fs');
- var readline = require('readline');
- var os = require('os');
- var tty = require('tty');
- var require$$0 = require('util');
- var require$$0$1 = require('events');
- var assert = require('assert');
-
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
- var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
- var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
- var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
- var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
- var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
- var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
-
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
-
- function getAugmentedNamespace(n) {
- if (n.__esModule) return n;
- var a = Object.defineProperty({}, '__esModule', {value: true});
- Object.keys(n).forEach(function (k) {
- var d = Object.getOwnPropertyDescriptor(n, k);
- Object.defineProperty(a, k, d.get ? d : {
- enumerable: true,
- get: function () {
- return n[k];
- }
- });
- });
- return a;
- }
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRegister (path, loader) {
- DYNAMIC_REQUIRE_LOADERS[path] = loader;
- }
-
- const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
- const DYNAMIC_REQUIRE_CACHE = Object.create(null);
- const DEFAULT_PARENT_MODULE = {
- id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
- };
- const CHECKED_EXTENSIONS = ['', '.js', '.json'];
-
- function normalize (path) {
- path = path.replace(/\\/g, '/');
- const parts = path.split('/');
- const slashed = parts[0] === '';
- for (let i = 1; i < parts.length; i++) {
- if (parts[i] === '.' || parts[i] === '') {
- parts.splice(i--, 1);
- }
- }
- for (let i = 1; i < parts.length; i++) {
- if (parts[i] !== '..') continue;
- if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
- parts.splice(--i, 2);
- i--;
- }
- }
- path = parts.join('/');
- if (slashed && path[0] !== '/')
- path = '/' + path;
- else if (path.length === 0)
- path = '.';
- return path;
- }
-
- function join () {
- if (arguments.length === 0)
- return '.';
- let joined;
- for (let i = 0; i < arguments.length; ++i) {
- let arg = arguments[i];
- if (arg.length > 0) {
- if (joined === undefined)
- joined = arg;
- else
- joined += '/' + arg;
- }
- }
- if (joined === undefined)
- return '.';
-
- return joined;
- }
-
- function isPossibleNodeModulesPath (modulePath) {
- let c0 = modulePath[0];
- if (c0 === '/' || c0 === '\\') return false;
- let c1 = modulePath[1], c2 = modulePath[2];
- if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
- (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
- if (c1 === ':' && (c2 === '/' || c2 === '\\'))
- return false;
- return true;
- }
-
- function dirname (path) {
- if (path.length === 0)
- return '.';
-
- let i = path.length - 1;
- while (i > 0) {
- const c = path.charCodeAt(i);
- if ((c === 47 || c === 92) && i !== path.length - 1)
- break;
- i--;
- }
-
- if (i > 0)
- return path.substr(0, i);
-
- if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
- return path.charAt(0);
-
- return '.';
- }
-
- function commonjsResolveImpl (path, originalModuleDir, testCache) {
- const shouldTryNodeModules = isPossibleNodeModulesPath(path);
- path = normalize(path);
- let relPath;
- if (path[0] === '/') {
- originalModuleDir = '/';
- }
- while (true) {
- if (!shouldTryNodeModules) {
- relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
- } else if (originalModuleDir) {
- relPath = normalize(originalModuleDir + '/node_modules/' + path);
- } else {
- relPath = normalize(join('node_modules', path));
- }
-
- if (relPath.endsWith('/..')) {
- break; // Travelled too far up, avoid infinite loop
- }
-
- for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
- const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
- if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
- return resolvedPath;
- } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
- return resolvedPath;
- } }
- if (!shouldTryNodeModules) break;
- const nextDir = normalize(originalModuleDir + '/..');
- if (nextDir === originalModuleDir) break;
- originalModuleDir = nextDir;
- }
- return null;
- }
-
- function commonjsResolve (path, originalModuleDir) {
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
- if (resolvedPath !== null) {
- return resolvedPath;
- }
- return require.resolve(path);
- }
-
- function commonjsRequire (path, originalModuleDir) {
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
- if (resolvedPath !== null) {
- let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
- if (cachedModule) return cachedModule.exports;
- const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
- if (loader) {
- DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
- id: resolvedPath,
- filename: resolvedPath,
- path: dirname(resolvedPath),
- exports: {},
- parent: DEFAULT_PARENT_MODULE,
- loaded: false,
- children: [],
- paths: [],
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
- }
- };
- try {
- loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
- } catch (error) {
- delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
- throw error;
- }
- cachedModule.loaded = true;
- return cachedModule.exports;
- } }
- return require(path);
- }
-
- commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
- commonjsRequire.resolve = commonjsResolve;
-
- /**
- * This method returns the first argument it receives.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Util
- * @param {*} value Any value.
- * @returns {*} Returns `value`.
- * @example
- *
- * var object = { 'a': 1 };
- *
- * console.log(_.identity(object) === object);
- * // => true
- */
- function identity(value) {
- return value;
- }
-
- var identity_1 = identity;
-
- /** Detect free variable `global` from Node.js. */
-
- var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
-
- var _freeGlobal = freeGlobal;
-
- /** Detect free variable `self`. */
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
-
- /** Used as a reference to the global object. */
- var root = _freeGlobal || freeSelf || Function('return this')();
-
- var _root = root;
-
- /** Built-in value references. */
- var Symbol$1 = _root.Symbol;
-
- var _Symbol = Symbol$1;
-
- /** Used for built-in method references. */
- var objectProto$h = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$e = objectProto$h.hasOwnProperty;
-
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString$1 = objectProto$h.toString;
-
- /** Built-in value references. */
- var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
-
- /**
- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the raw `toStringTag`.
- */
- function getRawTag(value) {
- var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
- tag = value[symToStringTag$1];
-
- try {
- value[symToStringTag$1] = undefined;
- var unmasked = true;
- } catch (e) {}
-
- var result = nativeObjectToString$1.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag$1] = tag;
- } else {
- delete value[symToStringTag$1];
- }
- }
- return result;
- }
-
- var _getRawTag = getRawTag;
-
- /** Used for built-in method references. */
- var objectProto$g = Object.prototype;
-
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto$g.toString;
-
- /**
- * Converts `value` to a string using `Object.prototype.toString`.
- *
- * @private
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- */
- function objectToString(value) {
- return nativeObjectToString.call(value);
- }
-
- var _objectToString = objectToString;
-
- /** `Object#toString` result references. */
- var nullTag = '[object Null]',
- undefinedTag = '[object Undefined]';
-
- /** Built-in value references. */
- var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
-
- /**
- * The base implementation of `getTag` without fallbacks for buggy environments.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- function baseGetTag(value) {
- if (value == null) {
- return value === undefined ? undefinedTag : nullTag;
- }
- return (symToStringTag && symToStringTag in Object(value))
- ? _getRawTag(value)
- : _objectToString(value);
- }
-
- var _baseGetTag = baseGetTag;
-
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject$1(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
- }
-
- var isObject_1 = isObject$1;
-
- /** `Object#toString` result references. */
- var asyncTag = '[object AsyncFunction]',
- funcTag$2 = '[object Function]',
- genTag$1 = '[object GeneratorFunction]',
- proxyTag = '[object Proxy]';
-
- /**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- *
- * _.isFunction(/abc/);
- * // => false
- */
- function isFunction(value) {
- if (!isObject_1(value)) {
- return false;
- }
- // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 9 which returns 'object' for typed arrays and other constructors.
- var tag = _baseGetTag(value);
- return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
- }
-
- var isFunction_1 = isFunction;
-
- /** Used to detect overreaching core-js shims. */
- var coreJsData = _root['__core-js_shared__'];
-
- var _coreJsData = coreJsData;
-
- /** Used to detect methods masquerading as native. */
- var maskSrcKey = (function() {
- var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
- return uid ? ('Symbol(src)_1.' + uid) : '';
- }());
-
- /**
- * Checks if `func` has its source masked.
- *
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
- */
- function isMasked(func) {
- return !!maskSrcKey && (maskSrcKey in func);
- }
-
- var _isMasked = isMasked;
-
- /** Used for built-in method references. */
- var funcProto$2 = Function.prototype;
-
- /** Used to resolve the decompiled source of functions. */
- var funcToString$2 = funcProto$2.toString;
-
- /**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to convert.
- * @returns {string} Returns the source code.
- */
- function toSource(func) {
- if (func != null) {
- try {
- return funcToString$2.call(func);
- } catch (e) {}
- try {
- return (func + '');
- } catch (e) {}
- }
- return '';
- }
-
- var _toSource = toSource;
-
- /**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
-
- /** Used to detect host constructors (Safari). */
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
-
- /** Used for built-in method references. */
- var funcProto$1 = Function.prototype,
- objectProto$f = Object.prototype;
-
- /** Used to resolve the decompiled source of functions. */
- var funcToString$1 = funcProto$1.toString;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$d = objectProto$f.hasOwnProperty;
-
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' +
- funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
- );
-
- /**
- * The base implementation of `_.isNative` without bad shim checks.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- */
- function baseIsNative(value) {
- if (!isObject_1(value) || _isMasked(value)) {
- return false;
- }
- var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
- return pattern.test(_toSource(value));
- }
-
- var _baseIsNative = baseIsNative;
-
- /**
- * Gets the value at `key` of `object`.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {string} key The key of the property to get.
- * @returns {*} Returns the property value.
- */
- function getValue(object, key) {
- return object == null ? undefined : object[key];
- }
-
- var _getValue = getValue;
-
- /**
- * Gets the native function at `key` of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {string} key The key of the method to get.
- * @returns {*} Returns the function if it's native, else `undefined`.
- */
- function getNative(object, key) {
- var value = _getValue(object, key);
- return _baseIsNative(value) ? value : undefined;
- }
-
- var _getNative = getNative;
-
- /* Built-in method references that are verified to be native. */
- var WeakMap$1 = _getNative(_root, 'WeakMap');
-
- var _WeakMap = WeakMap$1;
-
- /** Used to store function metadata. */
- var metaMap = _WeakMap && new _WeakMap;
-
- var _metaMap = metaMap;
-
- /**
- * The base implementation of `setData` without support for hot loop shorting.
- *
- * @private
- * @param {Function} func The function to associate metadata with.
- * @param {*} data The metadata.
- * @returns {Function} Returns `func`.
- */
- var baseSetData = !_metaMap ? identity_1 : function(func, data) {
- _metaMap.set(func, data);
- return func;
- };
-
- var _baseSetData = baseSetData;
-
- /** Built-in value references. */
- var objectCreate = Object.create;
-
- /**
- * The base implementation of `_.create` without support for assigning
- * properties to the created object.
- *
- * @private
- * @param {Object} proto The object to inherit from.
- * @returns {Object} Returns the new object.
- */
- var baseCreate = (function() {
- function object() {}
- return function(proto) {
- if (!isObject_1(proto)) {
- return {};
- }
- if (objectCreate) {
- return objectCreate(proto);
- }
- object.prototype = proto;
- var result = new object;
- object.prototype = undefined;
- return result;
- };
- }());
-
- var _baseCreate = baseCreate;
-
- /**
- * Creates a function that produces an instance of `Ctor` regardless of
- * whether it was invoked as part of a `new` expression or by `call` or `apply`.
- *
- * @private
- * @param {Function} Ctor The constructor to wrap.
- * @returns {Function} Returns the new wrapped function.
- */
- function createCtor(Ctor) {
- return function() {
- // Use a `switch` statement to work with class constructors. See
- // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
- // for more details.
- var args = arguments;
- switch (args.length) {
- case 0: return new Ctor;
- case 1: return new Ctor(args[0]);
- case 2: return new Ctor(args[0], args[1]);
- case 3: return new Ctor(args[0], args[1], args[2]);
- case 4: return new Ctor(args[0], args[1], args[2], args[3]);
- case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
- case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
- case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
- }
- var thisBinding = _baseCreate(Ctor.prototype),
- result = Ctor.apply(thisBinding, args);
-
- // Mimic the constructor's `return` behavior.
- // See https://es5.github.io/#x13.2.2 for more details.
- return isObject_1(result) ? result : thisBinding;
- };
- }
-
- var _createCtor = createCtor;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$6 = 1;
-
- /**
- * Creates a function that wraps `func` to invoke it with the optional `this`
- * binding of `thisArg`.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @returns {Function} Returns the new wrapped function.
- */
- function createBind(func, bitmask, thisArg) {
- var isBind = bitmask & WRAP_BIND_FLAG$6,
- Ctor = _createCtor(func);
-
- function wrapper() {
- var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
- return fn.apply(isBind ? thisArg : this, arguments);
- }
- return wrapper;
- }
-
- var _createBind = createBind;
-
- /**
- * A faster alternative to `Function#apply`, this function invokes `func`
- * with the `this` binding of `thisArg` and the arguments of `args`.
- *
- * @private
- * @param {Function} func The function to invoke.
- * @param {*} thisArg The `this` binding of `func`.
- * @param {Array} args The arguments to invoke `func` with.
- * @returns {*} Returns the result of `func`.
- */
- function apply(func, thisArg, args) {
- switch (args.length) {
- case 0: return func.call(thisArg);
- case 1: return func.call(thisArg, args[0]);
- case 2: return func.call(thisArg, args[0], args[1]);
- case 3: return func.call(thisArg, args[0], args[1], args[2]);
- }
- return func.apply(thisArg, args);
- }
-
- var _apply = apply;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax$3 = Math.max;
-
- /**
- * Creates an array that is the composition of partially applied arguments,
- * placeholders, and provided arguments into a single array of arguments.
- *
- * @private
- * @param {Array} args The provided arguments.
- * @param {Array} partials The arguments to prepend to those provided.
- * @param {Array} holders The `partials` placeholder indexes.
- * @params {boolean} [isCurried] Specify composing for a curried function.
- * @returns {Array} Returns the new array of composed arguments.
- */
- function composeArgs(args, partials, holders, isCurried) {
- var argsIndex = -1,
- argsLength = args.length,
- holdersLength = holders.length,
- leftIndex = -1,
- leftLength = partials.length,
- rangeLength = nativeMax$3(argsLength - holdersLength, 0),
- result = Array(leftLength + rangeLength),
- isUncurried = !isCurried;
-
- while (++leftIndex < leftLength) {
- result[leftIndex] = partials[leftIndex];
- }
- while (++argsIndex < holdersLength) {
- if (isUncurried || argsIndex < argsLength) {
- result[holders[argsIndex]] = args[argsIndex];
- }
- }
- while (rangeLength--) {
- result[leftIndex++] = args[argsIndex++];
- }
- return result;
- }
-
- var _composeArgs = composeArgs;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax$2 = Math.max;
-
- /**
- * This function is like `composeArgs` except that the arguments composition
- * is tailored for `_.partialRight`.
- *
- * @private
- * @param {Array} args The provided arguments.
- * @param {Array} partials The arguments to append to those provided.
- * @param {Array} holders The `partials` placeholder indexes.
- * @params {boolean} [isCurried] Specify composing for a curried function.
- * @returns {Array} Returns the new array of composed arguments.
- */
- function composeArgsRight(args, partials, holders, isCurried) {
- var argsIndex = -1,
- argsLength = args.length,
- holdersIndex = -1,
- holdersLength = holders.length,
- rightIndex = -1,
- rightLength = partials.length,
- rangeLength = nativeMax$2(argsLength - holdersLength, 0),
- result = Array(rangeLength + rightLength),
- isUncurried = !isCurried;
-
- while (++argsIndex < rangeLength) {
- result[argsIndex] = args[argsIndex];
- }
- var offset = argsIndex;
- while (++rightIndex < rightLength) {
- result[offset + rightIndex] = partials[rightIndex];
- }
- while (++holdersIndex < holdersLength) {
- if (isUncurried || argsIndex < argsLength) {
- result[offset + holders[holdersIndex]] = args[argsIndex++];
- }
- }
- return result;
- }
-
- var _composeArgsRight = composeArgsRight;
-
- /**
- * Gets the number of `placeholder` occurrences in `array`.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} placeholder The placeholder to search for.
- * @returns {number} Returns the placeholder count.
- */
- function countHolders(array, placeholder) {
- var length = array.length,
- result = 0;
-
- while (length--) {
- if (array[length] === placeholder) {
- ++result;
- }
- }
- return result;
- }
-
- var _countHolders = countHolders;
-
- /**
- * The function whose prototype chain sequence wrappers inherit from.
- *
- * @private
- */
- function baseLodash() {
- // No operation performed.
- }
-
- var _baseLodash = baseLodash;
-
- /** Used as references for the maximum length and index of an array. */
- var MAX_ARRAY_LENGTH = 4294967295;
-
- /**
- * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
- *
- * @private
- * @constructor
- * @param {*} value The value to wrap.
- */
- function LazyWrapper(value) {
- this.__wrapped__ = value;
- this.__actions__ = [];
- this.__dir__ = 1;
- this.__filtered__ = false;
- this.__iteratees__ = [];
- this.__takeCount__ = MAX_ARRAY_LENGTH;
- this.__views__ = [];
- }
-
- // Ensure `LazyWrapper` is an instance of `baseLodash`.
- LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
- LazyWrapper.prototype.constructor = LazyWrapper;
-
- var _LazyWrapper = LazyWrapper;
-
- /**
- * This method returns `undefined`.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Util
- * @example
- *
- * _.times(2, _.noop);
- * // => [undefined, undefined]
- */
- function noop() {
- // No operation performed.
- }
-
- var noop_1 = noop;
-
- /**
- * Gets metadata for `func`.
- *
- * @private
- * @param {Function} func The function to query.
- * @returns {*} Returns the metadata for `func`.
- */
- var getData = !_metaMap ? noop_1 : function(func) {
- return _metaMap.get(func);
- };
-
- var _getData = getData;
-
- /** Used to lookup unminified function names. */
- var realNames = {};
-
- var _realNames = realNames;
-
- /** Used for built-in method references. */
- var objectProto$e = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$c = objectProto$e.hasOwnProperty;
-
- /**
- * Gets the name of `func`.
- *
- * @private
- * @param {Function} func The function to query.
- * @returns {string} Returns the function name.
- */
- function getFuncName(func) {
- var result = (func.name + ''),
- array = _realNames[result],
- length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
-
- while (length--) {
- var data = array[length],
- otherFunc = data.func;
- if (otherFunc == null || otherFunc == func) {
- return data.name;
- }
- }
- return result;
- }
-
- var _getFuncName = getFuncName;
-
- /**
- * The base constructor for creating `lodash` wrapper objects.
- *
- * @private
- * @param {*} value The value to wrap.
- * @param {boolean} [chainAll] Enable explicit method chain sequences.
- */
- function LodashWrapper(value, chainAll) {
- this.__wrapped__ = value;
- this.__actions__ = [];
- this.__chain__ = !!chainAll;
- this.__index__ = 0;
- this.__values__ = undefined;
- }
-
- LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
- LodashWrapper.prototype.constructor = LodashWrapper;
-
- var _LodashWrapper = LodashWrapper;
-
- /**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
- var isArray$3 = Array.isArray;
-
- var isArray_1 = isArray$3;
-
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return value != null && typeof value == 'object';
- }
-
- var isObjectLike_1 = isObjectLike;
-
- /**
- * Copies the values of `source` to `array`.
- *
- * @private
- * @param {Array} source The array to copy values from.
- * @param {Array} [array=[]] The array to copy values to.
- * @returns {Array} Returns `array`.
- */
- function copyArray(source, array) {
- var index = -1,
- length = source.length;
-
- array || (array = Array(length));
- while (++index < length) {
- array[index] = source[index];
- }
- return array;
- }
-
- var _copyArray = copyArray;
-
- /**
- * Creates a clone of `wrapper`.
- *
- * @private
- * @param {Object} wrapper The wrapper to clone.
- * @returns {Object} Returns the cloned wrapper.
- */
- function wrapperClone(wrapper) {
- if (wrapper instanceof _LazyWrapper) {
- return wrapper.clone();
- }
- var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
- result.__actions__ = _copyArray(wrapper.__actions__);
- result.__index__ = wrapper.__index__;
- result.__values__ = wrapper.__values__;
- return result;
- }
-
- var _wrapperClone = wrapperClone;
-
- /** Used for built-in method references. */
- var objectProto$d = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$b = objectProto$d.hasOwnProperty;
-
- /**
- * Creates a `lodash` object which wraps `value` to enable implicit method
- * chain sequences. Methods that operate on and return arrays, collections,
- * and functions can be chained together. Methods that retrieve a single value
- * or may return a primitive value will automatically end the chain sequence
- * and return the unwrapped value. Otherwise, the value must be unwrapped
- * with `_#value`.
- *
- * Explicit chain sequences, which must be unwrapped with `_#value`, may be
- * enabled using `_.chain`.
- *
- * The execution of chained methods is lazy, that is, it's deferred until
- * `_#value` is implicitly or explicitly called.
- *
- * Lazy evaluation allows several methods to support shortcut fusion.
- * Shortcut fusion is an optimization to merge iteratee calls; this avoids
- * the creation of intermediate arrays and can greatly reduce the number of
- * iteratee executions. Sections of a chain sequence qualify for shortcut
- * fusion if the section is applied to an array and iteratees accept only
- * one argument. The heuristic for whether a section qualifies for shortcut
- * fusion is subject to change.
- *
- * Chaining is supported in custom builds as long as the `_#value` method is
- * directly or indirectly included in the build.
- *
- * In addition to lodash methods, wrappers have `Array` and `String` methods.
- *
- * The wrapper `Array` methods are:
- * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
- *
- * The wrapper `String` methods are:
- * `replace` and `split`
- *
- * The wrapper methods that support shortcut fusion are:
- * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
- * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
- * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
- *
- * The chainable wrapper methods are:
- * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
- * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
- * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
- * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
- * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
- * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
- * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
- * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
- * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
- * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
- * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
- * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
- * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
- * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
- * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
- * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
- * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
- * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
- * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
- * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
- * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
- * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
- * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
- * `zipObject`, `zipObjectDeep`, and `zipWith`
- *
- * The wrapper methods that are **not** chainable by default are:
- * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
- * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
- * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
- * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
- * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
- * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
- * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
- * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
- * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
- * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
- * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
- * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
- * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
- * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
- * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
- * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
- * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
- * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
- * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
- * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
- * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
- * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
- * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
- * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
- * `upperFirst`, `value`, and `words`
- *
- * @name _
- * @constructor
- * @category Seq
- * @param {*} value The value to wrap in a `lodash` instance.
- * @returns {Object} Returns the new `lodash` wrapper instance.
- * @example
- *
- * function square(n) {
- * return n * n;
- * }
- *
- * var wrapped = _([1, 2, 3]);
- *
- * // Returns an unwrapped value.
- * wrapped.reduce(_.add);
- * // => 6
- *
- * // Returns a wrapped value.
- * var squares = wrapped.map(square);
- *
- * _.isArray(squares);
- * // => false
- *
- * _.isArray(squares.value());
- * // => true
- */
- function lodash(value) {
- if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
- if (value instanceof _LodashWrapper) {
- return value;
- }
- if (hasOwnProperty$b.call(value, '__wrapped__')) {
- return _wrapperClone(value);
- }
- }
- return new _LodashWrapper(value);
- }
-
- // Ensure wrappers are instances of `baseLodash`.
- lodash.prototype = _baseLodash.prototype;
- lodash.prototype.constructor = lodash;
-
- var wrapperLodash = lodash;
-
- /**
- * Checks if `func` has a lazy counterpart.
- *
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
- * else `false`.
- */
- function isLaziable(func) {
- var funcName = _getFuncName(func),
- other = wrapperLodash[funcName];
-
- if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
- return false;
- }
- if (func === other) {
- return true;
- }
- var data = _getData(other);
- return !!data && func === data[0];
- }
-
- var _isLaziable = isLaziable;
-
- /** Used to detect hot functions by number of calls within a span of milliseconds. */
- var HOT_COUNT = 800,
- HOT_SPAN = 16;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeNow = Date.now;
-
- /**
- * Creates a function that'll short out and invoke `identity` instead
- * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
- * milliseconds.
- *
- * @private
- * @param {Function} func The function to restrict.
- * @returns {Function} Returns the new shortable function.
- */
- function shortOut(func) {
- var count = 0,
- lastCalled = 0;
-
- return function() {
- var stamp = nativeNow(),
- remaining = HOT_SPAN - (stamp - lastCalled);
-
- lastCalled = stamp;
- if (remaining > 0) {
- if (++count >= HOT_COUNT) {
- return arguments[0];
- }
- } else {
- count = 0;
- }
- return func.apply(undefined, arguments);
- };
- }
-
- var _shortOut = shortOut;
-
- /**
- * Sets metadata for `func`.
- *
- * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
- * period of time, it will trip its breaker and transition to an identity
- * function to avoid garbage collection pauses in V8. See
- * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
- * for more details.
- *
- * @private
- * @param {Function} func The function to associate metadata with.
- * @param {*} data The metadata.
- * @returns {Function} Returns `func`.
- */
- var setData = _shortOut(_baseSetData);
-
- var _setData = setData;
-
- /** Used to match wrap detail comments. */
- var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
- reSplitDetails = /,? & /;
-
- /**
- * Extracts wrapper details from the `source` body comment.
- *
- * @private
- * @param {string} source The source to inspect.
- * @returns {Array} Returns the wrapper details.
- */
- function getWrapDetails(source) {
- var match = source.match(reWrapDetails);
- return match ? match[1].split(reSplitDetails) : [];
- }
-
- var _getWrapDetails = getWrapDetails;
-
- /** Used to match wrap detail comments. */
- var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
-
- /**
- * Inserts wrapper `details` in a comment at the top of the `source` body.
- *
- * @private
- * @param {string} source The source to modify.
- * @returns {Array} details The details to insert.
- * @returns {string} Returns the modified source.
- */
- function insertWrapDetails(source, details) {
- var length = details.length;
- if (!length) {
- return source;
- }
- var lastIndex = length - 1;
- details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
- details = details.join(length > 2 ? ', ' : ' ');
- return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
- }
-
- var _insertWrapDetails = insertWrapDetails;
-
- /**
- * Creates a function that returns `value`.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {*} value The value to return from the new function.
- * @returns {Function} Returns the new constant function.
- * @example
- *
- * var objects = _.times(2, _.constant({ 'a': 1 }));
- *
- * console.log(objects);
- * // => [{ 'a': 1 }, { 'a': 1 }]
- *
- * console.log(objects[0] === objects[1]);
- * // => true
- */
- function constant(value) {
- return function() {
- return value;
- };
- }
-
- var constant_1 = constant;
-
- var defineProperty = (function() {
- try {
- var func = _getNative(Object, 'defineProperty');
- func({}, '', {});
- return func;
- } catch (e) {}
- }());
-
- var _defineProperty = defineProperty;
-
- /**
- * The base implementation of `setToString` without support for hot loop shorting.
- *
- * @private
- * @param {Function} func The function to modify.
- * @param {Function} string The `toString` result.
- * @returns {Function} Returns `func`.
- */
- var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
- return _defineProperty(func, 'toString', {
- 'configurable': true,
- 'enumerable': false,
- 'value': constant_1(string),
- 'writable': true
- });
- };
-
- var _baseSetToString = baseSetToString;
-
- /**
- * Sets the `toString` method of `func` to return `string`.
- *
- * @private
- * @param {Function} func The function to modify.
- * @param {Function} string The `toString` result.
- * @returns {Function} Returns `func`.
- */
- var setToString = _shortOut(_baseSetToString);
-
- var _setToString = setToString;
-
- /**
- * A specialized version of `_.forEach` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns `array`.
- */
- function arrayEach(array, iteratee) {
- var index = -1,
- length = array == null ? 0 : array.length;
-
- while (++index < length) {
- if (iteratee(array[index], index, array) === false) {
- break;
- }
- }
- return array;
- }
-
- var _arrayEach = arrayEach;
-
- /**
- * The base implementation of `_.findIndex` and `_.findLastIndex` without
- * support for iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {Function} predicate The function invoked per iteration.
- * @param {number} fromIndex The index to search from.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseFindIndex(array, predicate, fromIndex, fromRight) {
- var length = array.length,
- index = fromIndex + (fromRight ? 1 : -1);
-
- while ((fromRight ? index-- : ++index < length)) {
- if (predicate(array[index], index, array)) {
- return index;
- }
- }
- return -1;
- }
-
- var _baseFindIndex = baseFindIndex;
-
- /**
- * The base implementation of `_.isNaN` without support for number objects.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
- */
- function baseIsNaN(value) {
- return value !== value;
- }
-
- var _baseIsNaN = baseIsNaN;
-
- /**
- * A specialized version of `_.indexOf` which performs strict equality
- * comparisons of values, i.e. `===`.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function strictIndexOf(array, value, fromIndex) {
- var index = fromIndex - 1,
- length = array.length;
-
- while (++index < length) {
- if (array[index] === value) {
- return index;
- }
- }
- return -1;
- }
-
- var _strictIndexOf = strictIndexOf;
-
- /**
- * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseIndexOf(array, value, fromIndex) {
- return value === value
- ? _strictIndexOf(array, value, fromIndex)
- : _baseFindIndex(array, _baseIsNaN, fromIndex);
- }
-
- var _baseIndexOf = baseIndexOf;
-
- /**
- * A specialized version of `_.includes` for arrays without support for
- * specifying an index to search from.
- *
- * @private
- * @param {Array} [array] The array to inspect.
- * @param {*} target The value to search for.
- * @returns {boolean} Returns `true` if `target` is found, else `false`.
- */
- function arrayIncludes(array, value) {
- var length = array == null ? 0 : array.length;
- return !!length && _baseIndexOf(array, value, 0) > -1;
- }
-
- var _arrayIncludes = arrayIncludes;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$5 = 1,
- WRAP_BIND_KEY_FLAG$4 = 2,
- WRAP_CURRY_FLAG$4 = 8,
- WRAP_CURRY_RIGHT_FLAG$2 = 16,
- WRAP_PARTIAL_FLAG$2 = 32,
- WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
- WRAP_ARY_FLAG$3 = 128,
- WRAP_REARG_FLAG$2 = 256,
- WRAP_FLIP_FLAG$1 = 512;
-
- /** Used to associate wrap methods with their bit flags. */
- var wrapFlags = [
- ['ary', WRAP_ARY_FLAG$3],
- ['bind', WRAP_BIND_FLAG$5],
- ['bindKey', WRAP_BIND_KEY_FLAG$4],
- ['curry', WRAP_CURRY_FLAG$4],
- ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
- ['flip', WRAP_FLIP_FLAG$1],
- ['partial', WRAP_PARTIAL_FLAG$2],
- ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
- ['rearg', WRAP_REARG_FLAG$2]
- ];
-
- /**
- * Updates wrapper `details` based on `bitmask` flags.
- *
- * @private
- * @returns {Array} details The details to modify.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @returns {Array} Returns `details`.
- */
- function updateWrapDetails(details, bitmask) {
- _arrayEach(wrapFlags, function(pair) {
- var value = '_.' + pair[0];
- if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
- details.push(value);
- }
- });
- return details.sort();
- }
-
- var _updateWrapDetails = updateWrapDetails;
-
- /**
- * Sets the `toString` method of `wrapper` to mimic the source of `reference`
- * with wrapper details in a comment at the top of the source body.
- *
- * @private
- * @param {Function} wrapper The function to modify.
- * @param {Function} reference The reference function.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @returns {Function} Returns `wrapper`.
- */
- function setWrapToString(wrapper, reference, bitmask) {
- var source = (reference + '');
- return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
- }
-
- var _setWrapToString = setWrapToString;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$4 = 1,
- WRAP_BIND_KEY_FLAG$3 = 2,
- WRAP_CURRY_BOUND_FLAG$1 = 4,
- WRAP_CURRY_FLAG$3 = 8,
- WRAP_PARTIAL_FLAG$1 = 32,
- WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
-
- /**
- * Creates a function that wraps `func` to continue currying.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @param {Function} wrapFunc The function to create the `func` wrapper.
- * @param {*} placeholder The placeholder value.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {Array} [partials] The arguments to prepend to those provided to
- * the new function.
- * @param {Array} [holders] The `partials` placeholder indexes.
- * @param {Array} [argPos] The argument positions of the new function.
- * @param {number} [ary] The arity cap of `func`.
- * @param {number} [arity] The arity of `func`.
- * @returns {Function} Returns the new wrapped function.
- */
- function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
- var isCurry = bitmask & WRAP_CURRY_FLAG$3,
- newHolders = isCurry ? holders : undefined,
- newHoldersRight = isCurry ? undefined : holders,
- newPartials = isCurry ? partials : undefined,
- newPartialsRight = isCurry ? undefined : partials;
-
- bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
- bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
-
- if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
- bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
- }
- var newData = [
- func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
- newHoldersRight, argPos, ary, arity
- ];
-
- var result = wrapFunc.apply(undefined, newData);
- if (_isLaziable(func)) {
- _setData(result, newData);
- }
- result.placeholder = placeholder;
- return _setWrapToString(result, func, bitmask);
- }
-
- var _createRecurry = createRecurry;
-
- /**
- * Gets the argument placeholder value for `func`.
- *
- * @private
- * @param {Function} func The function to inspect.
- * @returns {*} Returns the placeholder value.
- */
- function getHolder(func) {
- var object = func;
- return object.placeholder;
- }
-
- var _getHolder = getHolder;
-
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER$1 = 9007199254740991;
-
- /** Used to detect unsigned integer values. */
- var reIsUint = /^(?:0|[1-9]\d*)$/;
-
- /**
- * Checks if `value` is a valid array-like index.
- *
- * @private
- * @param {*} value The value to check.
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
- */
- function isIndex(value, length) {
- var type = typeof value;
- length = length == null ? MAX_SAFE_INTEGER$1 : length;
-
- return !!length &&
- (type == 'number' ||
- (type != 'symbol' && reIsUint.test(value))) &&
- (value > -1 && value % 1 == 0 && value < length);
- }
-
- var _isIndex = isIndex;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMin$1 = Math.min;
-
- /**
- * Reorder `array` according to the specified indexes where the element at
- * the first index is assigned as the first element, the element at
- * the second index is assigned as the second element, and so on.
- *
- * @private
- * @param {Array} array The array to reorder.
- * @param {Array} indexes The arranged array indexes.
- * @returns {Array} Returns `array`.
- */
- function reorder(array, indexes) {
- var arrLength = array.length,
- length = nativeMin$1(indexes.length, arrLength),
- oldArray = _copyArray(array);
-
- while (length--) {
- var index = indexes[length];
- array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
- }
- return array;
- }
-
- var _reorder = reorder;
-
- /** Used as the internal argument placeholder. */
- var PLACEHOLDER$1 = '__lodash_placeholder__';
-
- /**
- * Replaces all `placeholder` elements in `array` with an internal placeholder
- * and returns an array of their indexes.
- *
- * @private
- * @param {Array} array The array to modify.
- * @param {*} placeholder The placeholder to replace.
- * @returns {Array} Returns the new array of placeholder indexes.
- */
- function replaceHolders(array, placeholder) {
- var index = -1,
- length = array.length,
- resIndex = 0,
- result = [];
-
- while (++index < length) {
- var value = array[index];
- if (value === placeholder || value === PLACEHOLDER$1) {
- array[index] = PLACEHOLDER$1;
- result[resIndex++] = index;
- }
- }
- return result;
- }
-
- var _replaceHolders = replaceHolders;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$3 = 1,
- WRAP_BIND_KEY_FLAG$2 = 2,
- WRAP_CURRY_FLAG$2 = 8,
- WRAP_CURRY_RIGHT_FLAG$1 = 16,
- WRAP_ARY_FLAG$2 = 128,
- WRAP_FLIP_FLAG = 512;
-
- /**
- * Creates a function that wraps `func` to invoke it with optional `this`
- * binding of `thisArg`, partial application, and currying.
- *
- * @private
- * @param {Function|string} func The function or method name to wrap.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {Array} [partials] The arguments to prepend to those provided to
- * the new function.
- * @param {Array} [holders] The `partials` placeholder indexes.
- * @param {Array} [partialsRight] The arguments to append to those provided
- * to the new function.
- * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
- * @param {Array} [argPos] The argument positions of the new function.
- * @param {number} [ary] The arity cap of `func`.
- * @param {number} [arity] The arity of `func`.
- * @returns {Function} Returns the new wrapped function.
- */
- function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
- var isAry = bitmask & WRAP_ARY_FLAG$2,
- isBind = bitmask & WRAP_BIND_FLAG$3,
- isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
- isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
- isFlip = bitmask & WRAP_FLIP_FLAG,
- Ctor = isBindKey ? undefined : _createCtor(func);
-
- function wrapper() {
- var length = arguments.length,
- args = Array(length),
- index = length;
-
- while (index--) {
- args[index] = arguments[index];
- }
- if (isCurried) {
- var placeholder = _getHolder(wrapper),
- holdersCount = _countHolders(args, placeholder);
- }
- if (partials) {
- args = _composeArgs(args, partials, holders, isCurried);
- }
- if (partialsRight) {
- args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
- }
- length -= holdersCount;
- if (isCurried && length < arity) {
- var newHolders = _replaceHolders(args, placeholder);
- return _createRecurry(
- func, bitmask, createHybrid, wrapper.placeholder, thisArg,
- args, newHolders, argPos, ary, arity - length
- );
- }
- var thisBinding = isBind ? thisArg : this,
- fn = isBindKey ? thisBinding[func] : func;
-
- length = args.length;
- if (argPos) {
- args = _reorder(args, argPos);
- } else if (isFlip && length > 1) {
- args.reverse();
- }
- if (isAry && ary < length) {
- args.length = ary;
- }
- if (this && this !== _root && this instanceof wrapper) {
- fn = Ctor || _createCtor(fn);
- }
- return fn.apply(thisBinding, args);
- }
- return wrapper;
- }
-
- var _createHybrid = createHybrid;
-
- /**
- * Creates a function that wraps `func` to enable currying.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @param {number} arity The arity of `func`.
- * @returns {Function} Returns the new wrapped function.
- */
- function createCurry(func, bitmask, arity) {
- var Ctor = _createCtor(func);
-
- function wrapper() {
- var length = arguments.length,
- args = Array(length),
- index = length,
- placeholder = _getHolder(wrapper);
-
- while (index--) {
- args[index] = arguments[index];
- }
- var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
- ? []
- : _replaceHolders(args, placeholder);
-
- length -= holders.length;
- if (length < arity) {
- return _createRecurry(
- func, bitmask, _createHybrid, wrapper.placeholder, undefined,
- args, holders, undefined, undefined, arity - length);
- }
- var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
- return _apply(fn, this, args);
- }
- return wrapper;
- }
-
- var _createCurry = createCurry;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$2 = 1;
-
- /**
- * Creates a function that wraps `func` to invoke it with the `this` binding
- * of `thisArg` and `partials` prepended to the arguments it receives.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
- * @param {*} thisArg The `this` binding of `func`.
- * @param {Array} partials The arguments to prepend to those provided to
- * the new function.
- * @returns {Function} Returns the new wrapped function.
- */
- function createPartial(func, bitmask, thisArg, partials) {
- var isBind = bitmask & WRAP_BIND_FLAG$2,
- Ctor = _createCtor(func);
-
- function wrapper() {
- var argsIndex = -1,
- argsLength = arguments.length,
- leftIndex = -1,
- leftLength = partials.length,
- args = Array(leftLength + argsLength),
- fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
-
- while (++leftIndex < leftLength) {
- args[leftIndex] = partials[leftIndex];
- }
- while (argsLength--) {
- args[leftIndex++] = arguments[++argsIndex];
- }
- return _apply(fn, isBind ? thisArg : this, args);
- }
- return wrapper;
- }
-
- var _createPartial = createPartial;
-
- /** Used as the internal argument placeholder. */
- var PLACEHOLDER = '__lodash_placeholder__';
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG$1 = 1,
- WRAP_BIND_KEY_FLAG$1 = 2,
- WRAP_CURRY_BOUND_FLAG = 4,
- WRAP_CURRY_FLAG$1 = 8,
- WRAP_ARY_FLAG$1 = 128,
- WRAP_REARG_FLAG$1 = 256;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMin = Math.min;
-
- /**
- * Merges the function metadata of `source` into `data`.
- *
- * Merging metadata reduces the number of wrappers used to invoke a function.
- * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
- * may be applied regardless of execution order. Methods like `_.ary` and
- * `_.rearg` modify function arguments, making the order in which they are
- * executed important, preventing the merging of metadata. However, we make
- * an exception for a safe combined case where curried functions have `_.ary`
- * and or `_.rearg` applied.
- *
- * @private
- * @param {Array} data The destination metadata.
- * @param {Array} source The source metadata.
- * @returns {Array} Returns `data`.
- */
- function mergeData(data, source) {
- var bitmask = data[1],
- srcBitmask = source[1],
- newBitmask = bitmask | srcBitmask,
- isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
-
- var isCombo =
- ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
- ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
- ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
-
- // Exit early if metadata can't be merged.
- if (!(isCommon || isCombo)) {
- return data;
- }
- // Use source `thisArg` if available.
- if (srcBitmask & WRAP_BIND_FLAG$1) {
- data[2] = source[2];
- // Set when currying a bound function.
- newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
- }
- // Compose partial arguments.
- var value = source[3];
- if (value) {
- var partials = data[3];
- data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
- data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
- }
- // Compose partial right arguments.
- value = source[5];
- if (value) {
- partials = data[5];
- data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
- data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
- }
- // Use source `argPos` if available.
- value = source[7];
- if (value) {
- data[7] = value;
- }
- // Use source `ary` if it's smaller.
- if (srcBitmask & WRAP_ARY_FLAG$1) {
- data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
- }
- // Use source `arity` if one is not provided.
- if (data[9] == null) {
- data[9] = source[9];
- }
- // Use source `func` and merge bitmasks.
- data[0] = source[0];
- data[1] = newBitmask;
-
- return data;
- }
-
- var _mergeData = mergeData;
-
- /** Used to match a single whitespace character. */
- var reWhitespace = /\s/;
-
- /**
- * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
- * character of `string`.
- *
- * @private
- * @param {string} string The string to inspect.
- * @returns {number} Returns the index of the last non-whitespace character.
- */
- function trimmedEndIndex(string) {
- var index = string.length;
-
- while (index-- && reWhitespace.test(string.charAt(index))) {}
- return index;
- }
-
- var _trimmedEndIndex = trimmedEndIndex;
-
- /** Used to match leading whitespace. */
- var reTrimStart = /^\s+/;
-
- /**
- * The base implementation of `_.trim`.
- *
- * @private
- * @param {string} string The string to trim.
- * @returns {string} Returns the trimmed string.
- */
- function baseTrim(string) {
- return string
- ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
- : string;
- }
-
- var _baseTrim = baseTrim;
-
- /** `Object#toString` result references. */
- var symbolTag$3 = '[object Symbol]';
-
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == 'symbol' ||
- (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
- }
-
- var isSymbol_1 = isSymbol;
-
- /** Used as references for various `Number` constants. */
- var NAN = 0 / 0;
-
- /** Used to detect bad signed hexadecimal string values. */
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
-
- /** Used to detect binary string values. */
- var reIsBinary = /^0b[01]+$/i;
-
- /** Used to detect octal string values. */
- var reIsOctal = /^0o[0-7]+$/i;
-
- /** Built-in method references without a dependency on `root`. */
- var freeParseInt = parseInt;
-
- /**
- * Converts `value` to a number.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to process.
- * @returns {number} Returns the number.
- * @example
- *
- * _.toNumber(3.2);
- * // => 3.2
- *
- * _.toNumber(Number.MIN_VALUE);
- * // => 5e-324
- *
- * _.toNumber(Infinity);
- * // => Infinity
- *
- * _.toNumber('3.2');
- * // => 3.2
- */
- function toNumber(value) {
- if (typeof value == 'number') {
- return value;
- }
- if (isSymbol_1(value)) {
- return NAN;
- }
- if (isObject_1(value)) {
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
- value = isObject_1(other) ? (other + '') : other;
- }
- if (typeof value != 'string') {
- return value === 0 ? value : +value;
- }
- value = _baseTrim(value);
- var isBinary = reIsBinary.test(value);
- return (isBinary || reIsOctal.test(value))
- ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
- : (reIsBadHex.test(value) ? NAN : +value);
- }
-
- var toNumber_1 = toNumber;
-
- /** Used as references for various `Number` constants. */
- var INFINITY$2 = 1 / 0,
- MAX_INTEGER = 1.7976931348623157e+308;
-
- /**
- * Converts `value` to a finite number.
- *
- * @static
- * @memberOf _
- * @since 4.12.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted number.
- * @example
- *
- * _.toFinite(3.2);
- * // => 3.2
- *
- * _.toFinite(Number.MIN_VALUE);
- * // => 5e-324
- *
- * _.toFinite(Infinity);
- * // => 1.7976931348623157e+308
- *
- * _.toFinite('3.2');
- * // => 3.2
- */
- function toFinite(value) {
- if (!value) {
- return value === 0 ? value : 0;
- }
- value = toNumber_1(value);
- if (value === INFINITY$2 || value === -INFINITY$2) {
- var sign = (value < 0 ? -1 : 1);
- return sign * MAX_INTEGER;
- }
- return value === value ? value : 0;
- }
-
- var toFinite_1 = toFinite;
-
- /**
- * Converts `value` to an integer.
- *
- * **Note:** This method is loosely based on
- * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted integer.
- * @example
- *
- * _.toInteger(3.2);
- * // => 3
- *
- * _.toInteger(Number.MIN_VALUE);
- * // => 0
- *
- * _.toInteger(Infinity);
- * // => 1.7976931348623157e+308
- *
- * _.toInteger('3.2');
- * // => 3
- */
- function toInteger(value) {
- var result = toFinite_1(value),
- remainder = result % 1;
-
- return result === result ? (remainder ? result - remainder : result) : 0;
- }
-
- var toInteger_1 = toInteger;
-
- /** Error message constants. */
- var FUNC_ERROR_TEXT$1 = 'Expected a function';
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_BIND_FLAG = 1,
- WRAP_BIND_KEY_FLAG = 2,
- WRAP_CURRY_FLAG = 8,
- WRAP_CURRY_RIGHT_FLAG = 16,
- WRAP_PARTIAL_FLAG = 32,
- WRAP_PARTIAL_RIGHT_FLAG = 64;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax$1 = Math.max;
-
- /**
- * Creates a function that either curries or invokes `func` with optional
- * `this` binding and partially applied arguments.
- *
- * @private
- * @param {Function|string} func The function or method name to wrap.
- * @param {number} bitmask The bitmask flags.
- * 1 - `_.bind`
- * 2 - `_.bindKey`
- * 4 - `_.curry` or `_.curryRight` of a bound function
- * 8 - `_.curry`
- * 16 - `_.curryRight`
- * 32 - `_.partial`
- * 64 - `_.partialRight`
- * 128 - `_.rearg`
- * 256 - `_.ary`
- * 512 - `_.flip`
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {Array} [partials] The arguments to be partially applied.
- * @param {Array} [holders] The `partials` placeholder indexes.
- * @param {Array} [argPos] The argument positions of the new function.
- * @param {number} [ary] The arity cap of `func`.
- * @param {number} [arity] The arity of `func`.
- * @returns {Function} Returns the new wrapped function.
- */
- function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
- var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
- if (!isBindKey && typeof func != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT$1);
- }
- var length = partials ? partials.length : 0;
- if (!length) {
- bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
- partials = holders = undefined;
- }
- ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
- arity = arity === undefined ? arity : toInteger_1(arity);
- length -= holders ? holders.length : 0;
-
- if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
- var partialsRight = partials,
- holdersRight = holders;
-
- partials = holders = undefined;
- }
- var data = isBindKey ? undefined : _getData(func);
-
- var newData = [
- func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
- argPos, ary, arity
- ];
-
- if (data) {
- _mergeData(newData, data);
- }
- func = newData[0];
- bitmask = newData[1];
- thisArg = newData[2];
- partials = newData[3];
- holders = newData[4];
- arity = newData[9] = newData[9] === undefined
- ? (isBindKey ? 0 : func.length)
- : nativeMax$1(newData[9] - length, 0);
-
- if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
- bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
- }
- if (!bitmask || bitmask == WRAP_BIND_FLAG) {
- var result = _createBind(func, bitmask, thisArg);
- } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
- result = _createCurry(func, bitmask, arity);
- } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
- result = _createPartial(func, bitmask, thisArg, partials);
- } else {
- result = _createHybrid.apply(undefined, newData);
- }
- var setter = data ? _baseSetData : _setData;
- return _setWrapToString(setter(result, newData), func, bitmask);
- }
-
- var _createWrap = createWrap;
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
- var createWrap = _createWrap;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_CURRY_FLAG = 8;
-
- /**
- * Creates a function that accepts arguments of `func` and either invokes
- * `func` returning its result, if at least `arity` number of arguments have
- * been provided, or returns a function that accepts the remaining `func`
- * arguments, and so on. The arity of `func` may be specified if `func.length`
- * is not sufficient.
- *
- * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
- * may be used as a placeholder for provided arguments.
- *
- * **Note:** This method doesn't set the "length" property of curried functions.
- *
- * @static
- * @memberOf _
- * @since 2.0.0
- * @category Function
- * @param {Function} func The function to curry.
- * @param {number} [arity=func.length] The arity of `func`.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {Function} Returns the new curried function.
- * @example
- *
- * var abc = function(a, b, c) {
- * return [a, b, c];
- * };
- *
- * var curried = _.curry(abc);
- *
- * curried(1)(2)(3);
- * // => [1, 2, 3]
- *
- * curried(1, 2)(3);
- * // => [1, 2, 3]
- *
- * curried(1, 2, 3);
- * // => [1, 2, 3]
- *
- * // Curried with placeholders.
- * curried(1)(_, 3)(2);
- * // => [1, 2, 3]
- */
- function curry(func, arity, guard) {
- arity = guard ? undefined : arity;
- var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
- result.placeholder = curry.placeholder;
- return result;
- }
-
- // Assign default placeholders.
- curry.placeholder = {};
-
- module.exports = curry;
-
- });
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
- var createWrap = _createWrap;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_CURRY_RIGHT_FLAG = 16;
-
- /**
- * This method is like `_.curry` except that arguments are applied to `func`
- * in the manner of `_.partialRight` instead of `_.partial`.
- *
- * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
- * builds, may be used as a placeholder for provided arguments.
- *
- * **Note:** This method doesn't set the "length" property of curried functions.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Function
- * @param {Function} func The function to curry.
- * @param {number} [arity=func.length] The arity of `func`.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {Function} Returns the new curried function.
- * @example
- *
- * var abc = function(a, b, c) {
- * return [a, b, c];
- * };
- *
- * var curried = _.curryRight(abc);
- *
- * curried(3)(2)(1);
- * // => [1, 2, 3]
- *
- * curried(2, 3)(1);
- * // => [1, 2, 3]
- *
- * curried(1, 2, 3);
- * // => [1, 2, 3]
- *
- * // Curried with placeholders.
- * curried(3)(1, _)(2);
- * // => [1, 2, 3]
- */
- function curryRight(func, arity, guard) {
- arity = guard ? undefined : arity;
- var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
- result.placeholder = curryRight.placeholder;
- return result;
- }
-
- // Assign default placeholders.
- curryRight.placeholder = {};
-
- module.exports = curryRight;
-
- });
-
- /** Used to map aliases to their real names. */
-
- var _mapping = createCommonjsModule(function (module, exports) {
- exports.aliasToReal = {
-
- // Lodash aliases.
- 'each': 'forEach',
- 'eachRight': 'forEachRight',
- 'entries': 'toPairs',
- 'entriesIn': 'toPairsIn',
- 'extend': 'assignIn',
- 'extendAll': 'assignInAll',
- 'extendAllWith': 'assignInAllWith',
- 'extendWith': 'assignInWith',
- 'first': 'head',
-
- // Methods that are curried variants of others.
- 'conforms': 'conformsTo',
- 'matches': 'isMatch',
- 'property': 'get',
-
- // Ramda aliases.
- '__': 'placeholder',
- 'F': 'stubFalse',
- 'T': 'stubTrue',
- 'all': 'every',
- 'allPass': 'overEvery',
- 'always': 'constant',
- 'any': 'some',
- 'anyPass': 'overSome',
- 'apply': 'spread',
- 'assoc': 'set',
- 'assocPath': 'set',
- 'complement': 'negate',
- 'compose': 'flowRight',
- 'contains': 'includes',
- 'dissoc': 'unset',
- 'dissocPath': 'unset',
- 'dropLast': 'dropRight',
- 'dropLastWhile': 'dropRightWhile',
- 'equals': 'isEqual',
- 'identical': 'eq',
- 'indexBy': 'keyBy',
- 'init': 'initial',
- 'invertObj': 'invert',
- 'juxt': 'over',
- 'omitAll': 'omit',
- 'nAry': 'ary',
- 'path': 'get',
- 'pathEq': 'matchesProperty',
- 'pathOr': 'getOr',
- 'paths': 'at',
- 'pickAll': 'pick',
- 'pipe': 'flow',
- 'pluck': 'map',
- 'prop': 'get',
- 'propEq': 'matchesProperty',
- 'propOr': 'getOr',
- 'props': 'at',
- 'symmetricDifference': 'xor',
- 'symmetricDifferenceBy': 'xorBy',
- 'symmetricDifferenceWith': 'xorWith',
- 'takeLast': 'takeRight',
- 'takeLastWhile': 'takeRightWhile',
- 'unapply': 'rest',
- 'unnest': 'flatten',
- 'useWith': 'overArgs',
- 'where': 'conformsTo',
- 'whereEq': 'isMatch',
- 'zipObj': 'zipObject'
- };
-
- /** Used to map ary to method names. */
- exports.aryMethod = {
- '1': [
- 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
- 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
- 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
- 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
- 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
- 'uniqueId', 'words', 'zipAll'
- ],
- '2': [
- 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
- 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
- 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
- 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
- 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
- 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
- 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
- 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
- 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
- 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
- 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
- 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
- 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
- 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
- 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
- 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
- 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
- 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
- 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
- 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
- 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
- 'zipObjectDeep'
- ],
- '3': [
- 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
- 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
- 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
- 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
- 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
- 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
- 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
- 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
- 'xorWith', 'zipWith'
- ],
- '4': [
- 'fill', 'setWith', 'updateWith'
- ]
- };
-
- /** Used to map ary to rearg configs. */
- exports.aryRearg = {
- '2': [1, 0],
- '3': [2, 0, 1],
- '4': [3, 2, 0, 1]
- };
-
- /** Used to map method names to their iteratee ary. */
- exports.iterateeAry = {
- 'dropRightWhile': 1,
- 'dropWhile': 1,
- 'every': 1,
- 'filter': 1,
- 'find': 1,
- 'findFrom': 1,
- 'findIndex': 1,
- 'findIndexFrom': 1,
- 'findKey': 1,
- 'findLast': 1,
- 'findLastFrom': 1,
- 'findLastIndex': 1,
- 'findLastIndexFrom': 1,
- 'findLastKey': 1,
- 'flatMap': 1,
- 'flatMapDeep': 1,
- 'flatMapDepth': 1,
- 'forEach': 1,
- 'forEachRight': 1,
- 'forIn': 1,
- 'forInRight': 1,
- 'forOwn': 1,
- 'forOwnRight': 1,
- 'map': 1,
- 'mapKeys': 1,
- 'mapValues': 1,
- 'partition': 1,
- 'reduce': 2,
- 'reduceRight': 2,
- 'reject': 1,
- 'remove': 1,
- 'some': 1,
- 'takeRightWhile': 1,
- 'takeWhile': 1,
- 'times': 1,
- 'transform': 2
- };
-
- /** Used to map method names to iteratee rearg configs. */
- exports.iterateeRearg = {
- 'mapKeys': [1],
- 'reduceRight': [1, 0]
- };
-
- /** Used to map method names to rearg configs. */
- exports.methodRearg = {
- 'assignInAllWith': [1, 0],
- 'assignInWith': [1, 2, 0],
- 'assignAllWith': [1, 0],
- 'assignWith': [1, 2, 0],
- 'differenceBy': [1, 2, 0],
- 'differenceWith': [1, 2, 0],
- 'getOr': [2, 1, 0],
- 'intersectionBy': [1, 2, 0],
- 'intersectionWith': [1, 2, 0],
- 'isEqualWith': [1, 2, 0],
- 'isMatchWith': [2, 1, 0],
- 'mergeAllWith': [1, 0],
- 'mergeWith': [1, 2, 0],
- 'padChars': [2, 1, 0],
- 'padCharsEnd': [2, 1, 0],
- 'padCharsStart': [2, 1, 0],
- 'pullAllBy': [2, 1, 0],
- 'pullAllWith': [2, 1, 0],
- 'rangeStep': [1, 2, 0],
- 'rangeStepRight': [1, 2, 0],
- 'setWith': [3, 1, 2, 0],
- 'sortedIndexBy': [2, 1, 0],
- 'sortedLastIndexBy': [2, 1, 0],
- 'unionBy': [1, 2, 0],
- 'unionWith': [1, 2, 0],
- 'updateWith': [3, 1, 2, 0],
- 'xorBy': [1, 2, 0],
- 'xorWith': [1, 2, 0],
- 'zipWith': [1, 2, 0]
- };
-
- /** Used to map method names to spread configs. */
- exports.methodSpread = {
- 'assignAll': { 'start': 0 },
- 'assignAllWith': { 'start': 0 },
- 'assignInAll': { 'start': 0 },
- 'assignInAllWith': { 'start': 0 },
- 'defaultsAll': { 'start': 0 },
- 'defaultsDeepAll': { 'start': 0 },
- 'invokeArgs': { 'start': 2 },
- 'invokeArgsMap': { 'start': 2 },
- 'mergeAll': { 'start': 0 },
- 'mergeAllWith': { 'start': 0 },
- 'partial': { 'start': 1 },
- 'partialRight': { 'start': 1 },
- 'without': { 'start': 1 },
- 'zipAll': { 'start': 0 }
- };
-
- /** Used to identify methods which mutate arrays or objects. */
- exports.mutate = {
- 'array': {
- 'fill': true,
- 'pull': true,
- 'pullAll': true,
- 'pullAllBy': true,
- 'pullAllWith': true,
- 'pullAt': true,
- 'remove': true,
- 'reverse': true
- },
- 'object': {
- 'assign': true,
- 'assignAll': true,
- 'assignAllWith': true,
- 'assignIn': true,
- 'assignInAll': true,
- 'assignInAllWith': true,
- 'assignInWith': true,
- 'assignWith': true,
- 'defaults': true,
- 'defaultsAll': true,
- 'defaultsDeep': true,
- 'defaultsDeepAll': true,
- 'merge': true,
- 'mergeAll': true,
- 'mergeAllWith': true,
- 'mergeWith': true,
- },
- 'set': {
- 'set': true,
- 'setWith': true,
- 'unset': true,
- 'update': true,
- 'updateWith': true
- }
- };
-
- /** Used to map real names to their aliases. */
- exports.realToAlias = (function() {
- var hasOwnProperty = Object.prototype.hasOwnProperty,
- object = exports.aliasToReal,
- result = {};
-
- for (var key in object) {
- var value = object[key];
- if (hasOwnProperty.call(result, value)) {
- result[value].push(key);
- } else {
- result[value] = [key];
- }
- }
- return result;
- }());
-
- /** Used to map method names to other names. */
- exports.remap = {
- 'assignAll': 'assign',
- 'assignAllWith': 'assignWith',
- 'assignInAll': 'assignIn',
- 'assignInAllWith': 'assignInWith',
- 'curryN': 'curry',
- 'curryRightN': 'curryRight',
- 'defaultsAll': 'defaults',
- 'defaultsDeepAll': 'defaultsDeep',
- 'findFrom': 'find',
- 'findIndexFrom': 'findIndex',
- 'findLastFrom': 'findLast',
- 'findLastIndexFrom': 'findLastIndex',
- 'getOr': 'get',
- 'includesFrom': 'includes',
- 'indexOfFrom': 'indexOf',
- 'invokeArgs': 'invoke',
- 'invokeArgsMap': 'invokeMap',
- 'lastIndexOfFrom': 'lastIndexOf',
- 'mergeAll': 'merge',
- 'mergeAllWith': 'mergeWith',
- 'padChars': 'pad',
- 'padCharsEnd': 'padEnd',
- 'padCharsStart': 'padStart',
- 'propertyOf': 'get',
- 'rangeStep': 'range',
- 'rangeStepRight': 'rangeRight',
- 'restFrom': 'rest',
- 'spreadFrom': 'spread',
- 'trimChars': 'trim',
- 'trimCharsEnd': 'trimEnd',
- 'trimCharsStart': 'trimStart',
- 'zipAll': 'zip'
- };
-
- /** Used to track methods that skip fixing their arity. */
- exports.skipFixed = {
- 'castArray': true,
- 'flow': true,
- 'flowRight': true,
- 'iteratee': true,
- 'mixin': true,
- 'rearg': true,
- 'runInContext': true
- };
-
- /** Used to track methods that skip rearranging arguments. */
- exports.skipRearg = {
- 'add': true,
- 'assign': true,
- 'assignIn': true,
- 'bind': true,
- 'bindKey': true,
- 'concat': true,
- 'difference': true,
- 'divide': true,
- 'eq': true,
- 'gt': true,
- 'gte': true,
- 'isEqual': true,
- 'lt': true,
- 'lte': true,
- 'matchesProperty': true,
- 'merge': true,
- 'multiply': true,
- 'overArgs': true,
- 'partial': true,
- 'partialRight': true,
- 'propertyOf': true,
- 'random': true,
- 'range': true,
- 'rangeRight': true,
- 'subtract': true,
- 'zip': true,
- 'zipObject': true,
- 'zipObjectDeep': true
- };
- }, "/$$rollup_base$$/node_modules/lodash/fp");
-
- /**
- * The default argument placeholder value for methods.
- *
- * @type {Object}
- */
- var placeholder = {};
-
- /** Built-in value reference. */
- var push = Array.prototype.push;
-
- /**
- * Creates a function, with an arity of `n`, that invokes `func` with the
- * arguments it receives.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {number} n The arity of the new function.
- * @returns {Function} Returns the new function.
- */
- function baseArity(func, n) {
- return n == 2
- ? function(a, b) { return func.apply(undefined, arguments); }
- : function(a) { return func.apply(undefined, arguments); };
- }
-
- /**
- * Creates a function that invokes `func`, with up to `n` arguments, ignoring
- * any additional arguments.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @param {number} n The arity cap.
- * @returns {Function} Returns the new function.
- */
- function baseAry(func, n) {
- return n == 2
- ? function(a, b) { return func(a, b); }
- : function(a) { return func(a); };
- }
-
- /**
- * Creates a clone of `array`.
- *
- * @private
- * @param {Array} array The array to clone.
- * @returns {Array} Returns the cloned array.
- */
- function cloneArray(array) {
- var length = array ? array.length : 0,
- result = Array(length);
-
- while (length--) {
- result[length] = array[length];
- }
- return result;
- }
-
- /**
- * Creates a function that clones a given object using the assignment `func`.
- *
- * @private
- * @param {Function} func The assignment function.
- * @returns {Function} Returns the new cloner function.
- */
- function createCloner(func) {
- return function(object) {
- return func({}, object);
- };
- }
-
- /**
- * A specialized version of `_.spread` which flattens the spread array into
- * the arguments of the invoked `func`.
- *
- * @private
- * @param {Function} func The function to spread arguments over.
- * @param {number} start The start position of the spread.
- * @returns {Function} Returns the new function.
- */
- function flatSpread(func, start) {
- return function() {
- var length = arguments.length,
- lastIndex = length - 1,
- args = Array(length);
-
- while (length--) {
- args[length] = arguments[length];
- }
- var array = args[start],
- otherArgs = args.slice(0, start);
-
- if (array) {
- push.apply(otherArgs, array);
- }
- if (start != lastIndex) {
- push.apply(otherArgs, args.slice(start + 1));
- }
- return func.apply(this, otherArgs);
- };
- }
-
- /**
- * Creates a function that wraps `func` and uses `cloner` to clone the first
- * argument it receives.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} cloner The function to clone arguments.
- * @returns {Function} Returns the new immutable function.
- */
- function wrapImmutable(func, cloner) {
- return function() {
- var length = arguments.length;
- if (!length) {
- return;
- }
- var args = Array(length);
- while (length--) {
- args[length] = arguments[length];
- }
- var result = args[0] = cloner.apply(undefined, args);
- func.apply(undefined, args);
- return result;
- };
- }
-
- /**
- * The base implementation of `convert` which accepts a `util` object of methods
- * required to perform conversions.
- *
- * @param {Object} util The util object.
- * @param {string} name The name of the function to convert.
- * @param {Function} func The function to convert.
- * @param {Object} [options] The options object.
- * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
- * @param {boolean} [options.curry=true] Specify currying.
- * @param {boolean} [options.fixed=true] Specify fixed arity.
- * @param {boolean} [options.immutable=true] Specify immutable operations.
- * @param {boolean} [options.rearg=true] Specify rearranging arguments.
- * @returns {Function|Object} Returns the converted function or object.
- */
- function baseConvert(util, name, func, options) {
- var isLib = typeof name == 'function',
- isObj = name === Object(name);
-
- if (isObj) {
- options = func;
- func = name;
- name = undefined;
- }
- if (func == null) {
- throw new TypeError;
- }
- options || (options = {});
-
- var config = {
- 'cap': 'cap' in options ? options.cap : true,
- 'curry': 'curry' in options ? options.curry : true,
- 'fixed': 'fixed' in options ? options.fixed : true,
- 'immutable': 'immutable' in options ? options.immutable : true,
- 'rearg': 'rearg' in options ? options.rearg : true
- };
-
- var defaultHolder = isLib ? func : placeholder,
- forceCurry = ('curry' in options) && options.curry,
- forceFixed = ('fixed' in options) && options.fixed,
- forceRearg = ('rearg' in options) && options.rearg,
- pristine = isLib ? func.runInContext() : undefined;
-
- var helpers = isLib ? func : {
- 'ary': util.ary,
- 'assign': util.assign,
- 'clone': util.clone,
- 'curry': util.curry,
- 'forEach': util.forEach,
- 'isArray': util.isArray,
- 'isError': util.isError,
- 'isFunction': util.isFunction,
- 'isWeakMap': util.isWeakMap,
- 'iteratee': util.iteratee,
- 'keys': util.keys,
- 'rearg': util.rearg,
- 'toInteger': util.toInteger,
- 'toPath': util.toPath
- };
-
- var ary = helpers.ary,
- assign = helpers.assign,
- clone = helpers.clone,
- curry = helpers.curry,
- each = helpers.forEach,
- isArray = helpers.isArray,
- isError = helpers.isError,
- isFunction = helpers.isFunction,
- isWeakMap = helpers.isWeakMap,
- keys = helpers.keys,
- rearg = helpers.rearg,
- toInteger = helpers.toInteger,
- toPath = helpers.toPath;
-
- var aryMethodKeys = keys(_mapping.aryMethod);
-
- var wrappers = {
- 'castArray': function(castArray) {
- return function() {
- var value = arguments[0];
- return isArray(value)
- ? castArray(cloneArray(value))
- : castArray.apply(undefined, arguments);
- };
- },
- 'iteratee': function(iteratee) {
- return function() {
- var func = arguments[0],
- arity = arguments[1],
- result = iteratee(func, arity),
- length = result.length;
-
- if (config.cap && typeof arity == 'number') {
- arity = arity > 2 ? (arity - 2) : 1;
- return (length && length <= arity) ? result : baseAry(result, arity);
- }
- return result;
- };
- },
- 'mixin': function(mixin) {
- return function(source) {
- var func = this;
- if (!isFunction(func)) {
- return mixin(func, Object(source));
- }
- var pairs = [];
- each(keys(source), function(key) {
- if (isFunction(source[key])) {
- pairs.push([key, func.prototype[key]]);
- }
- });
-
- mixin(func, Object(source));
-
- each(pairs, function(pair) {
- var value = pair[1];
- if (isFunction(value)) {
- func.prototype[pair[0]] = value;
- } else {
- delete func.prototype[pair[0]];
- }
- });
- return func;
- };
- },
- 'nthArg': function(nthArg) {
- return function(n) {
- var arity = n < 0 ? 1 : (toInteger(n) + 1);
- return curry(nthArg(n), arity);
- };
- },
- 'rearg': function(rearg) {
- return function(func, indexes) {
- var arity = indexes ? indexes.length : 0;
- return curry(rearg(func, indexes), arity);
- };
- },
- 'runInContext': function(runInContext) {
- return function(context) {
- return baseConvert(util, runInContext(context), options);
- };
- }
- };
-
- /*--------------------------------------------------------------------------*/
-
- /**
- * Casts `func` to a function with an arity capped iteratee if needed.
- *
- * @private
- * @param {string} name The name of the function to inspect.
- * @param {Function} func The function to inspect.
- * @returns {Function} Returns the cast function.
- */
- function castCap(name, func) {
- if (config.cap) {
- var indexes = _mapping.iterateeRearg[name];
- if (indexes) {
- return iterateeRearg(func, indexes);
- }
- var n = !isLib && _mapping.iterateeAry[name];
- if (n) {
- return iterateeAry(func, n);
- }
- }
- return func;
- }
-
- /**
- * Casts `func` to a curried function if needed.
- *
- * @private
- * @param {string} name The name of the function to inspect.
- * @param {Function} func The function to inspect.
- * @param {number} n The arity of `func`.
- * @returns {Function} Returns the cast function.
- */
- function castCurry(name, func, n) {
- return (forceCurry || (config.curry && n > 1))
- ? curry(func, n)
- : func;
- }
-
- /**
- * Casts `func` to a fixed arity function if needed.
- *
- * @private
- * @param {string} name The name of the function to inspect.
- * @param {Function} func The function to inspect.
- * @param {number} n The arity cap.
- * @returns {Function} Returns the cast function.
- */
- function castFixed(name, func, n) {
- if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
- var data = _mapping.methodSpread[name],
- start = data && data.start;
-
- return start === undefined ? ary(func, n) : flatSpread(func, start);
- }
- return func;
- }
-
- /**
- * Casts `func` to an rearged function if needed.
- *
- * @private
- * @param {string} name The name of the function to inspect.
- * @param {Function} func The function to inspect.
- * @param {number} n The arity of `func`.
- * @returns {Function} Returns the cast function.
- */
- function castRearg(name, func, n) {
- return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
- ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
- : func;
- }
-
- /**
- * Creates a clone of `object` by `path`.
- *
- * @private
- * @param {Object} object The object to clone.
- * @param {Array|string} path The path to clone by.
- * @returns {Object} Returns the cloned object.
- */
- function cloneByPath(object, path) {
- path = toPath(path);
-
- var index = -1,
- length = path.length,
- lastIndex = length - 1,
- result = clone(Object(object)),
- nested = result;
-
- while (nested != null && ++index < length) {
- var key = path[index],
- value = nested[key];
-
- if (value != null &&
- !(isFunction(value) || isError(value) || isWeakMap(value))) {
- nested[key] = clone(index == lastIndex ? value : Object(value));
- }
- nested = nested[key];
- }
- return result;
- }
-
- /**
- * Converts `lodash` to an immutable auto-curried iteratee-first data-last
- * version with conversion `options` applied.
- *
- * @param {Object} [options] The options object. See `baseConvert` for more details.
- * @returns {Function} Returns the converted `lodash`.
- */
- function convertLib(options) {
- return _.runInContext.convert(options)(undefined);
- }
-
- /**
- * Create a converter function for `func` of `name`.
- *
- * @param {string} name The name of the function to convert.
- * @param {Function} func The function to convert.
- * @returns {Function} Returns the new converter function.
- */
- function createConverter(name, func) {
- var realName = _mapping.aliasToReal[name] || name,
- methodName = _mapping.remap[realName] || realName,
- oldOptions = options;
-
- return function(options) {
- var newUtil = isLib ? pristine : helpers,
- newFunc = isLib ? pristine[methodName] : func,
- newOptions = assign(assign({}, oldOptions), options);
-
- return baseConvert(newUtil, realName, newFunc, newOptions);
- };
- }
-
- /**
- * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
- * arguments, ignoring any additional arguments.
- *
- * @private
- * @param {Function} func The function to cap iteratee arguments for.
- * @param {number} n The arity cap.
- * @returns {Function} Returns the new function.
- */
- function iterateeAry(func, n) {
- return overArg(func, function(func) {
- return typeof func == 'function' ? baseAry(func, n) : func;
- });
- }
-
- /**
- * Creates a function that wraps `func` to invoke its iteratee with arguments
- * arranged according to the specified `indexes` where the argument value at
- * the first index is provided as the first argument, the argument value at
- * the second index is provided as the second argument, and so on.
- *
- * @private
- * @param {Function} func The function to rearrange iteratee arguments for.
- * @param {number[]} indexes The arranged argument indexes.
- * @returns {Function} Returns the new function.
- */
- function iterateeRearg(func, indexes) {
- return overArg(func, function(func) {
- var n = indexes.length;
- return baseArity(rearg(baseAry(func, n), indexes), n);
- });
- }
-
- /**
- * Creates a function that invokes `func` with its first argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
- */
- function overArg(func, transform) {
- return function() {
- var length = arguments.length;
- if (!length) {
- return func();
- }
- var args = Array(length);
- while (length--) {
- args[length] = arguments[length];
- }
- var index = config.rearg ? 0 : (length - 1);
- args[index] = transform(args[index]);
- return func.apply(undefined, args);
- };
- }
-
- /**
- * Creates a function that wraps `func` and applys the conversions
- * rules by `name`.
- *
- * @private
- * @param {string} name The name of the function to wrap.
- * @param {Function} func The function to wrap.
- * @returns {Function} Returns the converted function.
- */
- function wrap(name, func, placeholder) {
- var result,
- realName = _mapping.aliasToReal[name] || name,
- wrapped = func,
- wrapper = wrappers[realName];
-
- if (wrapper) {
- wrapped = wrapper(func);
- }
- else if (config.immutable) {
- if (_mapping.mutate.array[realName]) {
- wrapped = wrapImmutable(func, cloneArray);
- }
- else if (_mapping.mutate.object[realName]) {
- wrapped = wrapImmutable(func, createCloner(func));
- }
- else if (_mapping.mutate.set[realName]) {
- wrapped = wrapImmutable(func, cloneByPath);
- }
- }
- each(aryMethodKeys, function(aryKey) {
- each(_mapping.aryMethod[aryKey], function(otherName) {
- if (realName == otherName) {
- var data = _mapping.methodSpread[realName],
- afterRearg = data && data.afterRearg;
-
- result = afterRearg
- ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
- : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
-
- result = castCap(realName, result);
- result = castCurry(realName, result, aryKey);
- return false;
- }
- });
- return !result;
- });
-
- result || (result = wrapped);
- if (result == func) {
- result = forceCurry ? curry(result, 1) : function() {
- return func.apply(this, arguments);
- };
- }
- result.convert = createConverter(realName, func);
- result.placeholder = func.placeholder = placeholder;
-
- return result;
- }
-
- /*--------------------------------------------------------------------------*/
-
- if (!isObj) {
- return wrap(name, func, defaultHolder);
- }
- var _ = func;
-
- // Convert methods by ary cap.
- var pairs = [];
- each(aryMethodKeys, function(aryKey) {
- each(_mapping.aryMethod[aryKey], function(key) {
- var func = _[_mapping.remap[key] || key];
- if (func) {
- pairs.push([key, wrap(key, func, _)]);
- }
- });
- });
-
- // Convert remaining methods.
- each(keys(_), function(key) {
- var func = _[key];
- if (typeof func == 'function') {
- var length = pairs.length;
- while (length--) {
- if (pairs[length][0] == key) {
- return;
- }
- }
- func.convert = createConverter(key, func);
- pairs.push([key, func]);
- }
- });
-
- // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
- each(pairs, function(pair) {
- _[pair[0]] = pair[1];
- });
-
- _.convert = convertLib;
- _.placeholder = _;
-
- // Assign aliases.
- each(keys(_), function(key) {
- each(_mapping.realToAlias[key] || [], function(alias) {
- _[alias] = _[key];
- });
- });
-
- return _;
- }
-
- var _baseConvert = baseConvert;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_ARY_FLAG = 128;
-
- /**
- * Creates a function that invokes `func`, with up to `n` arguments,
- * ignoring any additional arguments.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Function
- * @param {Function} func The function to cap arguments for.
- * @param {number} [n=func.length] The arity cap.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {Function} Returns the new capped function.
- * @example
- *
- * _.map(['6', '8', '10'], _.ary(parseInt, 1));
- * // => [6, 8, 10]
- */
- function ary(func, n, guard) {
- n = guard ? undefined : n;
- n = (func && n == null) ? func.length : n;
- return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
- }
-
- var ary_1 = ary;
-
- /**
- * The base implementation of `assignValue` and `assignMergeValue` without
- * value checks.
- *
- * @private
- * @param {Object} object The object to modify.
- * @param {string} key The key of the property to assign.
- * @param {*} value The value to assign.
- */
- function baseAssignValue(object, key, value) {
- if (key == '__proto__' && _defineProperty) {
- _defineProperty(object, key, {
- 'configurable': true,
- 'enumerable': true,
- 'value': value,
- 'writable': true
- });
- } else {
- object[key] = value;
- }
- }
-
- var _baseAssignValue = baseAssignValue;
-
- /**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
- function eq(value, other) {
- return value === other || (value !== value && other !== other);
- }
-
- var eq_1 = eq;
-
- /** Used for built-in method references. */
- var objectProto$c = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$a = objectProto$c.hasOwnProperty;
-
- /**
- * Assigns `value` to `key` of `object` if the existing value is not equivalent
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * for equality comparisons.
- *
- * @private
- * @param {Object} object The object to modify.
- * @param {string} key The key of the property to assign.
- * @param {*} value The value to assign.
- */
- function assignValue(object, key, value) {
- var objValue = object[key];
- if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
- (value === undefined && !(key in object))) {
- _baseAssignValue(object, key, value);
- }
- }
-
- var _assignValue = assignValue;
-
- /**
- * Copies properties of `source` to `object`.
- *
- * @private
- * @param {Object} source The object to copy properties from.
- * @param {Array} props The property identifiers to copy.
- * @param {Object} [object={}] The object to copy properties to.
- * @param {Function} [customizer] The function to customize copied values.
- * @returns {Object} Returns `object`.
- */
- function copyObject(source, props, object, customizer) {
- var isNew = !object;
- object || (object = {});
-
- var index = -1,
- length = props.length;
-
- while (++index < length) {
- var key = props[index];
-
- var newValue = customizer
- ? customizer(object[key], source[key], key, object, source)
- : undefined;
-
- if (newValue === undefined) {
- newValue = source[key];
- }
- if (isNew) {
- _baseAssignValue(object, key, newValue);
- } else {
- _assignValue(object, key, newValue);
- }
- }
- return object;
- }
-
- var _copyObject = copyObject;
-
- /**
- * The base implementation of `_.times` without support for iteratee shorthands
- * or max array length checks.
- *
- * @private
- * @param {number} n The number of times to invoke `iteratee`.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the array of results.
- */
- function baseTimes(n, iteratee) {
- var index = -1,
- result = Array(n);
-
- while (++index < n) {
- result[index] = iteratee(index);
- }
- return result;
- }
-
- var _baseTimes = baseTimes;
-
- /** `Object#toString` result references. */
- var argsTag$3 = '[object Arguments]';
-
- /**
- * The base implementation of `_.isArguments`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- */
- function baseIsArguments(value) {
- return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
- }
-
- var _baseIsArguments = baseIsArguments;
-
- /** Used for built-in method references. */
- var objectProto$b = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
-
- /** Built-in value references. */
- var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
-
- /**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
- var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
- return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
- !propertyIsEnumerable$1.call(value, 'callee');
- };
-
- var isArguments_1 = isArguments;
-
- /**
- * This method returns `false`.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {boolean} Returns `false`.
- * @example
- *
- * _.times(2, _.stubFalse);
- * // => [false, false]
- */
- function stubFalse() {
- return false;
- }
-
- var stubFalse_1 = stubFalse;
-
- var isBuffer_1 = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
-
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
-
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
-
- /** Built-in value references. */
- var Buffer = moduleExports ? _root.Buffer : undefined;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
-
- /**
- * Checks if `value` is a buffer.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
- * @example
- *
- * _.isBuffer(new Buffer(2));
- * // => true
- *
- * _.isBuffer(new Uint8Array(2));
- * // => false
- */
- var isBuffer = nativeIsBuffer || stubFalse_1;
-
- module.exports = isBuffer;
- }, "/$$rollup_base$$/node_modules/lodash");
-
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER = 9007199254740991;
-
- /**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
- function isLength(value) {
- return typeof value == 'number' &&
- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
- }
-
- var isLength_1 = isLength;
-
- /** `Object#toString` result references. */
- var argsTag$2 = '[object Arguments]',
- arrayTag$2 = '[object Array]',
- boolTag$3 = '[object Boolean]',
- dateTag$3 = '[object Date]',
- errorTag$3 = '[object Error]',
- funcTag$1 = '[object Function]',
- mapTag$5 = '[object Map]',
- numberTag$3 = '[object Number]',
- objectTag$4 = '[object Object]',
- regexpTag$3 = '[object RegExp]',
- setTag$5 = '[object Set]',
- stringTag$3 = '[object String]',
- weakMapTag$3 = '[object WeakMap]';
-
- var arrayBufferTag$3 = '[object ArrayBuffer]',
- dataViewTag$4 = '[object DataView]',
- float32Tag$2 = '[object Float32Array]',
- float64Tag$2 = '[object Float64Array]',
- int8Tag$2 = '[object Int8Array]',
- int16Tag$2 = '[object Int16Array]',
- int32Tag$2 = '[object Int32Array]',
- uint8Tag$2 = '[object Uint8Array]',
- uint8ClampedTag$2 = '[object Uint8ClampedArray]',
- uint16Tag$2 = '[object Uint16Array]',
- uint32Tag$2 = '[object Uint32Array]';
-
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
- typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
- typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
- typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
- typedArrayTags[uint32Tag$2] = true;
- typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
- typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
- typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
- typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
- typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
- typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
- typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
- typedArrayTags[weakMapTag$3] = false;
-
- /**
- * The base implementation of `_.isTypedArray` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- */
- function baseIsTypedArray(value) {
- return isObjectLike_1(value) &&
- isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
- }
-
- var _baseIsTypedArray = baseIsTypedArray;
-
- /**
- * The base implementation of `_.unary` without support for storing metadata.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @returns {Function} Returns the new capped function.
- */
- function baseUnary(func) {
- return function(value) {
- return func(value);
- };
- }
-
- var _baseUnary = baseUnary;
-
- var _nodeUtil = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
-
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
-
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
-
- /** Detect free variable `process` from Node.js. */
- var freeProcess = moduleExports && _freeGlobal.process;
-
- /** Used to access faster Node.js helpers. */
- var nodeUtil = (function() {
- try {
- // Use `util.types` for Node.js 10+.
- var types = freeModule && freeModule.require && freeModule.require('util').types;
-
- if (types) {
- return types;
- }
-
- // Legacy `process.binding('util')` for Node.js < 10.
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
- } catch (e) {}
- }());
-
- module.exports = nodeUtil;
- }, "/$$rollup_base$$/node_modules/lodash");
-
- /* Node.js helper references. */
- var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
-
- /**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
- */
- var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
-
- var isTypedArray_1 = isTypedArray;
-
- /** Used for built-in method references. */
- var objectProto$a = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
-
- /**
- * Creates an array of the enumerable property names of the array-like `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @param {boolean} inherited Specify returning inherited property names.
- * @returns {Array} Returns the array of property names.
- */
- function arrayLikeKeys(value, inherited) {
- var isArr = isArray_1(value),
- isArg = !isArr && isArguments_1(value),
- isBuff = !isArr && !isArg && isBuffer_1(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? _baseTimes(value.length, String) : [],
- length = result.length;
-
- for (var key in value) {
- if ((inherited || hasOwnProperty$8.call(value, key)) &&
- !(skipIndexes && (
- // Safari 9 has enumerable `arguments.length` in strict mode.
- key == 'length' ||
- // Node.js 0.10 has enumerable non-index properties on buffers.
- (isBuff && (key == 'offset' || key == 'parent')) ||
- // PhantomJS 2 has enumerable non-index properties on typed arrays.
- (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
- // Skip index properties.
- _isIndex(key, length)
- ))) {
- result.push(key);
- }
- }
- return result;
- }
-
- var _arrayLikeKeys = arrayLikeKeys;
-
- /** Used for built-in method references. */
- var objectProto$9 = Object.prototype;
-
- /**
- * Checks if `value` is likely a prototype object.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
- */
- function isPrototype(value) {
- var Ctor = value && value.constructor,
- proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
-
- return value === proto;
- }
-
- var _isPrototype = isPrototype;
-
- /**
- * Creates a unary function that invokes `func` with its argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
- */
- function overArg(func, transform) {
- return function(arg) {
- return func(transform(arg));
- };
- }
-
- var _overArg = overArg;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeKeys = _overArg(Object.keys, Object);
-
- var _nativeKeys = nativeKeys;
-
- /** Used for built-in method references. */
- var objectProto$8 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
-
- /**
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function baseKeys(object) {
- if (!_isPrototype(object)) {
- return _nativeKeys(object);
- }
- var result = [];
- for (var key in Object(object)) {
- if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
-
- var _baseKeys = baseKeys;
-
- /**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
- function isArrayLike(value) {
- return value != null && isLength_1(value.length) && !isFunction_1(value);
- }
-
- var isArrayLike_1 = isArrayLike;
-
- /**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
- function keys(object) {
- return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
- }
-
- var keys_1 = keys;
-
- /**
- * The base implementation of `_.assign` without support for multiple sources
- * or `customizer` functions.
- *
- * @private
- * @param {Object} object The destination object.
- * @param {Object} source The source object.
- * @returns {Object} Returns `object`.
- */
- function baseAssign(object, source) {
- return object && _copyObject(source, keys_1(source), object);
- }
-
- var _baseAssign = baseAssign;
-
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
- }
-
- var _listCacheClear = listCacheClear;
-
- /**
- * Gets the index at which the `key` is found in `array` of key-value pairs.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} key The key to search for.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function assocIndexOf(array, key) {
- var length = array.length;
- while (length--) {
- if (eq_1(array[length][0], key)) {
- return length;
- }
- }
- return -1;
- }
-
- var _assocIndexOf = assocIndexOf;
-
- /** Used for built-in method references. */
- var arrayProto = Array.prototype;
-
- /** Built-in value references. */
- var splice = arrayProto.splice;
-
- /**
- * Removes `key` and its value from the list cache.
- *
- * @private
- * @name delete
- * @memberOf ListCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function listCacheDelete(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
-
- if (index < 0) {
- return false;
- }
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
- --this.size;
- return true;
- }
-
- var _listCacheDelete = listCacheDelete;
-
- /**
- * Gets the list cache value for `key`.
- *
- * @private
- * @name get
- * @memberOf ListCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function listCacheGet(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
-
- return index < 0 ? undefined : data[index][1];
- }
-
- var _listCacheGet = listCacheGet;
-
- /**
- * Checks if a list cache value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf ListCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function listCacheHas(key) {
- return _assocIndexOf(this.__data__, key) > -1;
- }
-
- var _listCacheHas = listCacheHas;
-
- /**
- * Sets the list cache `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf ListCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the list cache instance.
- */
- function listCacheSet(key, value) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
-
- if (index < 0) {
- ++this.size;
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
- return this;
- }
-
- var _listCacheSet = listCacheSet;
-
- /**
- * Creates an list cache object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function ListCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
-
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
-
- // Add methods to `ListCache`.
- ListCache.prototype.clear = _listCacheClear;
- ListCache.prototype['delete'] = _listCacheDelete;
- ListCache.prototype.get = _listCacheGet;
- ListCache.prototype.has = _listCacheHas;
- ListCache.prototype.set = _listCacheSet;
-
- var _ListCache = ListCache;
-
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new _ListCache;
- this.size = 0;
- }
-
- var _stackClear = stackClear;
-
- /**
- * Removes `key` and its value from the stack.
- *
- * @private
- * @name delete
- * @memberOf Stack
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function stackDelete(key) {
- var data = this.__data__,
- result = data['delete'](key);
-
- this.size = data.size;
- return result;
- }
-
- var _stackDelete = stackDelete;
-
- /**
- * Gets the stack value for `key`.
- *
- * @private
- * @name get
- * @memberOf Stack
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function stackGet(key) {
- return this.__data__.get(key);
- }
-
- var _stackGet = stackGet;
-
- /**
- * Checks if a stack value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Stack
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function stackHas(key) {
- return this.__data__.has(key);
- }
-
- var _stackHas = stackHas;
-
- /* Built-in method references that are verified to be native. */
- var Map$1 = _getNative(_root, 'Map');
-
- var _Map = Map$1;
-
- /* Built-in method references that are verified to be native. */
- var nativeCreate = _getNative(Object, 'create');
-
- var _nativeCreate = nativeCreate;
-
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
- this.size = 0;
- }
-
- var _hashClear = hashClear;
-
- /**
- * Removes `key` and its value from the hash.
- *
- * @private
- * @name delete
- * @memberOf Hash
- * @param {Object} hash The hash to modify.
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function hashDelete(key) {
- var result = this.has(key) && delete this.__data__[key];
- this.size -= result ? 1 : 0;
- return result;
- }
-
- var _hashDelete = hashDelete;
-
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
-
- /** Used for built-in method references. */
- var objectProto$7 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
-
- /**
- * Gets the hash value for `key`.
- *
- * @private
- * @name get
- * @memberOf Hash
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function hashGet(key) {
- var data = this.__data__;
- if (_nativeCreate) {
- var result = data[key];
- return result === HASH_UNDEFINED$2 ? undefined : result;
- }
- return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
- }
-
- var _hashGet = hashGet;
-
- /** Used for built-in method references. */
- var objectProto$6 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
-
- /**
- * Checks if a hash value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Hash
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function hashHas(key) {
- var data = this.__data__;
- return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
- }
-
- var _hashHas = hashHas;
-
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
-
- /**
- * Sets the hash `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Hash
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the hash instance.
- */
- function hashSet(key, value) {
- var data = this.__data__;
- this.size += this.has(key) ? 0 : 1;
- data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
- return this;
- }
-
- var _hashSet = hashSet;
-
- /**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Hash(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
-
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
-
- // Add methods to `Hash`.
- Hash.prototype.clear = _hashClear;
- Hash.prototype['delete'] = _hashDelete;
- Hash.prototype.get = _hashGet;
- Hash.prototype.has = _hashHas;
- Hash.prototype.set = _hashSet;
-
- var _Hash = Hash;
-
- /**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
- function mapCacheClear() {
- this.size = 0;
- this.__data__ = {
- 'hash': new _Hash,
- 'map': new (_Map || _ListCache),
- 'string': new _Hash
- };
- }
-
- var _mapCacheClear = mapCacheClear;
-
- /**
- * Checks if `value` is suitable for use as unique object key.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
- */
- function isKeyable(value) {
- var type = typeof value;
- return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
- ? (value !== '__proto__')
- : (value === null);
- }
-
- var _isKeyable = isKeyable;
-
- /**
- * Gets the data for `map`.
- *
- * @private
- * @param {Object} map The map to query.
- * @param {string} key The reference key.
- * @returns {*} Returns the map data.
- */
- function getMapData(map, key) {
- var data = map.__data__;
- return _isKeyable(key)
- ? data[typeof key == 'string' ? 'string' : 'hash']
- : data.map;
- }
-
- var _getMapData = getMapData;
-
- /**
- * Removes `key` and its value from the map.
- *
- * @private
- * @name delete
- * @memberOf MapCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function mapCacheDelete(key) {
- var result = _getMapData(this, key)['delete'](key);
- this.size -= result ? 1 : 0;
- return result;
- }
-
- var _mapCacheDelete = mapCacheDelete;
-
- /**
- * Gets the map value for `key`.
- *
- * @private
- * @name get
- * @memberOf MapCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function mapCacheGet(key) {
- return _getMapData(this, key).get(key);
- }
-
- var _mapCacheGet = mapCacheGet;
-
- /**
- * Checks if a map value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf MapCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function mapCacheHas(key) {
- return _getMapData(this, key).has(key);
- }
-
- var _mapCacheHas = mapCacheHas;
-
- /**
- * Sets the map `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf MapCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the map cache instance.
- */
- function mapCacheSet(key, value) {
- var data = _getMapData(this, key),
- size = data.size;
-
- data.set(key, value);
- this.size += data.size == size ? 0 : 1;
- return this;
- }
-
- var _mapCacheSet = mapCacheSet;
-
- /**
- * Creates a map cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function MapCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
-
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
-
- // Add methods to `MapCache`.
- MapCache.prototype.clear = _mapCacheClear;
- MapCache.prototype['delete'] = _mapCacheDelete;
- MapCache.prototype.get = _mapCacheGet;
- MapCache.prototype.has = _mapCacheHas;
- MapCache.prototype.set = _mapCacheSet;
-
- var _MapCache = MapCache;
-
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE = 200;
-
- /**
- * Sets the stack `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Stack
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the stack cache instance.
- */
- function stackSet(key, value) {
- var data = this.__data__;
- if (data instanceof _ListCache) {
- var pairs = data.__data__;
- if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
- pairs.push([key, value]);
- this.size = ++data.size;
- return this;
- }
- data = this.__data__ = new _MapCache(pairs);
- }
- data.set(key, value);
- this.size = data.size;
- return this;
- }
-
- var _stackSet = stackSet;
-
- /**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Stack(entries) {
- var data = this.__data__ = new _ListCache(entries);
- this.size = data.size;
- }
-
- // Add methods to `Stack`.
- Stack.prototype.clear = _stackClear;
- Stack.prototype['delete'] = _stackDelete;
- Stack.prototype.get = _stackGet;
- Stack.prototype.has = _stackHas;
- Stack.prototype.set = _stackSet;
-
- var _Stack = Stack;
-
- /**
- * This function is like
- * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * except that it includes inherited enumerable properties.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function nativeKeysIn(object) {
- var result = [];
- if (object != null) {
- for (var key in Object(object)) {
- result.push(key);
- }
- }
- return result;
- }
-
- var _nativeKeysIn = nativeKeysIn;
-
- /** Used for built-in method references. */
- var objectProto$5 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
-
- /**
- * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function baseKeysIn(object) {
- if (!isObject_1(object)) {
- return _nativeKeysIn(object);
- }
- var isProto = _isPrototype(object),
- result = [];
-
- for (var key in object) {
- if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
- result.push(key);
- }
- }
- return result;
- }
-
- var _baseKeysIn = baseKeysIn;
-
- /**
- * Creates an array of the own and inherited enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keysIn(new Foo);
- * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
- */
- function keysIn(object) {
- return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
- }
-
- var keysIn_1 = keysIn;
-
- /**
- * The base implementation of `_.assignIn` without support for multiple sources
- * or `customizer` functions.
- *
- * @private
- * @param {Object} object The destination object.
- * @param {Object} source The source object.
- * @returns {Object} Returns `object`.
- */
- function baseAssignIn(object, source) {
- return object && _copyObject(source, keysIn_1(source), object);
- }
-
- var _baseAssignIn = baseAssignIn;
-
- var _cloneBuffer = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
-
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
-
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
-
- /** Built-in value references. */
- var Buffer = moduleExports ? _root.Buffer : undefined,
- allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
-
- /**
- * Creates a clone of `buffer`.
- *
- * @private
- * @param {Buffer} buffer The buffer to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Buffer} Returns the cloned buffer.
- */
- function cloneBuffer(buffer, isDeep) {
- if (isDeep) {
- return buffer.slice();
- }
- var length = buffer.length,
- result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
-
- buffer.copy(result);
- return result;
- }
-
- module.exports = cloneBuffer;
- }, "/$$rollup_base$$/node_modules/lodash");
-
- /**
- * A specialized version of `_.filter` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Array} Returns the new filtered array.
- */
- function arrayFilter(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length,
- resIndex = 0,
- result = [];
-
- while (++index < length) {
- var value = array[index];
- if (predicate(value, index, array)) {
- result[resIndex++] = value;
- }
- }
- return result;
- }
-
- var _arrayFilter = arrayFilter;
-
- /**
- * This method returns a new empty array.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {Array} Returns the new empty array.
- * @example
- *
- * var arrays = _.times(2, _.stubArray);
- *
- * console.log(arrays);
- * // => [[], []]
- *
- * console.log(arrays[0] === arrays[1]);
- * // => false
- */
- function stubArray() {
- return [];
- }
-
- var stubArray_1 = stubArray;
-
- /** Used for built-in method references. */
- var objectProto$4 = Object.prototype;
-
- /** Built-in value references. */
- var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
-
- /**
- * Creates an array of the own enumerable symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
- var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
- if (object == null) {
- return [];
- }
- object = Object(object);
- return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
- return propertyIsEnumerable.call(object, symbol);
- });
- };
-
- var _getSymbols = getSymbols;
-
- /**
- * Copies own symbols of `source` to `object`.
- *
- * @private
- * @param {Object} source The object to copy symbols from.
- * @param {Object} [object={}] The object to copy symbols to.
- * @returns {Object} Returns `object`.
- */
- function copySymbols(source, object) {
- return _copyObject(source, _getSymbols(source), object);
- }
-
- var _copySymbols = copySymbols;
-
- /**
- * Appends the elements of `values` to `array`.
- *
- * @private
- * @param {Array} array The array to modify.
- * @param {Array} values The values to append.
- * @returns {Array} Returns `array`.
- */
- function arrayPush(array, values) {
- var index = -1,
- length = values.length,
- offset = array.length;
-
- while (++index < length) {
- array[offset + index] = values[index];
- }
- return array;
- }
-
- var _arrayPush = arrayPush;
-
- /** Built-in value references. */
- var getPrototype = _overArg(Object.getPrototypeOf, Object);
-
- var _getPrototype = getPrototype;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols = Object.getOwnPropertySymbols;
-
- /**
- * Creates an array of the own and inherited enumerable symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
- var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
- var result = [];
- while (object) {
- _arrayPush(result, _getSymbols(object));
- object = _getPrototype(object);
- }
- return result;
- };
-
- var _getSymbolsIn = getSymbolsIn;
-
- /**
- * Copies own and inherited symbols of `source` to `object`.
- *
- * @private
- * @param {Object} source The object to copy symbols from.
- * @param {Object} [object={}] The object to copy symbols to.
- * @returns {Object} Returns `object`.
- */
- function copySymbolsIn(source, object) {
- return _copyObject(source, _getSymbolsIn(source), object);
- }
-
- var _copySymbolsIn = copySymbolsIn;
-
- /**
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
- * symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function baseGetAllKeys(object, keysFunc, symbolsFunc) {
- var result = keysFunc(object);
- return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
- }
-
- var _baseGetAllKeys = baseGetAllKeys;
-
- /**
- * Creates an array of own enumerable property names and symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function getAllKeys(object) {
- return _baseGetAllKeys(object, keys_1, _getSymbols);
- }
-
- var _getAllKeys = getAllKeys;
-
- /**
- * Creates an array of own and inherited enumerable property names and
- * symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function getAllKeysIn(object) {
- return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
- }
-
- var _getAllKeysIn = getAllKeysIn;
-
- /* Built-in method references that are verified to be native. */
- var DataView = _getNative(_root, 'DataView');
-
- var _DataView = DataView;
-
- /* Built-in method references that are verified to be native. */
- var Promise$1 = _getNative(_root, 'Promise');
-
- var _Promise = Promise$1;
-
- /* Built-in method references that are verified to be native. */
- var Set$1 = _getNative(_root, 'Set');
-
- var _Set = Set$1;
-
- /** `Object#toString` result references. */
- var mapTag$4 = '[object Map]',
- objectTag$3 = '[object Object]',
- promiseTag = '[object Promise]',
- setTag$4 = '[object Set]',
- weakMapTag$2 = '[object WeakMap]';
-
- var dataViewTag$3 = '[object DataView]';
-
- /** Used to detect maps, sets, and weakmaps. */
- var dataViewCtorString = _toSource(_DataView),
- mapCtorString = _toSource(_Map),
- promiseCtorString = _toSource(_Promise),
- setCtorString = _toSource(_Set),
- weakMapCtorString = _toSource(_WeakMap);
-
- /**
- * Gets the `toStringTag` of `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- var getTag = _baseGetTag;
-
- // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
- if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
- (_Map && getTag(new _Map) != mapTag$4) ||
- (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
- (_Set && getTag(new _Set) != setTag$4) ||
- (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
- getTag = function(value) {
- var result = _baseGetTag(value),
- Ctor = result == objectTag$3 ? value.constructor : undefined,
- ctorString = Ctor ? _toSource(Ctor) : '';
-
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString: return dataViewTag$3;
- case mapCtorString: return mapTag$4;
- case promiseCtorString: return promiseTag;
- case setCtorString: return setTag$4;
- case weakMapCtorString: return weakMapTag$2;
- }
- }
- return result;
- };
- }
-
- var _getTag = getTag;
-
- /** Used for built-in method references. */
- var objectProto$3 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
-
- /**
- * Initializes an array clone.
- *
- * @private
- * @param {Array} array The array to clone.
- * @returns {Array} Returns the initialized clone.
- */
- function initCloneArray(array) {
- var length = array.length,
- result = new array.constructor(length);
-
- // Add properties assigned by `RegExp#exec`.
- if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
- result.index = array.index;
- result.input = array.input;
- }
- return result;
- }
-
- var _initCloneArray = initCloneArray;
-
- /** Built-in value references. */
- var Uint8Array$1 = _root.Uint8Array;
-
- var _Uint8Array = Uint8Array$1;
-
- /**
- * Creates a clone of `arrayBuffer`.
- *
- * @private
- * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
- * @returns {ArrayBuffer} Returns the cloned array buffer.
- */
- function cloneArrayBuffer(arrayBuffer) {
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
- new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
- return result;
- }
-
- var _cloneArrayBuffer = cloneArrayBuffer;
-
- /**
- * Creates a clone of `dataView`.
- *
- * @private
- * @param {Object} dataView The data view to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the cloned data view.
- */
- function cloneDataView(dataView, isDeep) {
- var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
- }
-
- var _cloneDataView = cloneDataView;
-
- /** Used to match `RegExp` flags from their coerced string values. */
- var reFlags = /\w*$/;
-
- /**
- * Creates a clone of `regexp`.
- *
- * @private
- * @param {Object} regexp The regexp to clone.
- * @returns {Object} Returns the cloned regexp.
- */
- function cloneRegExp(regexp) {
- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
- result.lastIndex = regexp.lastIndex;
- return result;
- }
-
- var _cloneRegExp = cloneRegExp;
-
- /** Used to convert symbols to primitives and strings. */
- var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
- symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
-
- /**
- * Creates a clone of the `symbol` object.
- *
- * @private
- * @param {Object} symbol The symbol object to clone.
- * @returns {Object} Returns the cloned symbol object.
- */
- function cloneSymbol(symbol) {
- return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
- }
-
- var _cloneSymbol = cloneSymbol;
-
- /**
- * Creates a clone of `typedArray`.
- *
- * @private
- * @param {Object} typedArray The typed array to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the cloned typed array.
- */
- function cloneTypedArray(typedArray, isDeep) {
- var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
- }
-
- var _cloneTypedArray = cloneTypedArray;
-
- /** `Object#toString` result references. */
- var boolTag$2 = '[object Boolean]',
- dateTag$2 = '[object Date]',
- mapTag$3 = '[object Map]',
- numberTag$2 = '[object Number]',
- regexpTag$2 = '[object RegExp]',
- setTag$3 = '[object Set]',
- stringTag$2 = '[object String]',
- symbolTag$2 = '[object Symbol]';
-
- var arrayBufferTag$2 = '[object ArrayBuffer]',
- dataViewTag$2 = '[object DataView]',
- float32Tag$1 = '[object Float32Array]',
- float64Tag$1 = '[object Float64Array]',
- int8Tag$1 = '[object Int8Array]',
- int16Tag$1 = '[object Int16Array]',
- int32Tag$1 = '[object Int32Array]',
- uint8Tag$1 = '[object Uint8Array]',
- uint8ClampedTag$1 = '[object Uint8ClampedArray]',
- uint16Tag$1 = '[object Uint16Array]',
- uint32Tag$1 = '[object Uint32Array]';
-
- /**
- * Initializes an object clone based on its `toStringTag`.
- *
- * **Note:** This function only supports cloning values with tags of
- * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
- *
- * @private
- * @param {Object} object The object to clone.
- * @param {string} tag The `toStringTag` of the object to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the initialized clone.
- */
- function initCloneByTag(object, tag, isDeep) {
- var Ctor = object.constructor;
- switch (tag) {
- case arrayBufferTag$2:
- return _cloneArrayBuffer(object);
-
- case boolTag$2:
- case dateTag$2:
- return new Ctor(+object);
-
- case dataViewTag$2:
- return _cloneDataView(object, isDeep);
-
- case float32Tag$1: case float64Tag$1:
- case int8Tag$1: case int16Tag$1: case int32Tag$1:
- case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
- return _cloneTypedArray(object, isDeep);
-
- case mapTag$3:
- return new Ctor;
-
- case numberTag$2:
- case stringTag$2:
- return new Ctor(object);
-
- case regexpTag$2:
- return _cloneRegExp(object);
-
- case setTag$3:
- return new Ctor;
-
- case symbolTag$2:
- return _cloneSymbol(object);
- }
- }
-
- var _initCloneByTag = initCloneByTag;
-
- /**
- * Initializes an object clone.
- *
- * @private
- * @param {Object} object The object to clone.
- * @returns {Object} Returns the initialized clone.
- */
- function initCloneObject(object) {
- return (typeof object.constructor == 'function' && !_isPrototype(object))
- ? _baseCreate(_getPrototype(object))
- : {};
- }
-
- var _initCloneObject = initCloneObject;
-
- /** `Object#toString` result references. */
- var mapTag$2 = '[object Map]';
-
- /**
- * The base implementation of `_.isMap` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a map, else `false`.
- */
- function baseIsMap(value) {
- return isObjectLike_1(value) && _getTag(value) == mapTag$2;
- }
-
- var _baseIsMap = baseIsMap;
-
- /* Node.js helper references. */
- var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
-
- /**
- * Checks if `value` is classified as a `Map` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a map, else `false`.
- * @example
- *
- * _.isMap(new Map);
- * // => true
- *
- * _.isMap(new WeakMap);
- * // => false
- */
- var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
-
- var isMap_1 = isMap;
-
- /** `Object#toString` result references. */
- var setTag$2 = '[object Set]';
-
- /**
- * The base implementation of `_.isSet` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a set, else `false`.
- */
- function baseIsSet(value) {
- return isObjectLike_1(value) && _getTag(value) == setTag$2;
- }
-
- var _baseIsSet = baseIsSet;
-
- /* Node.js helper references. */
- var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
-
- /**
- * Checks if `value` is classified as a `Set` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a set, else `false`.
- * @example
- *
- * _.isSet(new Set);
- * // => true
- *
- * _.isSet(new WeakSet);
- * // => false
- */
- var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
-
- var isSet_1 = isSet;
-
- /** Used to compose bitmasks for cloning. */
- var CLONE_DEEP_FLAG$1 = 1,
- CLONE_FLAT_FLAG = 2,
- CLONE_SYMBOLS_FLAG$1 = 4;
-
- /** `Object#toString` result references. */
- var argsTag$1 = '[object Arguments]',
- arrayTag$1 = '[object Array]',
- boolTag$1 = '[object Boolean]',
- dateTag$1 = '[object Date]',
- errorTag$2 = '[object Error]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- mapTag$1 = '[object Map]',
- numberTag$1 = '[object Number]',
- objectTag$2 = '[object Object]',
- regexpTag$1 = '[object RegExp]',
- setTag$1 = '[object Set]',
- stringTag$1 = '[object String]',
- symbolTag$1 = '[object Symbol]',
- weakMapTag$1 = '[object WeakMap]';
-
- var arrayBufferTag$1 = '[object ArrayBuffer]',
- dataViewTag$1 = '[object DataView]',
- float32Tag = '[object Float32Array]',
- float64Tag = '[object Float64Array]',
- int8Tag = '[object Int8Array]',
- int16Tag = '[object Int16Array]',
- int32Tag = '[object Int32Array]',
- uint8Tag = '[object Uint8Array]',
- uint8ClampedTag = '[object Uint8ClampedArray]',
- uint16Tag = '[object Uint16Array]',
- uint32Tag = '[object Uint32Array]';
-
- /** Used to identify `toStringTag` values supported by `_.clone`. */
- var cloneableTags = {};
- cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
- cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
- cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
- cloneableTags[float32Tag] = cloneableTags[float64Tag] =
- cloneableTags[int8Tag] = cloneableTags[int16Tag] =
- cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
- cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
- cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
- cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
- cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
- cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
- cloneableTags[errorTag$2] = cloneableTags[funcTag] =
- cloneableTags[weakMapTag$1] = false;
-
- /**
- * The base implementation of `_.clone` and `_.cloneDeep` which tracks
- * traversed objects.
- *
- * @private
- * @param {*} value The value to clone.
- * @param {boolean} bitmask The bitmask flags.
- * 1 - Deep clone
- * 2 - Flatten inherited properties
- * 4 - Clone symbols
- * @param {Function} [customizer] The function to customize cloning.
- * @param {string} [key] The key of `value`.
- * @param {Object} [object] The parent object of `value`.
- * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
- * @returns {*} Returns the cloned value.
- */
- function baseClone(value, bitmask, customizer, key, object, stack) {
- var result,
- isDeep = bitmask & CLONE_DEEP_FLAG$1,
- isFlat = bitmask & CLONE_FLAT_FLAG,
- isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
-
- if (customizer) {
- result = object ? customizer(value, key, object, stack) : customizer(value);
- }
- if (result !== undefined) {
- return result;
- }
- if (!isObject_1(value)) {
- return value;
- }
- var isArr = isArray_1(value);
- if (isArr) {
- result = _initCloneArray(value);
- if (!isDeep) {
- return _copyArray(value, result);
- }
- } else {
- var tag = _getTag(value),
- isFunc = tag == funcTag || tag == genTag;
-
- if (isBuffer_1(value)) {
- return _cloneBuffer(value, isDeep);
- }
- if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
- result = (isFlat || isFunc) ? {} : _initCloneObject(value);
- if (!isDeep) {
- return isFlat
- ? _copySymbolsIn(value, _baseAssignIn(result, value))
- : _copySymbols(value, _baseAssign(result, value));
- }
- } else {
- if (!cloneableTags[tag]) {
- return object ? value : {};
- }
- result = _initCloneByTag(value, tag, isDeep);
- }
- }
- // Check for circular references and return its corresponding clone.
- stack || (stack = new _Stack);
- var stacked = stack.get(value);
- if (stacked) {
- return stacked;
- }
- stack.set(value, result);
-
- if (isSet_1(value)) {
- value.forEach(function(subValue) {
- result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
- });
- } else if (isMap_1(value)) {
- value.forEach(function(subValue, key) {
- result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
- });
- }
-
- var keysFunc = isFull
- ? (isFlat ? _getAllKeysIn : _getAllKeys)
- : (isFlat ? keysIn_1 : keys_1);
-
- var props = isArr ? undefined : keysFunc(value);
- _arrayEach(props || value, function(subValue, key) {
- if (props) {
- key = subValue;
- subValue = value[key];
- }
- // Recursively populate clone (susceptible to call stack limits).
- _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
- });
- return result;
- }
-
- var _baseClone = baseClone;
-
- /** Used to compose bitmasks for cloning. */
- var CLONE_SYMBOLS_FLAG = 4;
-
- /**
- * Creates a shallow clone of `value`.
- *
- * **Note:** This method is loosely based on the
- * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
- * and supports cloning arrays, array buffers, booleans, date objects, maps,
- * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
- * arrays. The own enumerable properties of `arguments` objects are cloned
- * as plain objects. An empty object is returned for uncloneable values such
- * as error objects, functions, DOM nodes, and WeakMaps.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to clone.
- * @returns {*} Returns the cloned value.
- * @see _.cloneDeep
- * @example
- *
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
- *
- * var shallow = _.clone(objects);
- * console.log(shallow[0] === objects[0]);
- * // => true
- */
- function clone(value) {
- return _baseClone(value, CLONE_SYMBOLS_FLAG);
- }
-
- var clone_1 = clone;
-
- /** `Object#toString` result references. */
- var objectTag$1 = '[object Object]';
-
- /** Used for built-in method references. */
- var funcProto = Function.prototype,
- objectProto$2 = Object.prototype;
-
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
-
- /** Used to infer the `Object` constructor. */
- var objectCtorString = funcToString.call(Object);
-
- /**
- * Checks if `value` is a plain object, that is, an object created by the
- * `Object` constructor or one with a `[[Prototype]]` of `null`.
- *
- * @static
- * @memberOf _
- * @since 0.8.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * }
- *
- * _.isPlainObject(new Foo);
- * // => false
- *
- * _.isPlainObject([1, 2, 3]);
- * // => false
- *
- * _.isPlainObject({ 'x': 0, 'y': 0 });
- * // => true
- *
- * _.isPlainObject(Object.create(null));
- * // => true
- */
- function isPlainObject(value) {
- if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
- return false;
- }
- var proto = _getPrototype(value);
- if (proto === null) {
- return true;
- }
- var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
- return typeof Ctor == 'function' && Ctor instanceof Ctor &&
- funcToString.call(Ctor) == objectCtorString;
- }
-
- var isPlainObject_1 = isPlainObject;
-
- /** `Object#toString` result references. */
- var domExcTag = '[object DOMException]',
- errorTag$1 = '[object Error]';
-
- /**
- * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
- * `SyntaxError`, `TypeError`, or `URIError` object.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
- * @example
- *
- * _.isError(new Error);
- * // => true
- *
- * _.isError(Error);
- * // => false
- */
- function isError(value) {
- if (!isObjectLike_1(value)) {
- return false;
- }
- var tag = _baseGetTag(value);
- return tag == errorTag$1 || tag == domExcTag ||
- (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
- }
-
- var isError_1 = isError;
-
- /** `Object#toString` result references. */
- var weakMapTag = '[object WeakMap]';
-
- /**
- * Checks if `value` is classified as a `WeakMap` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
- * @example
- *
- * _.isWeakMap(new WeakMap);
- * // => true
- *
- * _.isWeakMap(new Map);
- * // => false
- */
- function isWeakMap(value) {
- return isObjectLike_1(value) && _getTag(value) == weakMapTag;
- }
-
- var isWeakMap_1 = isWeakMap;
-
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
-
- /**
- * Adds `value` to the array cache.
- *
- * @private
- * @name add
- * @memberOf SetCache
- * @alias push
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache instance.
- */
- function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED);
- return this;
- }
-
- var _setCacheAdd = setCacheAdd;
-
- /**
- * Checks if `value` is in the array cache.
- *
- * @private
- * @name has
- * @memberOf SetCache
- * @param {*} value The value to search for.
- * @returns {number} Returns `true` if `value` is found, else `false`.
- */
- function setCacheHas(value) {
- return this.__data__.has(value);
- }
-
- var _setCacheHas = setCacheHas;
-
- /**
- *
- * Creates an array cache object to store unique values.
- *
- * @private
- * @constructor
- * @param {Array} [values] The values to cache.
- */
- function SetCache(values) {
- var index = -1,
- length = values == null ? 0 : values.length;
-
- this.__data__ = new _MapCache;
- while (++index < length) {
- this.add(values[index]);
- }
- }
-
- // Add methods to `SetCache`.
- SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
- SetCache.prototype.has = _setCacheHas;
-
- var _SetCache = SetCache;
-
- /**
- * A specialized version of `_.some` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
- */
- function arraySome(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length;
-
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
- }
-
- var _arraySome = arraySome;
-
- /**
- * Checks if a `cache` value for `key` exists.
- *
- * @private
- * @param {Object} cache The cache to query.
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function cacheHas(cache, key) {
- return cache.has(key);
- }
-
- var _cacheHas = cacheHas;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$5 = 1,
- COMPARE_UNORDERED_FLAG$3 = 2;
-
- /**
- * A specialized version of `baseIsEqualDeep` for arrays with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Array} array The array to compare.
- * @param {Array} other The other array to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
- function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
- arrLength = array.length,
- othLength = other.length;
-
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- }
- // Check that cyclic values are equal.
- var arrStacked = stack.get(array);
- var othStacked = stack.get(other);
- if (arrStacked && othStacked) {
- return arrStacked == other && othStacked == array;
- }
- var index = -1,
- result = true,
- seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
-
- stack.set(array, other);
- stack.set(other, array);
-
- // Ignore non-index properties.
- while (++index < arrLength) {
- var arrValue = array[index],
- othValue = other[index];
-
- if (customizer) {
- var compared = isPartial
- ? customizer(othValue, arrValue, index, other, array, stack)
- : customizer(arrValue, othValue, index, array, other, stack);
- }
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- }
- // Recursively compare arrays (susceptible to call stack limits).
- if (seen) {
- if (!_arraySome(other, function(othValue, othIndex) {
- if (!_cacheHas(seen, othIndex) &&
- (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- return seen.push(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(
- arrValue === othValue ||
- equalFunc(arrValue, othValue, bitmask, customizer, stack)
- )) {
- result = false;
- break;
- }
- }
- stack['delete'](array);
- stack['delete'](other);
- return result;
- }
-
- var _equalArrays = equalArrays;
-
- /**
- * Converts `map` to its key-value pairs.
- *
- * @private
- * @param {Object} map The map to convert.
- * @returns {Array} Returns the key-value pairs.
- */
- function mapToArray(map) {
- var index = -1,
- result = Array(map.size);
-
- map.forEach(function(value, key) {
- result[++index] = [key, value];
- });
- return result;
- }
-
- var _mapToArray = mapToArray;
-
- /**
- * Converts `set` to an array of its values.
- *
- * @private
- * @param {Object} set The set to convert.
- * @returns {Array} Returns the values.
- */
- function setToArray(set) {
- var index = -1,
- result = Array(set.size);
-
- set.forEach(function(value) {
- result[++index] = value;
- });
- return result;
- }
-
- var _setToArray = setToArray;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$4 = 1,
- COMPARE_UNORDERED_FLAG$2 = 2;
-
- /** `Object#toString` result references. */
- var boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- symbolTag = '[object Symbol]';
-
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[object DataView]';
-
- /** Used to convert symbols to primitives and strings. */
- var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
- symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
-
- /**
- * A specialized version of `baseIsEqualDeep` for comparing objects of
- * the same `toStringTag`.
- *
- * **Note:** This function only supports comparing values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {string} tag The `toStringTag` of the objects to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
- switch (tag) {
- case dataViewTag:
- if ((object.byteLength != other.byteLength) ||
- (object.byteOffset != other.byteOffset)) {
- return false;
- }
- object = object.buffer;
- other = other.buffer;
-
- case arrayBufferTag:
- if ((object.byteLength != other.byteLength) ||
- !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
- return false;
- }
- return true;
-
- case boolTag:
- case dateTag:
- case numberTag:
- // Coerce booleans to `1` or `0` and dates to milliseconds.
- // Invalid dates are coerced to `NaN`.
- return eq_1(+object, +other);
-
- case errorTag:
- return object.name == other.name && object.message == other.message;
-
- case regexpTag:
- case stringTag:
- // Coerce regexes to strings and treat strings, primitives and objects,
- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
- // for more details.
- return object == (other + '');
-
- case mapTag:
- var convert = _mapToArray;
-
- case setTag:
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
- convert || (convert = _setToArray);
-
- if (object.size != other.size && !isPartial) {
- return false;
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked) {
- return stacked == other;
- }
- bitmask |= COMPARE_UNORDERED_FLAG$2;
-
- // Recursively compare objects (susceptible to call stack limits).
- stack.set(object, other);
- var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
- stack['delete'](object);
- return result;
-
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
- }
-
- var _equalByTag = equalByTag;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$3 = 1;
-
- /** Used for built-in method references. */
- var objectProto$1 = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
-
- /**
- * A specialized version of `baseIsEqualDeep` for objects with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
- objProps = _getAllKeys(object),
- objLength = objProps.length,
- othProps = _getAllKeys(other),
- othLength = othProps.length;
-
- if (objLength != othLength && !isPartial) {
- return false;
- }
- var index = objLength;
- while (index--) {
- var key = objProps[index];
- if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
- return false;
- }
- }
- // Check that cyclic values are equal.
- var objStacked = stack.get(object);
- var othStacked = stack.get(other);
- if (objStacked && othStacked) {
- return objStacked == other && othStacked == object;
- }
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
-
- var skipCtor = isPartial;
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key],
- othValue = other[key];
-
- if (customizer) {
- var compared = isPartial
- ? customizer(othValue, objValue, key, other, object, stack)
- : customizer(objValue, othValue, key, object, other, stack);
- }
- // Recursively compare objects (susceptible to call stack limits).
- if (!(compared === undefined
- ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
- : compared
- )) {
- result = false;
- break;
- }
- skipCtor || (skipCtor = key == 'constructor');
- }
- if (result && !skipCtor) {
- var objCtor = object.constructor,
- othCtor = other.constructor;
-
- // Non `Object` object instances with different constructors are not equal.
- if (objCtor != othCtor &&
- ('constructor' in object && 'constructor' in other) &&
- !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
- typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- result = false;
- }
- }
- stack['delete'](object);
- stack['delete'](other);
- return result;
- }
-
- var _equalObjects = equalObjects;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$2 = 1;
-
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]',
- arrayTag = '[object Array]',
- objectTag = '[object Object]';
-
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
-
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
-
- /**
- * A specialized version of `baseIsEqual` for arrays and objects which performs
- * deep comparisons and tracks traversed objects enabling objects with circular
- * references to be compared.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
- var objIsArr = isArray_1(object),
- othIsArr = isArray_1(other),
- objTag = objIsArr ? arrayTag : _getTag(object),
- othTag = othIsArr ? arrayTag : _getTag(other);
-
- objTag = objTag == argsTag ? objectTag : objTag;
- othTag = othTag == argsTag ? objectTag : othTag;
-
- var objIsObj = objTag == objectTag,
- othIsObj = othTag == objectTag,
- isSameTag = objTag == othTag;
-
- if (isSameTag && isBuffer_1(object)) {
- if (!isBuffer_1(other)) {
- return false;
- }
- objIsArr = true;
- objIsObj = false;
- }
- if (isSameTag && !objIsObj) {
- stack || (stack = new _Stack);
- return (objIsArr || isTypedArray_1(object))
- ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
- : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
- var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
- othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
-
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object,
- othUnwrapped = othIsWrapped ? other.value() : other;
-
- stack || (stack = new _Stack);
- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new _Stack);
- return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
- }
-
- var _baseIsEqualDeep = baseIsEqualDeep;
-
- /**
- * The base implementation of `_.isEqual` which supports partial comparisons
- * and tracks traversed objects.
- *
- * @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {boolean} bitmask The bitmask flags.
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
- function baseIsEqual(value, other, bitmask, customizer, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
- return value !== value && other !== other;
- }
- return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
- }
-
- var _baseIsEqual = baseIsEqual;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$1 = 1,
- COMPARE_UNORDERED_FLAG$1 = 2;
-
- /**
- * The base implementation of `_.isMatch` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @param {Array} matchData The property names, values, and compare flags to match.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- */
- function baseIsMatch(object, source, matchData, customizer) {
- var index = matchData.length,
- length = index,
- noCustomizer = !customizer;
-
- if (object == null) {
- return !length;
- }
- object = Object(object);
- while (index--) {
- var data = matchData[index];
- if ((noCustomizer && data[2])
- ? data[1] !== object[data[0]]
- : !(data[0] in object)
- ) {
- return false;
- }
- }
- while (++index < length) {
- data = matchData[index];
- var key = data[0],
- objValue = object[key],
- srcValue = data[1];
-
- if (noCustomizer && data[2]) {
- if (objValue === undefined && !(key in object)) {
- return false;
- }
- } else {
- var stack = new _Stack;
- if (customizer) {
- var result = customizer(objValue, srcValue, key, object, source, stack);
- }
- if (!(result === undefined
- ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
- : result
- )) {
- return false;
- }
- }
- }
- return true;
- }
-
- var _baseIsMatch = baseIsMatch;
-
- /**
- * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` if suitable for strict
- * equality comparisons, else `false`.
- */
- function isStrictComparable(value) {
- return value === value && !isObject_1(value);
- }
-
- var _isStrictComparable = isStrictComparable;
-
- /**
- * Gets the property names, values, and compare flags of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the match data of `object`.
- */
- function getMatchData(object) {
- var result = keys_1(object),
- length = result.length;
-
- while (length--) {
- var key = result[length],
- value = object[key];
-
- result[length] = [key, value, _isStrictComparable(value)];
- }
- return result;
- }
-
- var _getMatchData = getMatchData;
-
- /**
- * A specialized version of `matchesProperty` for source values suitable
- * for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function matchesStrictComparable(key, srcValue) {
- return function(object) {
- if (object == null) {
- return false;
- }
- return object[key] === srcValue &&
- (srcValue !== undefined || (key in Object(object)));
- };
- }
-
- var _matchesStrictComparable = matchesStrictComparable;
-
- /**
- * The base implementation of `_.matches` which doesn't clone `source`.
- *
- * @private
- * @param {Object} source The object of property values to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatches(source) {
- var matchData = _getMatchData(source);
- if (matchData.length == 1 && matchData[0][2]) {
- return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
- }
- return function(object) {
- return object === source || _baseIsMatch(object, source, matchData);
- };
- }
-
- var _baseMatches = baseMatches;
-
- /** Used to match property names within property paths. */
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
- reIsPlainProp = /^\w*$/;
-
- /**
- * Checks if `value` is a property name and not a property path.
- *
- * @private
- * @param {*} value The value to check.
- * @param {Object} [object] The object to query keys on.
- * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
- */
- function isKey(value, object) {
- if (isArray_1(value)) {
- return false;
- }
- var type = typeof value;
- if (type == 'number' || type == 'symbol' || type == 'boolean' ||
- value == null || isSymbol_1(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
- (object != null && value in Object(object));
- }
-
- var _isKey = isKey;
-
- /** Error message constants. */
- var FUNC_ERROR_TEXT = 'Expected a function';
-
- /**
- * Creates a function that memoizes the result of `func`. If `resolver` is
- * provided, it determines the cache key for storing the result based on the
- * arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is used as the map cache key. The `func`
- * is invoked with the `this` binding of the memoized function.
- *
- * **Note:** The cache is exposed as the `cache` property on the memoized
- * function. Its creation may be customized by replacing the `_.memoize.Cache`
- * constructor with one whose instances implement the
- * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
- * method interface of `clear`, `delete`, `get`, `has`, and `set`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Function
- * @param {Function} func The function to have its output memoized.
- * @param {Function} [resolver] The function to resolve the cache key.
- * @returns {Function} Returns the new memoized function.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- * var other = { 'c': 3, 'd': 4 };
- *
- * var values = _.memoize(_.values);
- * values(object);
- * // => [1, 2]
- *
- * values(other);
- * // => [3, 4]
- *
- * object.a = 2;
- * values(object);
- * // => [1, 2]
- *
- * // Modify the result cache.
- * values.cache.set(object, ['a', 'b']);
- * values(object);
- * // => ['a', 'b']
- *
- * // Replace `_.memoize.Cache`.
- * _.memoize.Cache = WeakMap;
- */
- function memoize(func, resolver) {
- if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- var memoized = function() {
- var args = arguments,
- key = resolver ? resolver.apply(this, args) : args[0],
- cache = memoized.cache;
-
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
- memoized.cache = new (memoize.Cache || _MapCache);
- return memoized;
- }
-
- // Expose `MapCache`.
- memoize.Cache = _MapCache;
-
- var memoize_1 = memoize;
-
- /** Used as the maximum memoize cache size. */
- var MAX_MEMOIZE_SIZE = 500;
-
- /**
- * A specialized version of `_.memoize` which clears the memoized function's
- * cache when it exceeds `MAX_MEMOIZE_SIZE`.
- *
- * @private
- * @param {Function} func The function to have its output memoized.
- * @returns {Function} Returns the new memoized function.
- */
- function memoizeCapped(func) {
- var result = memoize_1(func, function(key) {
- if (cache.size === MAX_MEMOIZE_SIZE) {
- cache.clear();
- }
- return key;
- });
-
- var cache = result.cache;
- return result;
- }
-
- var _memoizeCapped = memoizeCapped;
-
- /** Used to match property names within property paths. */
- var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
-
- /** Used to match backslashes in property paths. */
- var reEscapeChar = /\\(\\)?/g;
-
- /**
- * Converts `string` to a property path array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the property path array.
- */
- var stringToPath = _memoizeCapped(function(string) {
- var result = [];
- if (string.charCodeAt(0) === 46 /* . */) {
- result.push('');
- }
- string.replace(rePropName, function(match, number, quote, subString) {
- result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
- });
- return result;
- });
-
- var _stringToPath = stringToPath;
-
- /**
- * A specialized version of `_.map` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- */
- function arrayMap(array, iteratee) {
- var index = -1,
- length = array == null ? 0 : array.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
- }
- return result;
- }
-
- var _arrayMap = arrayMap;
-
- /** Used as references for various `Number` constants. */
- var INFINITY$1 = 1 / 0;
-
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = _Symbol ? _Symbol.prototype : undefined,
- symbolToString = symbolProto ? symbolProto.toString : undefined;
-
- /**
- * The base implementation of `_.toString` which doesn't convert nullish
- * values to empty strings.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- */
- function baseToString(value) {
- // Exit early for strings to avoid a performance hit in some environments.
- if (typeof value == 'string') {
- return value;
- }
- if (isArray_1(value)) {
- // Recursively convert values (susceptible to call stack limits).
- return _arrayMap(value, baseToString) + '';
- }
- if (isSymbol_1(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
- }
-
- var _baseToString = baseToString;
-
- /**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? '' : _baseToString(value);
- }
-
- var toString_1 = toString;
-
- /**
- * Casts `value` to a path array if it's not one.
- *
- * @private
- * @param {*} value The value to inspect.
- * @param {Object} [object] The object to query keys on.
- * @returns {Array} Returns the cast property path array.
- */
- function castPath(value, object) {
- if (isArray_1(value)) {
- return value;
- }
- return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
- }
-
- var _castPath = castPath;
-
- /** Used as references for various `Number` constants. */
- var INFINITY = 1 / 0;
-
- /**
- * Converts `value` to a string key if it's not a string or symbol.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {string|symbol} Returns the key.
- */
- function toKey(value) {
- if (typeof value == 'string' || isSymbol_1(value)) {
- return value;
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
-
- var _toKey = toKey;
-
- /**
- * The base implementation of `_.get` without support for default values.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @returns {*} Returns the resolved value.
- */
- function baseGet(object, path) {
- path = _castPath(path, object);
-
- var index = 0,
- length = path.length;
-
- while (object != null && index < length) {
- object = object[_toKey(path[index++])];
- }
- return (index && index == length) ? object : undefined;
- }
-
- var _baseGet = baseGet;
-
- /**
- * Gets the value at `path` of `object`. If the resolved value is
- * `undefined`, the `defaultValue` is returned in its place.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.get(object, 'a[0].b.c');
- * // => 3
- *
- * _.get(object, ['a', '0', 'b', 'c']);
- * // => 3
- *
- * _.get(object, 'a.b.c', 'default');
- * // => 'default'
- */
- function get$1(object, path, defaultValue) {
- var result = object == null ? undefined : _baseGet(object, path);
- return result === undefined ? defaultValue : result;
- }
-
- var get_1 = get$1;
-
- /**
- * The base implementation of `_.hasIn` without support for deep paths.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {Array|string} key The key to check.
- * @returns {boolean} Returns `true` if `key` exists, else `false`.
- */
- function baseHasIn(object, key) {
- return object != null && key in Object(object);
- }
-
- var _baseHasIn = baseHasIn;
-
- /**
- * Checks if `path` exists on `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @param {Function} hasFunc The function to check properties.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- */
- function hasPath(object, path, hasFunc) {
- path = _castPath(path, object);
-
- var index = -1,
- length = path.length,
- result = false;
-
- while (++index < length) {
- var key = _toKey(path[index]);
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
- object = object[key];
- }
- if (result || ++index != length) {
- return result;
- }
- length = object == null ? 0 : object.length;
- return !!length && isLength_1(length) && _isIndex(key, length) &&
- (isArray_1(object) || isArguments_1(object));
- }
-
- var _hasPath = hasPath;
-
- /**
- * Checks if `path` is a direct or inherited property of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.hasIn(object, 'a');
- * // => true
- *
- * _.hasIn(object, 'a.b');
- * // => true
- *
- * _.hasIn(object, ['a', 'b']);
- * // => true
- *
- * _.hasIn(object, 'b');
- * // => false
- */
- function hasIn(object, path) {
- return object != null && _hasPath(object, path, _baseHasIn);
- }
-
- var hasIn_1 = hasIn;
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 2;
-
- /**
- * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
- *
- * @private
- * @param {string} path The path of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatchesProperty(path, srcValue) {
- if (_isKey(path) && _isStrictComparable(srcValue)) {
- return _matchesStrictComparable(_toKey(path), srcValue);
- }
- return function(object) {
- var objValue = get_1(object, path);
- return (objValue === undefined && objValue === srcValue)
- ? hasIn_1(object, path)
- : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
- };
- }
-
- var _baseMatchesProperty = baseMatchesProperty;
-
- /**
- * The base implementation of `_.property` without support for deep paths.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function baseProperty(key) {
- return function(object) {
- return object == null ? undefined : object[key];
- };
- }
-
- var _baseProperty = baseProperty;
-
- /**
- * A specialized version of `baseProperty` which supports deep paths.
- *
- * @private
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function basePropertyDeep(path) {
- return function(object) {
- return _baseGet(object, path);
- };
- }
-
- var _basePropertyDeep = basePropertyDeep;
-
- /**
- * Creates a function that returns the value at `path` of a given object.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- * @example
- *
- * var objects = [
- * { 'a': { 'b': 2 } },
- * { 'a': { 'b': 1 } }
- * ];
- *
- * _.map(objects, _.property('a.b'));
- * // => [2, 1]
- *
- * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
- * // => [1, 2]
- */
- function property(path) {
- return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
- }
-
- var property_1 = property;
-
- /**
- * The base implementation of `_.iteratee`.
- *
- * @private
- * @param {*} [value=_.identity] The value to convert to an iteratee.
- * @returns {Function} Returns the iteratee.
- */
- function baseIteratee(value) {
- // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
- // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
- if (typeof value == 'function') {
- return value;
- }
- if (value == null) {
- return identity_1;
- }
- if (typeof value == 'object') {
- return isArray_1(value)
- ? _baseMatchesProperty(value[0], value[1])
- : _baseMatches(value);
- }
- return property_1(value);
- }
-
- var _baseIteratee = baseIteratee;
-
- /** Used to compose bitmasks for cloning. */
- var CLONE_DEEP_FLAG = 1;
-
- /**
- * Creates a function that invokes `func` with the arguments of the created
- * function. If `func` is a property name, the created function returns the
- * property value for a given element. If `func` is an array or object, the
- * created function returns `true` for elements that contain the equivalent
- * source properties, otherwise it returns `false`.
- *
- * @static
- * @since 4.0.0
- * @memberOf _
- * @category Util
- * @param {*} [func=_.identity] The value to convert to a callback.
- * @returns {Function} Returns the callback.
- * @example
- *
- * var users = [
- * { 'user': 'barney', 'age': 36, 'active': true },
- * { 'user': 'fred', 'age': 40, 'active': false }
- * ];
- *
- * // The `_.matches` iteratee shorthand.
- * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
- * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
- *
- * // The `_.matchesProperty` iteratee shorthand.
- * _.filter(users, _.iteratee(['user', 'fred']));
- * // => [{ 'user': 'fred', 'age': 40 }]
- *
- * // The `_.property` iteratee shorthand.
- * _.map(users, _.iteratee('user'));
- * // => ['barney', 'fred']
- *
- * // Create custom iteratee shorthands.
- * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
- * return !_.isRegExp(func) ? iteratee(func) : function(string) {
- * return func.test(string);
- * };
- * });
- *
- * _.filter(['abc', 'def'], /ef/);
- * // => ['def']
- */
- function iteratee(func) {
- return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
- }
-
- var iteratee_1 = iteratee;
-
- /** Built-in value references. */
- var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
-
- /**
- * Checks if `value` is a flattenable `arguments` object or array.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
- */
- function isFlattenable(value) {
- return isArray_1(value) || isArguments_1(value) ||
- !!(spreadableSymbol && value && value[spreadableSymbol]);
- }
-
- var _isFlattenable = isFlattenable;
-
- /**
- * The base implementation of `_.flatten` with support for restricting flattening.
- *
- * @private
- * @param {Array} array The array to flatten.
- * @param {number} depth The maximum recursion depth.
- * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
- * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
- * @param {Array} [result=[]] The initial result value.
- * @returns {Array} Returns the new flattened array.
- */
- function baseFlatten(array, depth, predicate, isStrict, result) {
- var index = -1,
- length = array.length;
-
- predicate || (predicate = _isFlattenable);
- result || (result = []);
-
- while (++index < length) {
- var value = array[index];
- if (depth > 0 && predicate(value)) {
- if (depth > 1) {
- // Recursively flatten arrays (susceptible to call stack limits).
- baseFlatten(value, depth - 1, predicate, isStrict, result);
- } else {
- _arrayPush(result, value);
- }
- } else if (!isStrict) {
- result[result.length] = value;
- }
- }
- return result;
- }
-
- var _baseFlatten = baseFlatten;
-
- /**
- * Flattens `array` a single level deep.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Array
- * @param {Array} array The array to flatten.
- * @returns {Array} Returns the new flattened array.
- * @example
- *
- * _.flatten([1, [2, [3, [4]], 5]]);
- * // => [1, 2, [3, [4]], 5]
- */
- function flatten(array) {
- var length = array == null ? 0 : array.length;
- return length ? _baseFlatten(array, 1) : [];
- }
-
- var flatten_1 = flatten;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax = Math.max;
-
- /**
- * A specialized version of `baseRest` which transforms the rest array.
- *
- * @private
- * @param {Function} func The function to apply a rest parameter to.
- * @param {number} [start=func.length-1] The start position of the rest parameter.
- * @param {Function} transform The rest array transform.
- * @returns {Function} Returns the new function.
- */
- function overRest(func, start, transform) {
- start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
- return function() {
- var args = arguments,
- index = -1,
- length = nativeMax(args.length - start, 0),
- array = Array(length);
-
- while (++index < length) {
- array[index] = args[start + index];
- }
- index = -1;
- var otherArgs = Array(start + 1);
- while (++index < start) {
- otherArgs[index] = args[index];
- }
- otherArgs[start] = transform(array);
- return _apply(func, this, otherArgs);
- };
- }
-
- var _overRest = overRest;
-
- /**
- * A specialized version of `baseRest` which flattens the rest array.
- *
- * @private
- * @param {Function} func The function to apply a rest parameter to.
- * @returns {Function} Returns the new function.
- */
- function flatRest(func) {
- return _setToString(_overRest(func, undefined, flatten_1), func + '');
- }
-
- var _flatRest = flatRest;
-
- /** Used to compose bitmasks for function metadata. */
- var WRAP_REARG_FLAG = 256;
-
- /**
- * Creates a function that invokes `func` with arguments arranged according
- * to the specified `indexes` where the argument value at the first index is
- * provided as the first argument, the argument value at the second index is
- * provided as the second argument, and so on.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Function
- * @param {Function} func The function to rearrange arguments for.
- * @param {...(number|number[])} indexes The arranged argument indexes.
- * @returns {Function} Returns the new function.
- * @example
- *
- * var rearged = _.rearg(function(a, b, c) {
- * return [a, b, c];
- * }, [2, 0, 1]);
- *
- * rearged('b', 'c', 'a')
- * // => ['a', 'b', 'c']
- */
- var rearg = _flatRest(function(func, indexes) {
- return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
- });
-
- var rearg_1 = rearg;
-
- /**
- * Converts `value` to a property path array.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Util
- * @param {*} value The value to convert.
- * @returns {Array} Returns the new property path array.
- * @example
- *
- * _.toPath('a.b.c');
- * // => ['a', 'b', 'c']
- *
- * _.toPath('a[0].b.c');
- * // => ['a', '0', 'b', 'c']
- */
- function toPath(value) {
- if (isArray_1(value)) {
- return _arrayMap(value, _toKey);
- }
- return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
- }
-
- var toPath_1 = toPath;
-
- var _util = {
- 'ary': ary_1,
- 'assign': _baseAssign,
- 'clone': clone_1,
- 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
- 'forEach': _arrayEach,
- 'isArray': isArray_1,
- 'isError': isError_1,
- 'isFunction': isFunction_1,
- 'isWeakMap': isWeakMap_1,
- 'iteratee': iteratee_1,
- 'keys': _baseKeys,
- 'rearg': rearg_1,
- 'toInteger': toInteger_1,
- 'toPath': toPath_1
- };
-
- /**
- * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
- * version with conversion `options` applied. If `name` is an object its methods
- * will be converted.
- *
- * @param {string} name The name of the function to wrap.
- * @param {Function} [func] The function to wrap.
- * @param {Object} [options] The options object. See `baseConvert` for more details.
- * @returns {Function|Object} Returns the converted function or object.
- */
- function convert$2(name, func, options) {
- return _baseConvert(_util, name, func, options);
- }
-
- var convert_1 = convert$2;
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
- var convert = convert_1,
- func = convert('curry', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
-
- func.placeholder = placeholder;
- module.exports = func;
-
- });
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryN.js", function (module, exports) {
- var convert = convert_1,
- func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
-
- func.placeholder = placeholder;
- module.exports = func;
-
- });
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
- var convert = convert_1,
- func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
-
- func.placeholder = placeholder;
- module.exports = func;
-
- });
-
- commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
- var convert = convert_1,
- func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
-
- func.placeholder = placeholder;
- module.exports = func;
-
- });
-
- var moment = createCommonjsModule(function (module, exports) {
- (function (global, factory) {
- module.exports = factory() ;
- }(commonjsGlobal, (function () {
- var hookCallback;
-
- function hooks() {
- return hookCallback.apply(null, arguments);
- }
-
- // This is done to register the method called with moment()
- // without creating circular dependencies.
- function setHookCallback(callback) {
- hookCallback = callback;
- }
-
- function isArray(input) {
- return (
- input instanceof Array ||
- Object.prototype.toString.call(input) === '[object Array]'
- );
- }
-
- function isObject(input) {
- // IE8 will treat undefined and null as object if it wasn't for
- // input != null
- return (
- input != null &&
- Object.prototype.toString.call(input) === '[object Object]'
- );
- }
-
- function hasOwnProp(a, b) {
- return Object.prototype.hasOwnProperty.call(a, b);
- }
-
- function isObjectEmpty(obj) {
- if (Object.getOwnPropertyNames) {
- return Object.getOwnPropertyNames(obj).length === 0;
- } else {
- var k;
- for (k in obj) {
- if (hasOwnProp(obj, k)) {
- return false;
- }
- }
- return true;
- }
- }
-
- function isUndefined(input) {
- return input === void 0;
- }
-
- function isNumber(input) {
- return (
- typeof input === 'number' ||
- Object.prototype.toString.call(input) === '[object Number]'
- );
- }
-
- function isDate(input) {
- return (
- input instanceof Date ||
- Object.prototype.toString.call(input) === '[object Date]'
- );
- }
-
- function map(arr, fn) {
- var res = [],
- i;
- for (i = 0; i < arr.length; ++i) {
- res.push(fn(arr[i], i));
- }
- return res;
- }
-
- function extend(a, b) {
- for (var i in b) {
- if (hasOwnProp(b, i)) {
- a[i] = b[i];
- }
- }
-
- if (hasOwnProp(b, 'toString')) {
- a.toString = b.toString;
- }
-
- if (hasOwnProp(b, 'valueOf')) {
- a.valueOf = b.valueOf;
- }
-
- return a;
- }
-
- function createUTC(input, format, locale, strict) {
- return createLocalOrUTC(input, format, locale, strict, true).utc();
- }
-
- function defaultParsingFlags() {
- // We need to deep clone this object.
- return {
- empty: false,
- unusedTokens: [],
- unusedInput: [],
- overflow: -2,
- charsLeftOver: 0,
- nullInput: false,
- invalidEra: null,
- invalidMonth: null,
- invalidFormat: false,
- userInvalidated: false,
- iso: false,
- parsedDateParts: [],
- era: null,
- meridiem: null,
- rfc2822: false,
- weekdayMismatch: false,
- };
- }
-
- function getParsingFlags(m) {
- if (m._pf == null) {
- m._pf = defaultParsingFlags();
- }
- return m._pf;
- }
-
- var some;
- if (Array.prototype.some) {
- some = Array.prototype.some;
- } else {
- some = function (fun) {
- var t = Object(this),
- len = t.length >>> 0,
- i;
-
- for (i = 0; i < len; i++) {
- if (i in t && fun.call(this, t[i], i, t)) {
- return true;
- }
- }
-
- return false;
- };
- }
-
- function isValid(m) {
- if (m._isValid == null) {
- var flags = getParsingFlags(m),
- parsedParts = some.call(flags.parsedDateParts, function (i) {
- return i != null;
- }),
- isNowValid =
- !isNaN(m._d.getTime()) &&
- flags.overflow < 0 &&
- !flags.empty &&
- !flags.invalidEra &&
- !flags.invalidMonth &&
- !flags.invalidWeekday &&
- !flags.weekdayMismatch &&
- !flags.nullInput &&
- !flags.invalidFormat &&
- !flags.userInvalidated &&
- (!flags.meridiem || (flags.meridiem && parsedParts));
-
- if (m._strict) {
- isNowValid =
- isNowValid &&
- flags.charsLeftOver === 0 &&
- flags.unusedTokens.length === 0 &&
- flags.bigHour === undefined;
- }
-
- if (Object.isFrozen == null || !Object.isFrozen(m)) {
- m._isValid = isNowValid;
- } else {
- return isNowValid;
- }
- }
- return m._isValid;
- }
-
- function createInvalid(flags) {
- var m = createUTC(NaN);
- if (flags != null) {
- extend(getParsingFlags(m), flags);
- } else {
- getParsingFlags(m).userInvalidated = true;
- }
-
- return m;
- }
-
- // Plugins that add properties should also add the key here (null value),
- // so we can properly clone ourselves.
- var momentProperties = (hooks.momentProperties = []),
- updateInProgress = false;
-
- function copyConfig(to, from) {
- var i, prop, val;
-
- if (!isUndefined(from._isAMomentObject)) {
- to._isAMomentObject = from._isAMomentObject;
- }
- if (!isUndefined(from._i)) {
- to._i = from._i;
- }
- if (!isUndefined(from._f)) {
- to._f = from._f;
- }
- if (!isUndefined(from._l)) {
- to._l = from._l;
- }
- if (!isUndefined(from._strict)) {
- to._strict = from._strict;
- }
- if (!isUndefined(from._tzm)) {
- to._tzm = from._tzm;
- }
- if (!isUndefined(from._isUTC)) {
- to._isUTC = from._isUTC;
- }
- if (!isUndefined(from._offset)) {
- to._offset = from._offset;
- }
- if (!isUndefined(from._pf)) {
- to._pf = getParsingFlags(from);
- }
- if (!isUndefined(from._locale)) {
- to._locale = from._locale;
- }
-
- if (momentProperties.length > 0) {
- for (i = 0; i < momentProperties.length; i++) {
- prop = momentProperties[i];
- val = from[prop];
- if (!isUndefined(val)) {
- to[prop] = val;
- }
- }
- }
-
- return to;
- }
-
- // Moment prototype object
- function Moment(config) {
- copyConfig(this, config);
- this._d = new Date(config._d != null ? config._d.getTime() : NaN);
- if (!this.isValid()) {
- this._d = new Date(NaN);
- }
- // Prevent infinite loop in case updateOffset creates new moment
- // objects.
- if (updateInProgress === false) {
- updateInProgress = true;
- hooks.updateOffset(this);
- updateInProgress = false;
- }
- }
-
- function isMoment(obj) {
- return (
- obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
- );
- }
-
- function warn(msg) {
- if (
- hooks.suppressDeprecationWarnings === false &&
- typeof console !== 'undefined' &&
- console.warn
- ) {
- console.warn('Deprecation warning: ' + msg);
- }
- }
-
- function deprecate(msg, fn) {
- var firstTime = true;
-
- return extend(function () {
- if (hooks.deprecationHandler != null) {
- hooks.deprecationHandler(null, msg);
- }
- if (firstTime) {
- var args = [],
- arg,
- i,
- key;
- for (i = 0; i < arguments.length; i++) {
- arg = '';
- if (typeof arguments[i] === 'object') {
- arg += '\n[' + i + '] ';
- for (key in arguments[0]) {
- if (hasOwnProp(arguments[0], key)) {
- arg += key + ': ' + arguments[0][key] + ', ';
- }
- }
- arg = arg.slice(0, -2); // Remove trailing comma and space
- } else {
- arg = arguments[i];
- }
- args.push(arg);
- }
- warn(
- msg +
- '\nArguments: ' +
- Array.prototype.slice.call(args).join('') +
- '\n' +
- new Error().stack
- );
- firstTime = false;
- }
- return fn.apply(this, arguments);
- }, fn);
- }
-
- var deprecations = {};
-
- function deprecateSimple(name, msg) {
- if (hooks.deprecationHandler != null) {
- hooks.deprecationHandler(name, msg);
- }
- if (!deprecations[name]) {
- warn(msg);
- deprecations[name] = true;
- }
- }
-
- hooks.suppressDeprecationWarnings = false;
- hooks.deprecationHandler = null;
-
- function isFunction(input) {
- return (
- (typeof Function !== 'undefined' && input instanceof Function) ||
- Object.prototype.toString.call(input) === '[object Function]'
- );
- }
-
- function set(config) {
- var prop, i;
- for (i in config) {
- if (hasOwnProp(config, i)) {
- prop = config[i];
- if (isFunction(prop)) {
- this[i] = prop;
- } else {
- this['_' + i] = prop;
- }
- }
- }
- this._config = config;
- // Lenient ordinal parsing accepts just a number in addition to
- // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
- // TODO: Remove "ordinalParse" fallback in next major release.
- this._dayOfMonthOrdinalParseLenient = new RegExp(
- (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
- '|' +
- /\d{1,2}/.source
- );
- }
-
- function mergeConfigs(parentConfig, childConfig) {
- var res = extend({}, parentConfig),
- prop;
- for (prop in childConfig) {
- if (hasOwnProp(childConfig, prop)) {
- if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
- res[prop] = {};
- extend(res[prop], parentConfig[prop]);
- extend(res[prop], childConfig[prop]);
- } else if (childConfig[prop] != null) {
- res[prop] = childConfig[prop];
- } else {
- delete res[prop];
- }
- }
- }
- for (prop in parentConfig) {
- if (
- hasOwnProp(parentConfig, prop) &&
- !hasOwnProp(childConfig, prop) &&
- isObject(parentConfig[prop])
- ) {
- // make sure changes to properties don't modify parent config
- res[prop] = extend({}, res[prop]);
- }
- }
- return res;
- }
-
- function Locale(config) {
- if (config != null) {
- this.set(config);
- }
- }
-
- var keys;
-
- if (Object.keys) {
- keys = Object.keys;
- } else {
- keys = function (obj) {
- var i,
- res = [];
- for (i in obj) {
- if (hasOwnProp(obj, i)) {
- res.push(i);
- }
- }
- return res;
- };
- }
-
- var defaultCalendar = {
- sameDay: '[Today at] LT',
- nextDay: '[Tomorrow at] LT',
- nextWeek: 'dddd [at] LT',
- lastDay: '[Yesterday at] LT',
- lastWeek: '[Last] dddd [at] LT',
- sameElse: 'L',
- };
-
- function calendar(key, mom, now) {
- var output = this._calendar[key] || this._calendar['sameElse'];
- return isFunction(output) ? output.call(mom, now) : output;
- }
-
- function zeroFill(number, targetLength, forceSign) {
- var absNumber = '' + Math.abs(number),
- zerosToFill = targetLength - absNumber.length,
- sign = number >= 0;
- return (
- (sign ? (forceSign ? '+' : '') : '-') +
- Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
- absNumber
- );
- }
-
- 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,
- localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
- formatFunctions = {},
- formatTokenFunctions = {};
-
- // token: 'M'
- // padded: ['MM', 2]
- // ordinal: 'Mo'
- // callback: function () { this.month() + 1 }
- function addFormatToken(token, padded, ordinal, callback) {
- var func = callback;
- if (typeof callback === 'string') {
- func = function () {
- return this[callback]();
- };
- }
- if (token) {
- formatTokenFunctions[token] = func;
- }
- if (padded) {
- formatTokenFunctions[padded[0]] = function () {
- return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
- };
- }
- if (ordinal) {
- formatTokenFunctions[ordinal] = function () {
- return this.localeData().ordinal(
- func.apply(this, arguments),
- token
- );
- };
- }
- }
-
- function removeFormattingTokens(input) {
- if (input.match(/\[[\s\S]/)) {
- return input.replace(/^\[|\]$/g, '');
- }
- return input.replace(/\\/g, '');
- }
-
- function makeFormatFunction(format) {
- var array = format.match(formattingTokens),
- i,
- length;
-
- for (i = 0, length = array.length; i < length; i++) {
- if (formatTokenFunctions[array[i]]) {
- array[i] = formatTokenFunctions[array[i]];
- } else {
- array[i] = removeFormattingTokens(array[i]);
- }
- }
-
- return function (mom) {
- var output = '',
- i;
- for (i = 0; i < length; i++) {
- output += isFunction(array[i])
- ? array[i].call(mom, format)
- : array[i];
- }
- return output;
- };
- }
-
- // format date using native date object
- function formatMoment(m, format) {
- if (!m.isValid()) {
- return m.localeData().invalidDate();
- }
-
- format = expandFormat(format, m.localeData());
- formatFunctions[format] =
- formatFunctions[format] || makeFormatFunction(format);
-
- return formatFunctions[format](m);
- }
-
- function expandFormat(format, locale) {
- var i = 5;
-
- function replaceLongDateFormatTokens(input) {
- return locale.longDateFormat(input) || input;
- }
-
- localFormattingTokens.lastIndex = 0;
- while (i >= 0 && localFormattingTokens.test(format)) {
- format = format.replace(
- localFormattingTokens,
- replaceLongDateFormatTokens
- );
- localFormattingTokens.lastIndex = 0;
- i -= 1;
- }
-
- return format;
- }
-
- var defaultLongDateFormat = {
- LTS: 'h:mm:ss A',
- LT: 'h:mm A',
- L: 'MM/DD/YYYY',
- LL: 'MMMM D, YYYY',
- LLL: 'MMMM D, YYYY h:mm A',
- LLLL: 'dddd, MMMM D, YYYY h:mm A',
- };
-
- function longDateFormat(key) {
- var format = this._longDateFormat[key],
- formatUpper = this._longDateFormat[key.toUpperCase()];
-
- if (format || !formatUpper) {
- return format;
- }
-
- this._longDateFormat[key] = formatUpper
- .match(formattingTokens)
- .map(function (tok) {
- if (
- tok === 'MMMM' ||
- tok === 'MM' ||
- tok === 'DD' ||
- tok === 'dddd'
- ) {
- return tok.slice(1);
- }
- return tok;
- })
- .join('');
-
- return this._longDateFormat[key];
- }
-
- var defaultInvalidDate = 'Invalid date';
-
- function invalidDate() {
- return this._invalidDate;
- }
-
- var defaultOrdinal = '%d',
- defaultDayOfMonthOrdinalParse = /\d{1,2}/;
-
- function ordinal(number) {
- return this._ordinal.replace('%d', number);
- }
-
- var defaultRelativeTime = {
- future: 'in %s',
- past: '%s ago',
- s: 'a few seconds',
- ss: '%d seconds',
- m: 'a minute',
- mm: '%d minutes',
- h: 'an hour',
- hh: '%d hours',
- d: 'a day',
- dd: '%d days',
- w: 'a week',
- ww: '%d weeks',
- M: 'a month',
- MM: '%d months',
- y: 'a year',
- yy: '%d years',
- };
-
- function relativeTime(number, withoutSuffix, string, isFuture) {
- var output = this._relativeTime[string];
- return isFunction(output)
- ? output(number, withoutSuffix, string, isFuture)
- : output.replace(/%d/i, number);
- }
-
- function pastFuture(diff, output) {
- var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
- return isFunction(format) ? format(output) : format.replace(/%s/i, output);
- }
-
- var aliases = {};
-
- function addUnitAlias(unit, shorthand) {
- var lowerCase = unit.toLowerCase();
- aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
- }
-
- function normalizeUnits(units) {
- return typeof units === 'string'
- ? aliases[units] || aliases[units.toLowerCase()]
- : undefined;
- }
-
- function normalizeObjectUnits(inputObject) {
- var normalizedInput = {},
- normalizedProp,
- prop;
-
- for (prop in inputObject) {
- if (hasOwnProp(inputObject, prop)) {
- normalizedProp = normalizeUnits(prop);
- if (normalizedProp) {
- normalizedInput[normalizedProp] = inputObject[prop];
- }
- }
- }
-
- return normalizedInput;
- }
-
- var priorities = {};
-
- function addUnitPriority(unit, priority) {
- priorities[unit] = priority;
- }
-
- function getPrioritizedUnits(unitsObj) {
- var units = [],
- u;
- for (u in unitsObj) {
- if (hasOwnProp(unitsObj, u)) {
- units.push({ unit: u, priority: priorities[u] });
- }
- }
- units.sort(function (a, b) {
- return a.priority - b.priority;
- });
- return units;
- }
-
- function isLeapYear(year) {
- return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
- }
-
- function absFloor(number) {
- if (number < 0) {
- // -0 -> 0
- return Math.ceil(number) || 0;
- } else {
- return Math.floor(number);
- }
- }
-
- function toInt(argumentForCoercion) {
- var coercedNumber = +argumentForCoercion,
- value = 0;
-
- if (coercedNumber !== 0 && isFinite(coercedNumber)) {
- value = absFloor(coercedNumber);
- }
-
- return value;
- }
-
- function makeGetSet(unit, keepTime) {
- return function (value) {
- if (value != null) {
- set$1(this, unit, value);
- hooks.updateOffset(this, keepTime);
- return this;
- } else {
- return get(this, unit);
- }
- };
- }
-
- function get(mom, unit) {
- return mom.isValid()
- ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
- : NaN;
- }
-
- function set$1(mom, unit, value) {
- if (mom.isValid() && !isNaN(value)) {
- if (
- unit === 'FullYear' &&
- isLeapYear(mom.year()) &&
- mom.month() === 1 &&
- mom.date() === 29
- ) {
- value = toInt(value);
- mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
- value,
- mom.month(),
- daysInMonth(value, mom.month())
- );
- } else {
- mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
- }
- }
- }
-
- // MOMENTS
-
- function stringGet(units) {
- units = normalizeUnits(units);
- if (isFunction(this[units])) {
- return this[units]();
- }
- return this;
- }
-
- function stringSet(units, value) {
- if (typeof units === 'object') {
- units = normalizeObjectUnits(units);
- var prioritized = getPrioritizedUnits(units),
- i;
- for (i = 0; i < prioritized.length; i++) {
- this[prioritized[i].unit](units[prioritized[i].unit]);
- }
- } else {
- units = normalizeUnits(units);
- if (isFunction(this[units])) {
- return this[units](value);
- }
- }
- return this;
- }
-
- var match1 = /\d/, // 0 - 9
- match2 = /\d\d/, // 00 - 99
- match3 = /\d{3}/, // 000 - 999
- match4 = /\d{4}/, // 0000 - 9999
- match6 = /[+-]?\d{6}/, // -999999 - 999999
- match1to2 = /\d\d?/, // 0 - 99
- match3to4 = /\d\d\d\d?/, // 999 - 9999
- match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
- match1to3 = /\d{1,3}/, // 0 - 999
- match1to4 = /\d{1,4}/, // 0 - 9999
- match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
- matchUnsigned = /\d+/, // 0 - inf
- matchSigned = /[+-]?\d+/, // -inf - inf
- matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
- matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
- matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
- // any word (or two) characters or numbers including two/three word month in arabic.
- // includes scottish gaelic two word and hyphenated months
- 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,
- regexes;
-
- regexes = {};
-
- function addRegexToken(token, regex, strictRegex) {
- regexes[token] = isFunction(regex)
- ? regex
- : function (isStrict, localeData) {
- return isStrict && strictRegex ? strictRegex : regex;
- };
- }
-
- function getParseRegexForToken(token, config) {
- if (!hasOwnProp(regexes, token)) {
- return new RegExp(unescapeFormat(token));
- }
-
- return regexes[token](config._strict, config._locale);
- }
-
- // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
- function unescapeFormat(s) {
- return regexEscape(
- s
- .replace('\\', '')
- .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
- matched,
- p1,
- p2,
- p3,
- p4
- ) {
- return p1 || p2 || p3 || p4;
- })
- );
- }
-
- function regexEscape(s) {
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
- }
-
- var tokens = {};
-
- function addParseToken(token, callback) {
- var i,
- func = callback;
- if (typeof token === 'string') {
- token = [token];
- }
- if (isNumber(callback)) {
- func = function (input, array) {
- array[callback] = toInt(input);
- };
- }
- for (i = 0; i < token.length; i++) {
- tokens[token[i]] = func;
- }
- }
-
- function addWeekParseToken(token, callback) {
- addParseToken(token, function (input, array, config, token) {
- config._w = config._w || {};
- callback(input, config._w, config, token);
- });
- }
-
- function addTimeToArrayFromToken(token, input, config) {
- if (input != null && hasOwnProp(tokens, token)) {
- tokens[token](input, config._a, config, token);
- }
- }
-
- var YEAR = 0,
- MONTH = 1,
- DATE = 2,
- HOUR = 3,
- MINUTE = 4,
- SECOND = 5,
- MILLISECOND = 6,
- WEEK = 7,
- WEEKDAY = 8;
-
- function mod(n, x) {
- return ((n % x) + x) % x;
- }
-
- var indexOf;
-
- if (Array.prototype.indexOf) {
- indexOf = Array.prototype.indexOf;
- } else {
- indexOf = function (o) {
- // I know
- var i;
- for (i = 0; i < this.length; ++i) {
- if (this[i] === o) {
- return i;
- }
- }
- return -1;
- };
- }
-
- function daysInMonth(year, month) {
- if (isNaN(year) || isNaN(month)) {
- return NaN;
- }
- var modMonth = mod(month, 12);
- year += (month - modMonth) / 12;
- return modMonth === 1
- ? isLeapYear(year)
- ? 29
- : 28
- : 31 - ((modMonth % 7) % 2);
- }
-
- // FORMATTING
-
- addFormatToken('M', ['MM', 2], 'Mo', function () {
- return this.month() + 1;
- });
-
- addFormatToken('MMM', 0, 0, function (format) {
- return this.localeData().monthsShort(this, format);
- });
-
- addFormatToken('MMMM', 0, 0, function (format) {
- return this.localeData().months(this, format);
- });
-
- // ALIASES
-
- addUnitAlias('month', 'M');
-
- // PRIORITY
-
- addUnitPriority('month', 8);
-
- // PARSING
-
- addRegexToken('M', match1to2);
- addRegexToken('MM', match1to2, match2);
- addRegexToken('MMM', function (isStrict, locale) {
- return locale.monthsShortRegex(isStrict);
- });
- addRegexToken('MMMM', function (isStrict, locale) {
- return locale.monthsRegex(isStrict);
- });
-
- addParseToken(['M', 'MM'], function (input, array) {
- array[MONTH] = toInt(input) - 1;
- });
-
- addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
- var month = config._locale.monthsParse(input, token, config._strict);
- // if we didn't find a month name, mark the date as invalid.
- if (month != null) {
- array[MONTH] = month;
- } else {
- getParsingFlags(config).invalidMonth = input;
- }
- });
-
- // LOCALES
-
- var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
- '_'
- ),
- defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
- '_'
- ),
- MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
- defaultMonthsShortRegex = matchWord,
- defaultMonthsRegex = matchWord;
-
- function localeMonths(m, format) {
- if (!m) {
- return isArray(this._months)
- ? this._months
- : this._months['standalone'];
- }
- return isArray(this._months)
- ? this._months[m.month()]
- : this._months[
- (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
- ? 'format'
- : 'standalone'
- ][m.month()];
- }
-
- function localeMonthsShort(m, format) {
- if (!m) {
- return isArray(this._monthsShort)
- ? this._monthsShort
- : this._monthsShort['standalone'];
- }
- return isArray(this._monthsShort)
- ? this._monthsShort[m.month()]
- : this._monthsShort[
- MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
- ][m.month()];
- }
-
- function handleStrictParse(monthName, format, strict) {
- var i,
- ii,
- mom,
- llc = monthName.toLocaleLowerCase();
- if (!this._monthsParse) {
- // this is not used
- this._monthsParse = [];
- this._longMonthsParse = [];
- this._shortMonthsParse = [];
- for (i = 0; i < 12; ++i) {
- mom = createUTC([2000, i]);
- this._shortMonthsParse[i] = this.monthsShort(
- mom,
- ''
- ).toLocaleLowerCase();
- this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
- }
- }
-
- if (strict) {
- if (format === 'MMM') {
- ii = indexOf.call(this._shortMonthsParse, llc);
- return ii !== -1 ? ii : null;
- } else {
- ii = indexOf.call(this._longMonthsParse, llc);
- return ii !== -1 ? ii : null;
- }
- } else {
- if (format === 'MMM') {
- ii = indexOf.call(this._shortMonthsParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._longMonthsParse, llc);
- return ii !== -1 ? ii : null;
- } else {
- ii = indexOf.call(this._longMonthsParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._shortMonthsParse, llc);
- return ii !== -1 ? ii : null;
- }
- }
- }
-
- function localeMonthsParse(monthName, format, strict) {
- var i, mom, regex;
-
- if (this._monthsParseExact) {
- return handleStrictParse.call(this, monthName, format, strict);
- }
-
- if (!this._monthsParse) {
- this._monthsParse = [];
- this._longMonthsParse = [];
- this._shortMonthsParse = [];
- }
-
- // TODO: add sorting
- // Sorting makes sure if one month (or abbr) is a prefix of another
- // see sorting in computeMonthsParse
- for (i = 0; i < 12; i++) {
- // make the regex if we don't have it already
- mom = createUTC([2000, i]);
- if (strict && !this._longMonthsParse[i]) {
- this._longMonthsParse[i] = new RegExp(
- '^' + this.months(mom, '').replace('.', '') + '$',
- 'i'
- );
- this._shortMonthsParse[i] = new RegExp(
- '^' + this.monthsShort(mom, '').replace('.', '') + '$',
- 'i'
- );
- }
- if (!strict && !this._monthsParse[i]) {
- regex =
- '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
- this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
- }
- // test the regex
- if (
- strict &&
- format === 'MMMM' &&
- this._longMonthsParse[i].test(monthName)
- ) {
- return i;
- } else if (
- strict &&
- format === 'MMM' &&
- this._shortMonthsParse[i].test(monthName)
- ) {
- return i;
- } else if (!strict && this._monthsParse[i].test(monthName)) {
- return i;
- }
- }
- }
-
- // MOMENTS
-
- function setMonth(mom, value) {
- var dayOfMonth;
-
- if (!mom.isValid()) {
- // No op
- return mom;
- }
-
- if (typeof value === 'string') {
- if (/^\d+$/.test(value)) {
- value = toInt(value);
- } else {
- value = mom.localeData().monthsParse(value);
- // TODO: Another silent failure?
- if (!isNumber(value)) {
- return mom;
- }
- }
- }
-
- dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
- mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
- return mom;
- }
-
- function getSetMonth(value) {
- if (value != null) {
- setMonth(this, value);
- hooks.updateOffset(this, true);
- return this;
- } else {
- return get(this, 'Month');
- }
- }
-
- function getDaysInMonth() {
- return daysInMonth(this.year(), this.month());
- }
-
- function monthsShortRegex(isStrict) {
- if (this._monthsParseExact) {
- if (!hasOwnProp(this, '_monthsRegex')) {
- computeMonthsParse.call(this);
- }
- if (isStrict) {
- return this._monthsShortStrictRegex;
- } else {
- return this._monthsShortRegex;
- }
- } else {
- if (!hasOwnProp(this, '_monthsShortRegex')) {
- this._monthsShortRegex = defaultMonthsShortRegex;
- }
- return this._monthsShortStrictRegex && isStrict
- ? this._monthsShortStrictRegex
- : this._monthsShortRegex;
- }
- }
-
- function monthsRegex(isStrict) {
- if (this._monthsParseExact) {
- if (!hasOwnProp(this, '_monthsRegex')) {
- computeMonthsParse.call(this);
- }
- if (isStrict) {
- return this._monthsStrictRegex;
- } else {
- return this._monthsRegex;
- }
- } else {
- if (!hasOwnProp(this, '_monthsRegex')) {
- this._monthsRegex = defaultMonthsRegex;
- }
- return this._monthsStrictRegex && isStrict
- ? this._monthsStrictRegex
- : this._monthsRegex;
- }
- }
-
- function computeMonthsParse() {
- function cmpLenRev(a, b) {
- return b.length - a.length;
- }
-
- var shortPieces = [],
- longPieces = [],
- mixedPieces = [],
- i,
- mom;
- for (i = 0; i < 12; i++) {
- // make the regex if we don't have it already
- mom = createUTC([2000, i]);
- shortPieces.push(this.monthsShort(mom, ''));
- longPieces.push(this.months(mom, ''));
- mixedPieces.push(this.months(mom, ''));
- mixedPieces.push(this.monthsShort(mom, ''));
- }
- // Sorting makes sure if one month (or abbr) is a prefix of another it
- // will match the longer piece.
- shortPieces.sort(cmpLenRev);
- longPieces.sort(cmpLenRev);
- mixedPieces.sort(cmpLenRev);
- for (i = 0; i < 12; i++) {
- shortPieces[i] = regexEscape(shortPieces[i]);
- longPieces[i] = regexEscape(longPieces[i]);
- }
- for (i = 0; i < 24; i++) {
- mixedPieces[i] = regexEscape(mixedPieces[i]);
- }
-
- this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
- this._monthsShortRegex = this._monthsRegex;
- this._monthsStrictRegex = new RegExp(
- '^(' + longPieces.join('|') + ')',
- 'i'
- );
- this._monthsShortStrictRegex = new RegExp(
- '^(' + shortPieces.join('|') + ')',
- 'i'
- );
- }
-
- // FORMATTING
-
- addFormatToken('Y', 0, 0, function () {
- var y = this.year();
- return y <= 9999 ? zeroFill(y, 4) : '+' + y;
- });
-
- addFormatToken(0, ['YY', 2], 0, function () {
- return this.year() % 100;
- });
-
- addFormatToken(0, ['YYYY', 4], 0, 'year');
- addFormatToken(0, ['YYYYY', 5], 0, 'year');
- addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
-
- // ALIASES
-
- addUnitAlias('year', 'y');
-
- // PRIORITIES
-
- addUnitPriority('year', 1);
-
- // PARSING
-
- addRegexToken('Y', matchSigned);
- addRegexToken('YY', match1to2, match2);
- addRegexToken('YYYY', match1to4, match4);
- addRegexToken('YYYYY', match1to6, match6);
- addRegexToken('YYYYYY', match1to6, match6);
-
- addParseToken(['YYYYY', 'YYYYYY'], YEAR);
- addParseToken('YYYY', function (input, array) {
- array[YEAR] =
- input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
- });
- addParseToken('YY', function (input, array) {
- array[YEAR] = hooks.parseTwoDigitYear(input);
- });
- addParseToken('Y', function (input, array) {
- array[YEAR] = parseInt(input, 10);
- });
-
- // HELPERS
-
- function daysInYear(year) {
- return isLeapYear(year) ? 366 : 365;
- }
-
- // HOOKS
-
- hooks.parseTwoDigitYear = function (input) {
- return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
- };
-
- // MOMENTS
-
- var getSetYear = makeGetSet('FullYear', true);
-
- function getIsLeapYear() {
- return isLeapYear(this.year());
- }
-
- function createDate(y, m, d, h, M, s, ms) {
- // can't just apply() to create a date:
- // https://stackoverflow.com/q/181348
- var date;
- // the date constructor remaps years 0-99 to 1900-1999
- if (y < 100 && y >= 0) {
- // preserve leap years using a full 400 year cycle, then reset
- date = new Date(y + 400, m, d, h, M, s, ms);
- if (isFinite(date.getFullYear())) {
- date.setFullYear(y);
- }
- } else {
- date = new Date(y, m, d, h, M, s, ms);
- }
-
- return date;
- }
-
- function createUTCDate(y) {
- var date, args;
- // the Date.UTC function remaps years 0-99 to 1900-1999
- if (y < 100 && y >= 0) {
- args = Array.prototype.slice.call(arguments);
- // preserve leap years using a full 400 year cycle, then reset
- args[0] = y + 400;
- date = new Date(Date.UTC.apply(null, args));
- if (isFinite(date.getUTCFullYear())) {
- date.setUTCFullYear(y);
- }
- } else {
- date = new Date(Date.UTC.apply(null, arguments));
- }
-
- return date;
- }
-
- // start-of-first-week - start-of-year
- function firstWeekOffset(year, dow, doy) {
- var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
- fwd = 7 + dow - doy,
- // first-week day local weekday -- which local weekday is fwd
- fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
-
- return -fwdlw + fwd - 1;
- }
-
- // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
- function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
- var localWeekday = (7 + weekday - dow) % 7,
- weekOffset = firstWeekOffset(year, dow, doy),
- dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
- resYear,
- resDayOfYear;
-
- if (dayOfYear <= 0) {
- resYear = year - 1;
- resDayOfYear = daysInYear(resYear) + dayOfYear;
- } else if (dayOfYear > daysInYear(year)) {
- resYear = year + 1;
- resDayOfYear = dayOfYear - daysInYear(year);
- } else {
- resYear = year;
- resDayOfYear = dayOfYear;
- }
-
- return {
- year: resYear,
- dayOfYear: resDayOfYear,
- };
- }
-
- function weekOfYear(mom, dow, doy) {
- var weekOffset = firstWeekOffset(mom.year(), dow, doy),
- week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
- resWeek,
- resYear;
-
- if (week < 1) {
- resYear = mom.year() - 1;
- resWeek = week + weeksInYear(resYear, dow, doy);
- } else if (week > weeksInYear(mom.year(), dow, doy)) {
- resWeek = week - weeksInYear(mom.year(), dow, doy);
- resYear = mom.year() + 1;
- } else {
- resYear = mom.year();
- resWeek = week;
- }
-
- return {
- week: resWeek,
- year: resYear,
- };
- }
-
- function weeksInYear(year, dow, doy) {
- var weekOffset = firstWeekOffset(year, dow, doy),
- weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
- return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
- }
-
- // FORMATTING
-
- addFormatToken('w', ['ww', 2], 'wo', 'week');
- addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
-
- // ALIASES
-
- addUnitAlias('week', 'w');
- addUnitAlias('isoWeek', 'W');
-
- // PRIORITIES
-
- addUnitPriority('week', 5);
- addUnitPriority('isoWeek', 5);
-
- // PARSING
-
- addRegexToken('w', match1to2);
- addRegexToken('ww', match1to2, match2);
- addRegexToken('W', match1to2);
- addRegexToken('WW', match1to2, match2);
-
- addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
- input,
- week,
- config,
- token
- ) {
- week[token.substr(0, 1)] = toInt(input);
- });
-
- // HELPERS
-
- // LOCALES
-
- function localeWeek(mom) {
- return weekOfYear(mom, this._week.dow, this._week.doy).week;
- }
-
- var defaultLocaleWeek = {
- dow: 0, // Sunday is the first day of the week.
- doy: 6, // The week that contains Jan 6th is the first week of the year.
- };
-
- function localeFirstDayOfWeek() {
- return this._week.dow;
- }
-
- function localeFirstDayOfYear() {
- return this._week.doy;
- }
-
- // MOMENTS
-
- function getSetWeek(input) {
- var week = this.localeData().week(this);
- return input == null ? week : this.add((input - week) * 7, 'd');
- }
-
- function getSetISOWeek(input) {
- var week = weekOfYear(this, 1, 4).week;
- return input == null ? week : this.add((input - week) * 7, 'd');
- }
-
- // FORMATTING
-
- addFormatToken('d', 0, 'do', 'day');
-
- addFormatToken('dd', 0, 0, function (format) {
- return this.localeData().weekdaysMin(this, format);
- });
-
- addFormatToken('ddd', 0, 0, function (format) {
- return this.localeData().weekdaysShort(this, format);
- });
-
- addFormatToken('dddd', 0, 0, function (format) {
- return this.localeData().weekdays(this, format);
- });
-
- addFormatToken('e', 0, 0, 'weekday');
- addFormatToken('E', 0, 0, 'isoWeekday');
-
- // ALIASES
-
- addUnitAlias('day', 'd');
- addUnitAlias('weekday', 'e');
- addUnitAlias('isoWeekday', 'E');
-
- // PRIORITY
- addUnitPriority('day', 11);
- addUnitPriority('weekday', 11);
- addUnitPriority('isoWeekday', 11);
-
- // PARSING
-
- addRegexToken('d', match1to2);
- addRegexToken('e', match1to2);
- addRegexToken('E', match1to2);
- addRegexToken('dd', function (isStrict, locale) {
- return locale.weekdaysMinRegex(isStrict);
- });
- addRegexToken('ddd', function (isStrict, locale) {
- return locale.weekdaysShortRegex(isStrict);
- });
- addRegexToken('dddd', function (isStrict, locale) {
- return locale.weekdaysRegex(isStrict);
- });
-
- addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
- var weekday = config._locale.weekdaysParse(input, token, config._strict);
- // if we didn't get a weekday name, mark the date as invalid
- if (weekday != null) {
- week.d = weekday;
- } else {
- getParsingFlags(config).invalidWeekday = input;
- }
- });
-
- addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
- week[token] = toInt(input);
- });
-
- // HELPERS
-
- function parseWeekday(input, locale) {
- if (typeof input !== 'string') {
- return input;
- }
-
- if (!isNaN(input)) {
- return parseInt(input, 10);
- }
-
- input = locale.weekdaysParse(input);
- if (typeof input === 'number') {
- return input;
- }
-
- return null;
- }
-
- function parseIsoWeekday(input, locale) {
- if (typeof input === 'string') {
- return locale.weekdaysParse(input) % 7 || 7;
- }
- return isNaN(input) ? null : input;
- }
-
- // LOCALES
- function shiftWeekdays(ws, n) {
- return ws.slice(n, 7).concat(ws.slice(0, n));
- }
-
- var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
- '_'
- ),
- defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
- defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
- defaultWeekdaysRegex = matchWord,
- defaultWeekdaysShortRegex = matchWord,
- defaultWeekdaysMinRegex = matchWord;
-
- function localeWeekdays(m, format) {
- var weekdays = isArray(this._weekdays)
- ? this._weekdays
- : this._weekdays[
- m && m !== true && this._weekdays.isFormat.test(format)
- ? 'format'
- : 'standalone'
- ];
- return m === true
- ? shiftWeekdays(weekdays, this._week.dow)
- : m
- ? weekdays[m.day()]
- : weekdays;
- }
-
- function localeWeekdaysShort(m) {
- return m === true
- ? shiftWeekdays(this._weekdaysShort, this._week.dow)
- : m
- ? this._weekdaysShort[m.day()]
- : this._weekdaysShort;
- }
-
- function localeWeekdaysMin(m) {
- return m === true
- ? shiftWeekdays(this._weekdaysMin, this._week.dow)
- : m
- ? this._weekdaysMin[m.day()]
- : this._weekdaysMin;
- }
-
- function handleStrictParse$1(weekdayName, format, strict) {
- var i,
- ii,
- mom,
- llc = weekdayName.toLocaleLowerCase();
- if (!this._weekdaysParse) {
- this._weekdaysParse = [];
- this._shortWeekdaysParse = [];
- this._minWeekdaysParse = [];
-
- for (i = 0; i < 7; ++i) {
- mom = createUTC([2000, 1]).day(i);
- this._minWeekdaysParse[i] = this.weekdaysMin(
- mom,
- ''
- ).toLocaleLowerCase();
- this._shortWeekdaysParse[i] = this.weekdaysShort(
- mom,
- ''
- ).toLocaleLowerCase();
- this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
- }
- }
-
- if (strict) {
- if (format === 'dddd') {
- ii = indexOf.call(this._weekdaysParse, llc);
- return ii !== -1 ? ii : null;
- } else if (format === 'ddd') {
- ii = indexOf.call(this._shortWeekdaysParse, llc);
- return ii !== -1 ? ii : null;
- } else {
- ii = indexOf.call(this._minWeekdaysParse, llc);
- return ii !== -1 ? ii : null;
- }
- } else {
- if (format === 'dddd') {
- ii = indexOf.call(this._weekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._shortWeekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._minWeekdaysParse, llc);
- return ii !== -1 ? ii : null;
- } else if (format === 'ddd') {
- ii = indexOf.call(this._shortWeekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._weekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._minWeekdaysParse, llc);
- return ii !== -1 ? ii : null;
- } else {
- ii = indexOf.call(this._minWeekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._weekdaysParse, llc);
- if (ii !== -1) {
- return ii;
- }
- ii = indexOf.call(this._shortWeekdaysParse, llc);
- return ii !== -1 ? ii : null;
- }
- }
- }
-
- function localeWeekdaysParse(weekdayName, format, strict) {
- var i, mom, regex;
-
- if (this._weekdaysParseExact) {
- return handleStrictParse$1.call(this, weekdayName, format, strict);
- }
-
- if (!this._weekdaysParse) {
- this._weekdaysParse = [];
- this._minWeekdaysParse = [];
- this._shortWeekdaysParse = [];
- this._fullWeekdaysParse = [];
- }
-
- for (i = 0; i < 7; i++) {
- // make the regex if we don't have it already
-
- mom = createUTC([2000, 1]).day(i);
- if (strict && !this._fullWeekdaysParse[i]) {
- this._fullWeekdaysParse[i] = new RegExp(
- '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
- 'i'
- );
- this._shortWeekdaysParse[i] = new RegExp(
- '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
- 'i'
- );
- this._minWeekdaysParse[i] = new RegExp(
- '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
- 'i'
- );
- }
- if (!this._weekdaysParse[i]) {
- regex =
- '^' +
- this.weekdays(mom, '') +
- '|^' +
- this.weekdaysShort(mom, '') +
- '|^' +
- this.weekdaysMin(mom, '');
- this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
- }
- // test the regex
- if (
- strict &&
- format === 'dddd' &&
- this._fullWeekdaysParse[i].test(weekdayName)
- ) {
- return i;
- } else if (
- strict &&
- format === 'ddd' &&
- this._shortWeekdaysParse[i].test(weekdayName)
- ) {
- return i;
- } else if (
- strict &&
- format === 'dd' &&
- this._minWeekdaysParse[i].test(weekdayName)
- ) {
- return i;
- } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
- return i;
- }
- }
- }
-
- // MOMENTS
-
- function getSetDayOfWeek(input) {
- if (!this.isValid()) {
- return input != null ? this : NaN;
- }
- var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
- if (input != null) {
- input = parseWeekday(input, this.localeData());
- return this.add(input - day, 'd');
- } else {
- return day;
- }
- }
-
- function getSetLocaleDayOfWeek(input) {
- if (!this.isValid()) {
- return input != null ? this : NaN;
- }
- var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
- return input == null ? weekday : this.add(input - weekday, 'd');
- }
-
- function getSetISODayOfWeek(input) {
- if (!this.isValid()) {
- return input != null ? this : NaN;
- }
-
- // behaves the same as moment#day except
- // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
- // as a setter, sunday should belong to the previous week.
-
- if (input != null) {
- var weekday = parseIsoWeekday(input, this.localeData());
- return this.day(this.day() % 7 ? weekday : weekday - 7);
- } else {
- return this.day() || 7;
- }
- }
-
- function weekdaysRegex(isStrict) {
- if (this._weekdaysParseExact) {
- if (!hasOwnProp(this, '_weekdaysRegex')) {
- computeWeekdaysParse.call(this);
- }
- if (isStrict) {
- return this._weekdaysStrictRegex;
- } else {
- return this._weekdaysRegex;
- }
- } else {
- if (!hasOwnProp(this, '_weekdaysRegex')) {
- this._weekdaysRegex = defaultWeekdaysRegex;
- }
- return this._weekdaysStrictRegex && isStrict
- ? this._weekdaysStrictRegex
- : this._weekdaysRegex;
- }
- }
-
- function weekdaysShortRegex(isStrict) {
- if (this._weekdaysParseExact) {
- if (!hasOwnProp(this, '_weekdaysRegex')) {
- computeWeekdaysParse.call(this);
- }
- if (isStrict) {
- return this._weekdaysShortStrictRegex;
- } else {
- return this._weekdaysShortRegex;
- }
- } else {
- if (!hasOwnProp(this, '_weekdaysShortRegex')) {
- this._weekdaysShortRegex = defaultWeekdaysShortRegex;
- }
- return this._weekdaysShortStrictRegex && isStrict
- ? this._weekdaysShortStrictRegex
- : this._weekdaysShortRegex;
- }
- }
-
- function weekdaysMinRegex(isStrict) {
- if (this._weekdaysParseExact) {
- if (!hasOwnProp(this, '_weekdaysRegex')) {
- computeWeekdaysParse.call(this);
- }
- if (isStrict) {
- return this._weekdaysMinStrictRegex;
- } else {
- return this._weekdaysMinRegex;
- }
- } else {
- if (!hasOwnProp(this, '_weekdaysMinRegex')) {
- this._weekdaysMinRegex = defaultWeekdaysMinRegex;
- }
- return this._weekdaysMinStrictRegex && isStrict
- ? this._weekdaysMinStrictRegex
- : this._weekdaysMinRegex;
- }
- }
-
- function computeWeekdaysParse() {
- function cmpLenRev(a, b) {
- return b.length - a.length;
- }
-
- var minPieces = [],
- shortPieces = [],
- longPieces = [],
- mixedPieces = [],
- i,
- mom,
- minp,
- shortp,
- longp;
- for (i = 0; i < 7; i++) {
- // make the regex if we don't have it already
- mom = createUTC([2000, 1]).day(i);
- minp = regexEscape(this.weekdaysMin(mom, ''));
- shortp = regexEscape(this.weekdaysShort(mom, ''));
- longp = regexEscape(this.weekdays(mom, ''));
- minPieces.push(minp);
- shortPieces.push(shortp);
- longPieces.push(longp);
- mixedPieces.push(minp);
- mixedPieces.push(shortp);
- mixedPieces.push(longp);
- }
- // Sorting makes sure if one weekday (or abbr) is a prefix of another it
- // will match the longer piece.
- minPieces.sort(cmpLenRev);
- shortPieces.sort(cmpLenRev);
- longPieces.sort(cmpLenRev);
- mixedPieces.sort(cmpLenRev);
-
- this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
- this._weekdaysShortRegex = this._weekdaysRegex;
- this._weekdaysMinRegex = this._weekdaysRegex;
-
- this._weekdaysStrictRegex = new RegExp(
- '^(' + longPieces.join('|') + ')',
- 'i'
- );
- this._weekdaysShortStrictRegex = new RegExp(
- '^(' + shortPieces.join('|') + ')',
- 'i'
- );
- this._weekdaysMinStrictRegex = new RegExp(
- '^(' + minPieces.join('|') + ')',
- 'i'
- );
- }
-
- // FORMATTING
-
- function hFormat() {
- return this.hours() % 12 || 12;
- }
-
- function kFormat() {
- return this.hours() || 24;
- }
-
- addFormatToken('H', ['HH', 2], 0, 'hour');
- addFormatToken('h', ['hh', 2], 0, hFormat);
- addFormatToken('k', ['kk', 2], 0, kFormat);
-
- addFormatToken('hmm', 0, 0, function () {
- return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
- });
-
- addFormatToken('hmmss', 0, 0, function () {
- return (
- '' +
- hFormat.apply(this) +
- zeroFill(this.minutes(), 2) +
- zeroFill(this.seconds(), 2)
- );
- });
-
- addFormatToken('Hmm', 0, 0, function () {
- return '' + this.hours() + zeroFill(this.minutes(), 2);
- });
-
- addFormatToken('Hmmss', 0, 0, function () {
- return (
- '' +
- this.hours() +
- zeroFill(this.minutes(), 2) +
- zeroFill(this.seconds(), 2)
- );
- });
-
- function meridiem(token, lowercase) {
- addFormatToken(token, 0, 0, function () {
- return this.localeData().meridiem(
- this.hours(),
- this.minutes(),
- lowercase
- );
- });
- }
-
- meridiem('a', true);
- meridiem('A', false);
-
- // ALIASES
-
- addUnitAlias('hour', 'h');
-
- // PRIORITY
- addUnitPriority('hour', 13);
-
- // PARSING
-
- function matchMeridiem(isStrict, locale) {
- return locale._meridiemParse;
- }
-
- addRegexToken('a', matchMeridiem);
- addRegexToken('A', matchMeridiem);
- addRegexToken('H', match1to2);
- addRegexToken('h', match1to2);
- addRegexToken('k', match1to2);
- addRegexToken('HH', match1to2, match2);
- addRegexToken('hh', match1to2, match2);
- addRegexToken('kk', match1to2, match2);
-
- addRegexToken('hmm', match3to4);
- addRegexToken('hmmss', match5to6);
- addRegexToken('Hmm', match3to4);
- addRegexToken('Hmmss', match5to6);
-
- addParseToken(['H', 'HH'], HOUR);
- addParseToken(['k', 'kk'], function (input, array, config) {
- var kInput = toInt(input);
- array[HOUR] = kInput === 24 ? 0 : kInput;
- });
- addParseToken(['a', 'A'], function (input, array, config) {
- config._isPm = config._locale.isPM(input);
- config._meridiem = input;
- });
- addParseToken(['h', 'hh'], function (input, array, config) {
- array[HOUR] = toInt(input);
- getParsingFlags(config).bigHour = true;
- });
- addParseToken('hmm', function (input, array, config) {
- var pos = input.length - 2;
- array[HOUR] = toInt(input.substr(0, pos));
- array[MINUTE] = toInt(input.substr(pos));
- getParsingFlags(config).bigHour = true;
- });
- addParseToken('hmmss', function (input, array, config) {
- var pos1 = input.length - 4,
- pos2 = input.length - 2;
- array[HOUR] = toInt(input.substr(0, pos1));
- array[MINUTE] = toInt(input.substr(pos1, 2));
- array[SECOND] = toInt(input.substr(pos2));
- getParsingFlags(config).bigHour = true;
- });
- addParseToken('Hmm', function (input, array, config) {
- var pos = input.length - 2;
- array[HOUR] = toInt(input.substr(0, pos));
- array[MINUTE] = toInt(input.substr(pos));
- });
- addParseToken('Hmmss', function (input, array, config) {
- var pos1 = input.length - 4,
- pos2 = input.length - 2;
- array[HOUR] = toInt(input.substr(0, pos1));
- array[MINUTE] = toInt(input.substr(pos1, 2));
- array[SECOND] = toInt(input.substr(pos2));
- });
-
- // LOCALES
-
- function localeIsPM(input) {
- // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
- // Using charAt should be more compatible.
- return (input + '').toLowerCase().charAt(0) === 'p';
- }
-
- var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
- // Setting the hour should keep the time, because the user explicitly
- // specified which hour they want. So trying to maintain the same hour (in
- // a new timezone) makes sense. Adding/subtracting hours does not follow
- // this rule.
- getSetHour = makeGetSet('Hours', true);
-
- function localeMeridiem(hours, minutes, isLower) {
- if (hours > 11) {
- return isLower ? 'pm' : 'PM';
- } else {
- return isLower ? 'am' : 'AM';
- }
- }
-
- var baseConfig = {
- calendar: defaultCalendar,
- longDateFormat: defaultLongDateFormat,
- invalidDate: defaultInvalidDate,
- ordinal: defaultOrdinal,
- dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
- relativeTime: defaultRelativeTime,
-
- months: defaultLocaleMonths,
- monthsShort: defaultLocaleMonthsShort,
-
- week: defaultLocaleWeek,
-
- weekdays: defaultLocaleWeekdays,
- weekdaysMin: defaultLocaleWeekdaysMin,
- weekdaysShort: defaultLocaleWeekdaysShort,
-
- meridiemParse: defaultLocaleMeridiemParse,
- };
-
- // internal storage for locale config files
- var locales = {},
- localeFamilies = {},
- globalLocale;
-
- function commonPrefix(arr1, arr2) {
- var i,
- minl = Math.min(arr1.length, arr2.length);
- for (i = 0; i < minl; i += 1) {
- if (arr1[i] !== arr2[i]) {
- return i;
- }
- }
- return minl;
- }
-
- function normalizeLocale(key) {
- return key ? key.toLowerCase().replace('_', '-') : key;
- }
-
- // pick the locale from the array
- // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
- // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
- function chooseLocale(names) {
- var i = 0,
- j,
- next,
- locale,
- split;
-
- while (i < names.length) {
- split = normalizeLocale(names[i]).split('-');
- j = split.length;
- next = normalizeLocale(names[i + 1]);
- next = next ? next.split('-') : null;
- while (j > 0) {
- locale = loadLocale(split.slice(0, j).join('-'));
- if (locale) {
- return locale;
- }
- if (
- next &&
- next.length >= j &&
- commonPrefix(split, next) >= j - 1
- ) {
- //the next array item is better than a shallower substring of this one
- break;
- }
- j--;
- }
- i++;
- }
- return globalLocale;
- }
-
- function loadLocale(name) {
- var oldLocale = null,
- aliasedRequire;
- // TODO: Find a better way to register and load all the locales in Node
- if (
- locales[name] === undefined &&
- 'object' !== 'undefined' &&
- module &&
- module.exports
- ) {
- try {
- oldLocale = globalLocale._abbr;
- aliasedRequire = commonjsRequire;
- aliasedRequire('./locale/' + name);
- getSetGlobalLocale(oldLocale);
- } catch (e) {
- // mark as not found to avoid repeating expensive file require call causing high CPU
- // when trying to find en-US, en_US, en-us for every format call
- locales[name] = null; // null means not found
- }
- }
- return locales[name];
- }
-
- // This function will load locale and then set the global locale. If
- // no arguments are passed in, it will simply return the current global
- // locale key.
- function getSetGlobalLocale(key, values) {
- var data;
- if (key) {
- if (isUndefined(values)) {
- data = getLocale(key);
- } else {
- data = defineLocale(key, values);
- }
-
- if (data) {
- // moment.duration._locale = moment._locale = data;
- globalLocale = data;
- } else {
- if (typeof console !== 'undefined' && console.warn) {
- //warn user if arguments are passed but the locale could not be set
- console.warn(
- 'Locale ' + key + ' not found. Did you forget to load it?'
- );
- }
- }
- }
-
- return globalLocale._abbr;
- }
-
- function defineLocale(name, config) {
- if (config !== null) {
- var locale,
- parentConfig = baseConfig;
- config.abbr = name;
- if (locales[name] != null) {
- deprecateSimple(
- 'defineLocaleOverride',
- 'use moment.updateLocale(localeName, config) to change ' +
- 'an existing locale. moment.defineLocale(localeName, ' +
- 'config) should only be used for creating a new locale ' +
- 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
- );
- parentConfig = locales[name]._config;
- } else if (config.parentLocale != null) {
- if (locales[config.parentLocale] != null) {
- parentConfig = locales[config.parentLocale]._config;
- } else {
- locale = loadLocale(config.parentLocale);
- if (locale != null) {
- parentConfig = locale._config;
- } else {
- if (!localeFamilies[config.parentLocale]) {
- localeFamilies[config.parentLocale] = [];
- }
- localeFamilies[config.parentLocale].push({
- name: name,
- config: config,
- });
- return null;
- }
- }
- }
- locales[name] = new Locale(mergeConfigs(parentConfig, config));
-
- if (localeFamilies[name]) {
- localeFamilies[name].forEach(function (x) {
- defineLocale(x.name, x.config);
- });
- }
-
- // backwards compat for now: also set the locale
- // make sure we set the locale AFTER all child locales have been
- // created, so we won't end up with the child locale set.
- getSetGlobalLocale(name);
-
- return locales[name];
- } else {
- // useful for testing
- delete locales[name];
- return null;
- }
- }
-
- function updateLocale(name, config) {
- if (config != null) {
- var locale,
- tmpLocale,
- parentConfig = baseConfig;
-
- if (locales[name] != null && locales[name].parentLocale != null) {
- // Update existing child locale in-place to avoid memory-leaks
- locales[name].set(mergeConfigs(locales[name]._config, config));
- } else {
- // MERGE
- tmpLocale = loadLocale(name);
- if (tmpLocale != null) {
- parentConfig = tmpLocale._config;
- }
- config = mergeConfigs(parentConfig, config);
- if (tmpLocale == null) {
- // updateLocale is called for creating a new locale
- // Set abbr so it will have a name (getters return
- // undefined otherwise).
- config.abbr = name;
- }
- locale = new Locale(config);
- locale.parentLocale = locales[name];
- locales[name] = locale;
- }
-
- // backwards compat for now: also set the locale
- getSetGlobalLocale(name);
- } else {
- // pass null for config to unupdate, useful for tests
- if (locales[name] != null) {
- if (locales[name].parentLocale != null) {
- locales[name] = locales[name].parentLocale;
- if (name === getSetGlobalLocale()) {
- getSetGlobalLocale(name);
- }
- } else if (locales[name] != null) {
- delete locales[name];
- }
- }
- }
- return locales[name];
- }
-
- // returns locale data
- function getLocale(key) {
- var locale;
-
- if (key && key._locale && key._locale._abbr) {
- key = key._locale._abbr;
- }
-
- if (!key) {
- return globalLocale;
- }
-
- if (!isArray(key)) {
- //short-circuit everything else
- locale = loadLocale(key);
- if (locale) {
- return locale;
- }
- key = [key];
- }
-
- return chooseLocale(key);
- }
-
- function listLocales() {
- return keys(locales);
- }
-
- function checkOverflow(m) {
- var overflow,
- a = m._a;
-
- if (a && getParsingFlags(m).overflow === -2) {
- overflow =
- a[MONTH] < 0 || a[MONTH] > 11
- ? MONTH
- : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
- ? DATE
- : a[HOUR] < 0 ||
- a[HOUR] > 24 ||
- (a[HOUR] === 24 &&
- (a[MINUTE] !== 0 ||
- a[SECOND] !== 0 ||
- a[MILLISECOND] !== 0))
- ? HOUR
- : a[MINUTE] < 0 || a[MINUTE] > 59
- ? MINUTE
- : a[SECOND] < 0 || a[SECOND] > 59
- ? SECOND
- : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
- ? MILLISECOND
- : -1;
-
- if (
- getParsingFlags(m)._overflowDayOfYear &&
- (overflow < YEAR || overflow > DATE)
- ) {
- overflow = DATE;
- }
- if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
- overflow = WEEK;
- }
- if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
- overflow = WEEKDAY;
- }
-
- getParsingFlags(m).overflow = overflow;
- }
-
- return m;
- }
-
- // iso 8601 regex
- // 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)
- 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)?)?$/,
- 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)?)?$/,
- tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
- isoDates = [
- ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
- ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
- ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
- ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
- ['YYYY-DDD', /\d{4}-\d{3}/],
- ['YYYY-MM', /\d{4}-\d\d/, false],
- ['YYYYYYMMDD', /[+-]\d{10}/],
- ['YYYYMMDD', /\d{8}/],
- ['GGGG[W]WWE', /\d{4}W\d{3}/],
- ['GGGG[W]WW', /\d{4}W\d{2}/, false],
- ['YYYYDDD', /\d{7}/],
- ['YYYYMM', /\d{6}/, false],
- ['YYYY', /\d{4}/, false],
- ],
- // iso time formats and regexes
- isoTimes = [
- ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
- ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
- ['HH:mm:ss', /\d\d:\d\d:\d\d/],
- ['HH:mm', /\d\d:\d\d/],
- ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
- ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
- ['HHmmss', /\d\d\d\d\d\d/],
- ['HHmm', /\d\d\d\d/],
- ['HH', /\d\d/],
- ],
- aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
- // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
- 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}))$/,
- obsOffsets = {
- UT: 0,
- GMT: 0,
- EDT: -4 * 60,
- EST: -5 * 60,
- CDT: -5 * 60,
- CST: -6 * 60,
- MDT: -6 * 60,
- MST: -7 * 60,
- PDT: -7 * 60,
- PST: -8 * 60,
- };
-
- // date from iso format
- function configFromISO(config) {
- var i,
- l,
- string = config._i,
- match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
- allowTime,
- dateFormat,
- timeFormat,
- tzFormat;
-
- if (match) {
- getParsingFlags(config).iso = true;
-
- for (i = 0, l = isoDates.length; i < l; i++) {
- if (isoDates[i][1].exec(match[1])) {
- dateFormat = isoDates[i][0];
- allowTime = isoDates[i][2] !== false;
- break;
- }
- }
- if (dateFormat == null) {
- config._isValid = false;
- return;
- }
- if (match[3]) {
- for (i = 0, l = isoTimes.length; i < l; i++) {
- if (isoTimes[i][1].exec(match[3])) {
- // match[2] should be 'T' or space
- timeFormat = (match[2] || ' ') + isoTimes[i][0];
- break;
- }
- }
- if (timeFormat == null) {
- config._isValid = false;
- return;
- }
- }
- if (!allowTime && timeFormat != null) {
- config._isValid = false;
- return;
- }
- if (match[4]) {
- if (tzRegex.exec(match[4])) {
- tzFormat = 'Z';
- } else {
- config._isValid = false;
- return;
- }
- }
- config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
- configFromStringAndFormat(config);
- } else {
- config._isValid = false;
- }
- }
-
- function extractFromRFC2822Strings(
- yearStr,
- monthStr,
- dayStr,
- hourStr,
- minuteStr,
- secondStr
- ) {
- var result = [
- untruncateYear(yearStr),
- defaultLocaleMonthsShort.indexOf(monthStr),
- parseInt(dayStr, 10),
- parseInt(hourStr, 10),
- parseInt(minuteStr, 10),
- ];
-
- if (secondStr) {
- result.push(parseInt(secondStr, 10));
- }
-
- return result;
- }
-
- function untruncateYear(yearStr) {
- var year = parseInt(yearStr, 10);
- if (year <= 49) {
- return 2000 + year;
- } else if (year <= 999) {
- return 1900 + year;
- }
- return year;
- }
-
- function preprocessRFC2822(s) {
- // Remove comments and folding whitespace and replace multiple-spaces with a single space
- return s
- .replace(/\([^)]*\)|[\n\t]/g, ' ')
- .replace(/(\s\s+)/g, ' ')
- .replace(/^\s\s*/, '')
- .replace(/\s\s*$/, '');
- }
-
- function checkWeekday(weekdayStr, parsedInput, config) {
- if (weekdayStr) {
- // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
- var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
- weekdayActual = new Date(
- parsedInput[0],
- parsedInput[1],
- parsedInput[2]
- ).getDay();
- if (weekdayProvided !== weekdayActual) {
- getParsingFlags(config).weekdayMismatch = true;
- config._isValid = false;
- return false;
- }
- }
- return true;
- }
-
- function calculateOffset(obsOffset, militaryOffset, numOffset) {
- if (obsOffset) {
- return obsOffsets[obsOffset];
- } else if (militaryOffset) {
- // the only allowed military tz is Z
- return 0;
- } else {
- var hm = parseInt(numOffset, 10),
- m = hm % 100,
- h = (hm - m) / 100;
- return h * 60 + m;
- }
- }
-
- // date and time from ref 2822 format
- function configFromRFC2822(config) {
- var match = rfc2822.exec(preprocessRFC2822(config._i)),
- parsedArray;
- if (match) {
- parsedArray = extractFromRFC2822Strings(
- match[4],
- match[3],
- match[2],
- match[5],
- match[6],
- match[7]
- );
- if (!checkWeekday(match[1], parsedArray, config)) {
- return;
- }
-
- config._a = parsedArray;
- config._tzm = calculateOffset(match[8], match[9], match[10]);
-
- config._d = createUTCDate.apply(null, config._a);
- config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
-
- getParsingFlags(config).rfc2822 = true;
- } else {
- config._isValid = false;
- }
- }
-
- // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
- function configFromString(config) {
- var matched = aspNetJsonRegex.exec(config._i);
- if (matched !== null) {
- config._d = new Date(+matched[1]);
- return;
- }
-
- configFromISO(config);
- if (config._isValid === false) {
- delete config._isValid;
- } else {
- return;
- }
-
- configFromRFC2822(config);
- if (config._isValid === false) {
- delete config._isValid;
- } else {
- return;
- }
-
- if (config._strict) {
- config._isValid = false;
- } else {
- // Final attempt, use Input Fallback
- hooks.createFromInputFallback(config);
- }
- }
-
- hooks.createFromInputFallback = deprecate(
- 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
- 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
- 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
- function (config) {
- config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
- }
- );
-
- // Pick the first defined of two or three arguments.
- function defaults(a, b, c) {
- if (a != null) {
- return a;
- }
- if (b != null) {
- return b;
- }
- return c;
- }
-
- function currentDateArray(config) {
- // hooks is actually the exported moment object
- var nowValue = new Date(hooks.now());
- if (config._useUTC) {
- return [
- nowValue.getUTCFullYear(),
- nowValue.getUTCMonth(),
- nowValue.getUTCDate(),
- ];
- }
- return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
- }
-
- // convert an array to a date.
- // the array should mirror the parameters below
- // note: all values past the year are optional and will default to the lowest possible value.
- // [year, month, day , hour, minute, second, millisecond]
- function configFromArray(config) {
- var i,
- date,
- input = [],
- currentDate,
- expectedWeekday,
- yearToUse;
-
- if (config._d) {
- return;
- }
-
- currentDate = currentDateArray(config);
-
- //compute day of the year from weeks and weekdays
- if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
- dayOfYearFromWeekInfo(config);
- }
-
- //if the day of the year is set, figure out what it is
- if (config._dayOfYear != null) {
- yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
-
- if (
- config._dayOfYear > daysInYear(yearToUse) ||
- config._dayOfYear === 0
- ) {
- getParsingFlags(config)._overflowDayOfYear = true;
- }
-
- date = createUTCDate(yearToUse, 0, config._dayOfYear);
- config._a[MONTH] = date.getUTCMonth();
- config._a[DATE] = date.getUTCDate();
- }
-
- // Default to current date.
- // * if no year, month, day of month are given, default to today
- // * if day of month is given, default month and year
- // * if month is given, default only year
- // * if year is given, don't default anything
- for (i = 0; i < 3 && config._a[i] == null; ++i) {
- config._a[i] = input[i] = currentDate[i];
- }
-
- // Zero out whatever was not defaulted, including time
- for (; i < 7; i++) {
- config._a[i] = input[i] =
- config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
- }
-
- // Check for 24:00:00.000
- if (
- config._a[HOUR] === 24 &&
- config._a[MINUTE] === 0 &&
- config._a[SECOND] === 0 &&
- config._a[MILLISECOND] === 0
- ) {
- config._nextDay = true;
- config._a[HOUR] = 0;
- }
-
- config._d = (config._useUTC ? createUTCDate : createDate).apply(
- null,
- input
- );
- expectedWeekday = config._useUTC
- ? config._d.getUTCDay()
- : config._d.getDay();
-
- // Apply timezone offset from input. The actual utcOffset can be changed
- // with parseZone.
- if (config._tzm != null) {
- config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
- }
-
- if (config._nextDay) {
- config._a[HOUR] = 24;
- }
-
- // check for mismatching day of week
- if (
- config._w &&
- typeof config._w.d !== 'undefined' &&
- config._w.d !== expectedWeekday
- ) {
- getParsingFlags(config).weekdayMismatch = true;
- }
- }
-
- function dayOfYearFromWeekInfo(config) {
- var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
-
- w = config._w;
- if (w.GG != null || w.W != null || w.E != null) {
- dow = 1;
- doy = 4;
-
- // TODO: We need to take the current isoWeekYear, but that depends on
- // how we interpret now (local, utc, fixed offset). So create
- // a now version of current config (take local/utc/offset flags, and
- // create now).
- weekYear = defaults(
- w.GG,
- config._a[YEAR],
- weekOfYear(createLocal(), 1, 4).year
- );
- week = defaults(w.W, 1);
- weekday = defaults(w.E, 1);
- if (weekday < 1 || weekday > 7) {
- weekdayOverflow = true;
- }
- } else {
- dow = config._locale._week.dow;
- doy = config._locale._week.doy;
-
- curWeek = weekOfYear(createLocal(), dow, doy);
-
- weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
-
- // Default to current week.
- week = defaults(w.w, curWeek.week);
-
- if (w.d != null) {
- // weekday -- low day numbers are considered next week
- weekday = w.d;
- if (weekday < 0 || weekday > 6) {
- weekdayOverflow = true;
- }
- } else if (w.e != null) {
- // local weekday -- counting starts from beginning of week
- weekday = w.e + dow;
- if (w.e < 0 || w.e > 6) {
- weekdayOverflow = true;
- }
- } else {
- // default to beginning of week
- weekday = dow;
- }
- }
- if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
- getParsingFlags(config)._overflowWeeks = true;
- } else if (weekdayOverflow != null) {
- getParsingFlags(config)._overflowWeekday = true;
- } else {
- temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
- config._a[YEAR] = temp.year;
- config._dayOfYear = temp.dayOfYear;
- }
- }
-
- // constant that refers to the ISO standard
- hooks.ISO_8601 = function () {};
-
- // constant that refers to the RFC 2822 form
- hooks.RFC_2822 = function () {};
-
- // date from string and format string
- function configFromStringAndFormat(config) {
- // TODO: Move this to another part of the creation flow to prevent circular deps
- if (config._f === hooks.ISO_8601) {
- configFromISO(config);
- return;
- }
- if (config._f === hooks.RFC_2822) {
- configFromRFC2822(config);
- return;
- }
- config._a = [];
- getParsingFlags(config).empty = true;
-
- // This array is used to make a Date, either with `new Date` or `Date.UTC`
- var string = '' + config._i,
- i,
- parsedInput,
- tokens,
- token,
- skipped,
- stringLength = string.length,
- totalParsedInputLength = 0,
- era;
-
- tokens =
- expandFormat(config._f, config._locale).match(formattingTokens) || [];
-
- for (i = 0; i < tokens.length; i++) {
- token = tokens[i];
- parsedInput = (string.match(getParseRegexForToken(token, config)) ||
- [])[0];
- if (parsedInput) {
- skipped = string.substr(0, string.indexOf(parsedInput));
- if (skipped.length > 0) {
- getParsingFlags(config).unusedInput.push(skipped);
- }
- string = string.slice(
- string.indexOf(parsedInput) + parsedInput.length
- );
- totalParsedInputLength += parsedInput.length;
- }
- // don't parse if it's not a known token
- if (formatTokenFunctions[token]) {
- if (parsedInput) {
- getParsingFlags(config).empty = false;
- } else {
- getParsingFlags(config).unusedTokens.push(token);
- }
- addTimeToArrayFromToken(token, parsedInput, config);
- } else if (config._strict && !parsedInput) {
- getParsingFlags(config).unusedTokens.push(token);
- }
- }
-
- // add remaining unparsed input length to the string
- getParsingFlags(config).charsLeftOver =
- stringLength - totalParsedInputLength;
- if (string.length > 0) {
- getParsingFlags(config).unusedInput.push(string);
- }
-
- // clear _12h flag if hour is <= 12
- if (
- config._a[HOUR] <= 12 &&
- getParsingFlags(config).bigHour === true &&
- config._a[HOUR] > 0
- ) {
- getParsingFlags(config).bigHour = undefined;
- }
-
- getParsingFlags(config).parsedDateParts = config._a.slice(0);
- getParsingFlags(config).meridiem = config._meridiem;
- // handle meridiem
- config._a[HOUR] = meridiemFixWrap(
- config._locale,
- config._a[HOUR],
- config._meridiem
- );
-
- // handle era
- era = getParsingFlags(config).era;
- if (era !== null) {
- config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
- }
-
- configFromArray(config);
- checkOverflow(config);
- }
-
- function meridiemFixWrap(locale, hour, meridiem) {
- var isPm;
-
- if (meridiem == null) {
- // nothing to do
- return hour;
- }
- if (locale.meridiemHour != null) {
- return locale.meridiemHour(hour, meridiem);
- } else if (locale.isPM != null) {
- // Fallback
- isPm = locale.isPM(meridiem);
- if (isPm && hour < 12) {
- hour += 12;
- }
- if (!isPm && hour === 12) {
- hour = 0;
- }
- return hour;
- } else {
- // this is not supposed to happen
- return hour;
- }
- }
-
- // date from string and array of format strings
- function configFromStringAndArray(config) {
- var tempConfig,
- bestMoment,
- scoreToBeat,
- i,
- currentScore,
- validFormatFound,
- bestFormatIsValid = false;
-
- if (config._f.length === 0) {
- getParsingFlags(config).invalidFormat = true;
- config._d = new Date(NaN);
- return;
- }
-
- for (i = 0; i < config._f.length; i++) {
- currentScore = 0;
- validFormatFound = false;
- tempConfig = copyConfig({}, config);
- if (config._useUTC != null) {
- tempConfig._useUTC = config._useUTC;
- }
- tempConfig._f = config._f[i];
- configFromStringAndFormat(tempConfig);
-
- if (isValid(tempConfig)) {
- validFormatFound = true;
- }
-
- // if there is any input that was not parsed add a penalty for that format
- currentScore += getParsingFlags(tempConfig).charsLeftOver;
-
- //or tokens
- currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
-
- getParsingFlags(tempConfig).score = currentScore;
-
- if (!bestFormatIsValid) {
- if (
- scoreToBeat == null ||
- currentScore < scoreToBeat ||
- validFormatFound
- ) {
- scoreToBeat = currentScore;
- bestMoment = tempConfig;
- if (validFormatFound) {
- bestFormatIsValid = true;
- }
- }
- } else {
- if (currentScore < scoreToBeat) {
- scoreToBeat = currentScore;
- bestMoment = tempConfig;
- }
- }
- }
-
- extend(config, bestMoment || tempConfig);
- }
-
- function configFromObject(config) {
- if (config._d) {
- return;
- }
-
- var i = normalizeObjectUnits(config._i),
- dayOrDate = i.day === undefined ? i.date : i.day;
- config._a = map(
- [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
- function (obj) {
- return obj && parseInt(obj, 10);
- }
- );
-
- configFromArray(config);
- }
-
- function createFromConfig(config) {
- var res = new Moment(checkOverflow(prepareConfig(config)));
- if (res._nextDay) {
- // Adding is smart enough around DST
- res.add(1, 'd');
- res._nextDay = undefined;
- }
-
- return res;
- }
-
- function prepareConfig(config) {
- var input = config._i,
- format = config._f;
-
- config._locale = config._locale || getLocale(config._l);
-
- if (input === null || (format === undefined && input === '')) {
- return createInvalid({ nullInput: true });
- }
-
- if (typeof input === 'string') {
- config._i = input = config._locale.preparse(input);
- }
-
- if (isMoment(input)) {
- return new Moment(checkOverflow(input));
- } else if (isDate(input)) {
- config._d = input;
- } else if (isArray(format)) {
- configFromStringAndArray(config);
- } else if (format) {
- configFromStringAndFormat(config);
- } else {
- configFromInput(config);
- }
-
- if (!isValid(config)) {
- config._d = null;
- }
-
- return config;
- }
-
- function configFromInput(config) {
- var input = config._i;
- if (isUndefined(input)) {
- config._d = new Date(hooks.now());
- } else if (isDate(input)) {
- config._d = new Date(input.valueOf());
- } else if (typeof input === 'string') {
- configFromString(config);
- } else if (isArray(input)) {
- config._a = map(input.slice(0), function (obj) {
- return parseInt(obj, 10);
- });
- configFromArray(config);
- } else if (isObject(input)) {
- configFromObject(config);
- } else if (isNumber(input)) {
- // from milliseconds
- config._d = new Date(input);
- } else {
- hooks.createFromInputFallback(config);
- }
- }
-
- function createLocalOrUTC(input, format, locale, strict, isUTC) {
- var c = {};
-
- if (format === true || format === false) {
- strict = format;
- format = undefined;
- }
-
- if (locale === true || locale === false) {
- strict = locale;
- locale = undefined;
- }
-
- if (
- (isObject(input) && isObjectEmpty(input)) ||
- (isArray(input) && input.length === 0)
- ) {
- input = undefined;
- }
- // object construction must be done this way.
- // https://github.com/moment/moment/issues/1423
- c._isAMomentObject = true;
- c._useUTC = c._isUTC = isUTC;
- c._l = locale;
- c._i = input;
- c._f = format;
- c._strict = strict;
-
- return createFromConfig(c);
- }
-
- function createLocal(input, format, locale, strict) {
- return createLocalOrUTC(input, format, locale, strict, false);
- }
-
- var prototypeMin = deprecate(
- 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
- function () {
- var other = createLocal.apply(null, arguments);
- if (this.isValid() && other.isValid()) {
- return other < this ? this : other;
- } else {
- return createInvalid();
- }
- }
- ),
- prototypeMax = deprecate(
- 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
- function () {
- var other = createLocal.apply(null, arguments);
- if (this.isValid() && other.isValid()) {
- return other > this ? this : other;
- } else {
- return createInvalid();
- }
- }
- );
-
- // Pick a moment m from moments so that m[fn](other) is true for all
- // other. This relies on the function fn to be transitive.
- //
- // moments should either be an array of moment objects or an array, whose
- // first element is an array of moment objects.
- function pickBy(fn, moments) {
- var res, i;
- if (moments.length === 1 && isArray(moments[0])) {
- moments = moments[0];
- }
- if (!moments.length) {
- return createLocal();
- }
- res = moments[0];
- for (i = 1; i < moments.length; ++i) {
- if (!moments[i].isValid() || moments[i][fn](res)) {
- res = moments[i];
- }
- }
- return res;
- }
-
- // TODO: Use [].sort instead?
- function min() {
- var args = [].slice.call(arguments, 0);
-
- return pickBy('isBefore', args);
- }
-
- function max() {
- var args = [].slice.call(arguments, 0);
-
- return pickBy('isAfter', args);
- }
-
- var now = function () {
- return Date.now ? Date.now() : +new Date();
- };
-
- var ordering = [
- 'year',
- 'quarter',
- 'month',
- 'week',
- 'day',
- 'hour',
- 'minute',
- 'second',
- 'millisecond',
- ];
-
- function isDurationValid(m) {
- var key,
- unitHasDecimal = false,
- i;
- for (key in m) {
- if (
- hasOwnProp(m, key) &&
- !(
- indexOf.call(ordering, key) !== -1 &&
- (m[key] == null || !isNaN(m[key]))
- )
- ) {
- return false;
- }
- }
-
- for (i = 0; i < ordering.length; ++i) {
- if (m[ordering[i]]) {
- if (unitHasDecimal) {
- return false; // only allow non-integers for smallest unit
- }
- if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
- unitHasDecimal = true;
- }
- }
- }
-
- return true;
- }
-
- function isValid$1() {
- return this._isValid;
- }
-
- function createInvalid$1() {
- return createDuration(NaN);
- }
-
- function Duration(duration) {
- var normalizedInput = normalizeObjectUnits(duration),
- years = normalizedInput.year || 0,
- quarters = normalizedInput.quarter || 0,
- months = normalizedInput.month || 0,
- weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
- days = normalizedInput.day || 0,
- hours = normalizedInput.hour || 0,
- minutes = normalizedInput.minute || 0,
- seconds = normalizedInput.second || 0,
- milliseconds = normalizedInput.millisecond || 0;
-
- this._isValid = isDurationValid(normalizedInput);
-
- // representation for dateAddRemove
- this._milliseconds =
- +milliseconds +
- seconds * 1e3 + // 1000
- minutes * 6e4 + // 1000 * 60
- hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
- // Because of dateAddRemove treats 24 hours as different from a
- // day when working around DST, we need to store them separately
- this._days = +days + weeks * 7;
- // It is impossible to translate months into days without knowing
- // which months you are are talking about, so we have to store
- // it separately.
- this._months = +months + quarters * 3 + years * 12;
-
- this._data = {};
-
- this._locale = getLocale();
-
- this._bubble();
- }
-
- function isDuration(obj) {
- return obj instanceof Duration;
- }
-
- function absRound(number) {
- if (number < 0) {
- return Math.round(-1 * number) * -1;
- } else {
- return Math.round(number);
- }
- }
-
- // compare two arrays, return the number of differences
- function compareArrays(array1, array2, dontConvert) {
- var len = Math.min(array1.length, array2.length),
- lengthDiff = Math.abs(array1.length - array2.length),
- diffs = 0,
- i;
- for (i = 0; i < len; i++) {
- if (
- (dontConvert && array1[i] !== array2[i]) ||
- (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
- ) {
- diffs++;
- }
- }
- return diffs + lengthDiff;
- }
-
- // FORMATTING
-
- function offset(token, separator) {
- addFormatToken(token, 0, 0, function () {
- var offset = this.utcOffset(),
- sign = '+';
- if (offset < 0) {
- offset = -offset;
- sign = '-';
- }
- return (
- sign +
- zeroFill(~~(offset / 60), 2) +
- separator +
- zeroFill(~~offset % 60, 2)
- );
- });
- }
-
- offset('Z', ':');
- offset('ZZ', '');
-
- // PARSING
-
- addRegexToken('Z', matchShortOffset);
- addRegexToken('ZZ', matchShortOffset);
- addParseToken(['Z', 'ZZ'], function (input, array, config) {
- config._useUTC = true;
- config._tzm = offsetFromString(matchShortOffset, input);
- });
-
- // HELPERS
-
- // timezone chunker
- // '+10:00' > ['10', '00']
- // '-1530' > ['-15', '30']
- var chunkOffset = /([\+\-]|\d\d)/gi;
-
- function offsetFromString(matcher, string) {
- var matches = (string || '').match(matcher),
- chunk,
- parts,
- minutes;
-
- if (matches === null) {
- return null;
- }
-
- chunk = matches[matches.length - 1] || [];
- parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
- minutes = +(parts[1] * 60) + toInt(parts[2]);
-
- return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
- }
-
- // Return a moment from input, that is local/utc/zone equivalent to model.
- function cloneWithOffset(input, model) {
- var res, diff;
- if (model._isUTC) {
- res = model.clone();
- diff =
- (isMoment(input) || isDate(input)
- ? input.valueOf()
- : createLocal(input).valueOf()) - res.valueOf();
- // Use low-level api, because this fn is low-level api.
- res._d.setTime(res._d.valueOf() + diff);
- hooks.updateOffset(res, false);
- return res;
- } else {
- return createLocal(input).local();
- }
- }
-
- function getDateOffset(m) {
- // On Firefox.24 Date#getTimezoneOffset returns a floating point.
- // https://github.com/moment/moment/pull/1871
- return -Math.round(m._d.getTimezoneOffset());
- }
-
- // HOOKS
-
- // This function will be called whenever a moment is mutated.
- // It is intended to keep the offset in sync with the timezone.
- hooks.updateOffset = function () {};
-
- // MOMENTS
-
- // keepLocalTime = true means only change the timezone, without
- // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
- // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
- // +0200, so we adjust the time as needed, to be valid.
- //
- // Keeping the time actually adds/subtracts (one hour)
- // from the actual represented time. That is why we call updateOffset
- // a second time. In case it wants us to change the offset again
- // _changeInProgress == true case, then we have to adjust, because
- // there is no such time in the given timezone.
- function getSetOffset(input, keepLocalTime, keepMinutes) {
- var offset = this._offset || 0,
- localAdjust;
- if (!this.isValid()) {
- return input != null ? this : NaN;
- }
- if (input != null) {
- if (typeof input === 'string') {
- input = offsetFromString(matchShortOffset, input);
- if (input === null) {
- return this;
- }
- } else if (Math.abs(input) < 16 && !keepMinutes) {
- input = input * 60;
- }
- if (!this._isUTC && keepLocalTime) {
- localAdjust = getDateOffset(this);
- }
- this._offset = input;
- this._isUTC = true;
- if (localAdjust != null) {
- this.add(localAdjust, 'm');
- }
- if (offset !== input) {
- if (!keepLocalTime || this._changeInProgress) {
- addSubtract(
- this,
- createDuration(input - offset, 'm'),
- 1,
- false
- );
- } else if (!this._changeInProgress) {
- this._changeInProgress = true;
- hooks.updateOffset(this, true);
- this._changeInProgress = null;
- }
- }
- return this;
- } else {
- return this._isUTC ? offset : getDateOffset(this);
- }
- }
-
- function getSetZone(input, keepLocalTime) {
- if (input != null) {
- if (typeof input !== 'string') {
- input = -input;
- }
-
- this.utcOffset(input, keepLocalTime);
-
- return this;
- } else {
- return -this.utcOffset();
- }
- }
-
- function setOffsetToUTC(keepLocalTime) {
- return this.utcOffset(0, keepLocalTime);
- }
-
- function setOffsetToLocal(keepLocalTime) {
- if (this._isUTC) {
- this.utcOffset(0, keepLocalTime);
- this._isUTC = false;
-
- if (keepLocalTime) {
- this.subtract(getDateOffset(this), 'm');
- }
- }
- return this;
- }
-
- function setOffsetToParsedOffset() {
- if (this._tzm != null) {
- this.utcOffset(this._tzm, false, true);
- } else if (typeof this._i === 'string') {
- var tZone = offsetFromString(matchOffset, this._i);
- if (tZone != null) {
- this.utcOffset(tZone);
- } else {
- this.utcOffset(0, true);
- }
- }
- return this;
- }
-
- function hasAlignedHourOffset(input) {
- if (!this.isValid()) {
- return false;
- }
- input = input ? createLocal(input).utcOffset() : 0;
-
- return (this.utcOffset() - input) % 60 === 0;
- }
-
- function isDaylightSavingTime() {
- return (
- this.utcOffset() > this.clone().month(0).utcOffset() ||
- this.utcOffset() > this.clone().month(5).utcOffset()
- );
- }
-
- function isDaylightSavingTimeShifted() {
- if (!isUndefined(this._isDSTShifted)) {
- return this._isDSTShifted;
- }
-
- var c = {},
- other;
-
- copyConfig(c, this);
- c = prepareConfig(c);
-
- if (c._a) {
- other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
- this._isDSTShifted =
- this.isValid() && compareArrays(c._a, other.toArray()) > 0;
- } else {
- this._isDSTShifted = false;
- }
-
- return this._isDSTShifted;
- }
-
- function isLocal() {
- return this.isValid() ? !this._isUTC : false;
- }
-
- function isUtcOffset() {
- return this.isValid() ? this._isUTC : false;
- }
-
- function isUtc() {
- return this.isValid() ? this._isUTC && this._offset === 0 : false;
- }
-
- // ASP.NET json date format regex
- var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
- // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
- // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
- // and further modified to allow for strings containing both week and day
- isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
-
- function createDuration(input, key) {
- var duration = input,
- // matching against regexp is expensive, do it on demand
- match = null,
- sign,
- ret,
- diffRes;
-
- if (isDuration(input)) {
- duration = {
- ms: input._milliseconds,
- d: input._days,
- M: input._months,
- };
- } else if (isNumber(input) || !isNaN(+input)) {
- duration = {};
- if (key) {
- duration[key] = +input;
- } else {
- duration.milliseconds = +input;
- }
- } else if ((match = aspNetRegex.exec(input))) {
- sign = match[1] === '-' ? -1 : 1;
- duration = {
- y: 0,
- d: toInt(match[DATE]) * sign,
- h: toInt(match[HOUR]) * sign,
- m: toInt(match[MINUTE]) * sign,
- s: toInt(match[SECOND]) * sign,
- ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
- };
- } else if ((match = isoRegex.exec(input))) {
- sign = match[1] === '-' ? -1 : 1;
- duration = {
- y: parseIso(match[2], sign),
- M: parseIso(match[3], sign),
- w: parseIso(match[4], sign),
- d: parseIso(match[5], sign),
- h: parseIso(match[6], sign),
- m: parseIso(match[7], sign),
- s: parseIso(match[8], sign),
- };
- } else if (duration == null) {
- // checks for null or undefined
- duration = {};
- } else if (
- typeof duration === 'object' &&
- ('from' in duration || 'to' in duration)
- ) {
- diffRes = momentsDifference(
- createLocal(duration.from),
- createLocal(duration.to)
- );
-
- duration = {};
- duration.ms = diffRes.milliseconds;
- duration.M = diffRes.months;
- }
-
- ret = new Duration(duration);
-
- if (isDuration(input) && hasOwnProp(input, '_locale')) {
- ret._locale = input._locale;
- }
-
- if (isDuration(input) && hasOwnProp(input, '_isValid')) {
- ret._isValid = input._isValid;
- }
-
- return ret;
- }
-
- createDuration.fn = Duration.prototype;
- createDuration.invalid = createInvalid$1;
-
- function parseIso(inp, sign) {
- // We'd normally use ~~inp for this, but unfortunately it also
- // converts floats to ints.
- // inp may be undefined, so careful calling replace on it.
- var res = inp && parseFloat(inp.replace(',', '.'));
- // apply sign while we're at it
- return (isNaN(res) ? 0 : res) * sign;
- }
-
- function positiveMomentsDifference(base, other) {
- var res = {};
-
- res.months =
- other.month() - base.month() + (other.year() - base.year()) * 12;
- if (base.clone().add(res.months, 'M').isAfter(other)) {
- --res.months;
- }
-
- res.milliseconds = +other - +base.clone().add(res.months, 'M');
-
- return res;
- }
-
- function momentsDifference(base, other) {
- var res;
- if (!(base.isValid() && other.isValid())) {
- return { milliseconds: 0, months: 0 };
- }
-
- other = cloneWithOffset(other, base);
- if (base.isBefore(other)) {
- res = positiveMomentsDifference(base, other);
- } else {
- res = positiveMomentsDifference(other, base);
- res.milliseconds = -res.milliseconds;
- res.months = -res.months;
- }
-
- return res;
- }
-
- // TODO: remove 'name' arg after deprecation is removed
- function createAdder(direction, name) {
- return function (val, period) {
- var dur, tmp;
- //invert the arguments, but complain about it
- if (period !== null && !isNaN(+period)) {
- deprecateSimple(
- name,
- 'moment().' +
- name +
- '(period, number) is deprecated. Please use moment().' +
- name +
- '(number, period). ' +
- 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
- );
- tmp = val;
- val = period;
- period = tmp;
- }
-
- dur = createDuration(val, period);
- addSubtract(this, dur, direction);
- return this;
- };
- }
-
- function addSubtract(mom, duration, isAdding, updateOffset) {
- var milliseconds = duration._milliseconds,
- days = absRound(duration._days),
- months = absRound(duration._months);
-
- if (!mom.isValid()) {
- // No op
- return;
- }
-
- updateOffset = updateOffset == null ? true : updateOffset;
-
- if (months) {
- setMonth(mom, get(mom, 'Month') + months * isAdding);
- }
- if (days) {
- set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
- }
- if (milliseconds) {
- mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
- }
- if (updateOffset) {
- hooks.updateOffset(mom, days || months);
- }
- }
-
- var add = createAdder(1, 'add'),
- subtract = createAdder(-1, 'subtract');
-
- function isString(input) {
- return typeof input === 'string' || input instanceof String;
- }
-
- // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
- function isMomentInput(input) {
- return (
- isMoment(input) ||
- isDate(input) ||
- isString(input) ||
- isNumber(input) ||
- isNumberOrStringArray(input) ||
- isMomentInputObject(input) ||
- input === null ||
- input === undefined
- );
- }
-
- function isMomentInputObject(input) {
- var objectTest = isObject(input) && !isObjectEmpty(input),
- propertyTest = false,
- properties = [
- 'years',
- 'year',
- 'y',
- 'months',
- 'month',
- 'M',
- 'days',
- 'day',
- 'd',
- 'dates',
- 'date',
- 'D',
- 'hours',
- 'hour',
- 'h',
- 'minutes',
- 'minute',
- 'm',
- 'seconds',
- 'second',
- 's',
- 'milliseconds',
- 'millisecond',
- 'ms',
- ],
- i,
- property;
-
- for (i = 0; i < properties.length; i += 1) {
- property = properties[i];
- propertyTest = propertyTest || hasOwnProp(input, property);
- }
-
- return objectTest && propertyTest;
- }
-
- function isNumberOrStringArray(input) {
- var arrayTest = isArray(input),
- dataTypeTest = false;
- if (arrayTest) {
- dataTypeTest =
- input.filter(function (item) {
- return !isNumber(item) && isString(input);
- }).length === 0;
- }
- return arrayTest && dataTypeTest;
- }
-
- function isCalendarSpec(input) {
- var objectTest = isObject(input) && !isObjectEmpty(input),
- propertyTest = false,
- properties = [
- 'sameDay',
- 'nextDay',
- 'lastDay',
- 'nextWeek',
- 'lastWeek',
- 'sameElse',
- ],
- i,
- property;
-
- for (i = 0; i < properties.length; i += 1) {
- property = properties[i];
- propertyTest = propertyTest || hasOwnProp(input, property);
- }
-
- return objectTest && propertyTest;
- }
-
- function getCalendarFormat(myMoment, now) {
- var diff = myMoment.diff(now, 'days', true);
- return diff < -6
- ? 'sameElse'
- : diff < -1
- ? 'lastWeek'
- : diff < 0
- ? 'lastDay'
- : diff < 1
- ? 'sameDay'
- : diff < 2
- ? 'nextDay'
- : diff < 7
- ? 'nextWeek'
- : 'sameElse';
- }
-
- function calendar$1(time, formats) {
- // Support for single parameter, formats only overload to the calendar function
- if (arguments.length === 1) {
- if (!arguments[0]) {
- time = undefined;
- formats = undefined;
- } else if (isMomentInput(arguments[0])) {
- time = arguments[0];
- formats = undefined;
- } else if (isCalendarSpec(arguments[0])) {
- formats = arguments[0];
- time = undefined;
- }
- }
- // We want to compare the start of today, vs this.
- // Getting start-of-today depends on whether we're local/utc/offset or not.
- var now = time || createLocal(),
- sod = cloneWithOffset(now, this).startOf('day'),
- format = hooks.calendarFormat(this, sod) || 'sameElse',
- output =
- formats &&
- (isFunction(formats[format])
- ? formats[format].call(this, now)
- : formats[format]);
-
- return this.format(
- output || this.localeData().calendar(format, this, createLocal(now))
- );
- }
-
- function clone() {
- return new Moment(this);
- }
-
- function isAfter(input, units) {
- var localInput = isMoment(input) ? input : createLocal(input);
- if (!(this.isValid() && localInput.isValid())) {
- return false;
- }
- units = normalizeUnits(units) || 'millisecond';
- if (units === 'millisecond') {
- return this.valueOf() > localInput.valueOf();
- } else {
- return localInput.valueOf() < this.clone().startOf(units).valueOf();
- }
- }
-
- function isBefore(input, units) {
- var localInput = isMoment(input) ? input : createLocal(input);
- if (!(this.isValid() && localInput.isValid())) {
- return false;
- }
- units = normalizeUnits(units) || 'millisecond';
- if (units === 'millisecond') {
- return this.valueOf() < localInput.valueOf();
- } else {
- return this.clone().endOf(units).valueOf() < localInput.valueOf();
- }
- }
-
- function isBetween(from, to, units, inclusivity) {
- var localFrom = isMoment(from) ? from : createLocal(from),
- localTo = isMoment(to) ? to : createLocal(to);
- if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
- return false;
- }
- inclusivity = inclusivity || '()';
- return (
- (inclusivity[0] === '('
- ? this.isAfter(localFrom, units)
- : !this.isBefore(localFrom, units)) &&
- (inclusivity[1] === ')'
- ? this.isBefore(localTo, units)
- : !this.isAfter(localTo, units))
- );
- }
-
- function isSame(input, units) {
- var localInput = isMoment(input) ? input : createLocal(input),
- inputMs;
- if (!(this.isValid() && localInput.isValid())) {
- return false;
- }
- units = normalizeUnits(units) || 'millisecond';
- if (units === 'millisecond') {
- return this.valueOf() === localInput.valueOf();
- } else {
- inputMs = localInput.valueOf();
- return (
- this.clone().startOf(units).valueOf() <= inputMs &&
- inputMs <= this.clone().endOf(units).valueOf()
- );
- }
- }
-
- function isSameOrAfter(input, units) {
- return this.isSame(input, units) || this.isAfter(input, units);
- }
-
- function isSameOrBefore(input, units) {
- return this.isSame(input, units) || this.isBefore(input, units);
- }
-
- function diff(input, units, asFloat) {
- var that, zoneDelta, output;
-
- if (!this.isValid()) {
- return NaN;
- }
-
- that = cloneWithOffset(input, this);
-
- if (!that.isValid()) {
- return NaN;
- }
-
- zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
-
- units = normalizeUnits(units);
-
- switch (units) {
- case 'year':
- output = monthDiff(this, that) / 12;
- break;
- case 'month':
- output = monthDiff(this, that);
- break;
- case 'quarter':
- output = monthDiff(this, that) / 3;
- break;
- case 'second':
- output = (this - that) / 1e3;
- break; // 1000
- case 'minute':
- output = (this - that) / 6e4;
- break; // 1000 * 60
- case 'hour':
- output = (this - that) / 36e5;
- break; // 1000 * 60 * 60
- case 'day':
- output = (this - that - zoneDelta) / 864e5;
- break; // 1000 * 60 * 60 * 24, negate dst
- case 'week':
- output = (this - that - zoneDelta) / 6048e5;
- break; // 1000 * 60 * 60 * 24 * 7, negate dst
- default:
- output = this - that;
- }
-
- return asFloat ? output : absFloor(output);
- }
-
- function monthDiff(a, b) {
- if (a.date() < b.date()) {
- // end-of-month calculations work correct when the start month has more
- // days than the end month.
- return -monthDiff(b, a);
- }
- // difference in months
- var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
- // b is in (anchor - 1 month, anchor + 1 month)
- anchor = a.clone().add(wholeMonthDiff, 'months'),
- anchor2,
- adjust;
-
- if (b - anchor < 0) {
- anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
- // linear across the month
- adjust = (b - anchor) / (anchor - anchor2);
- } else {
- anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
- // linear across the month
- adjust = (b - anchor) / (anchor2 - anchor);
- }
-
- //check for negative zero, return zero if negative zero
- return -(wholeMonthDiff + adjust) || 0;
- }
-
- hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
- hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
-
- function toString() {
- return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
- }
-
- function toISOString(keepOffset) {
- if (!this.isValid()) {
- return null;
- }
- var utc = keepOffset !== true,
- m = utc ? this.clone().utc() : this;
- if (m.year() < 0 || m.year() > 9999) {
- return formatMoment(
- m,
- utc
- ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
- : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
- );
- }
- if (isFunction(Date.prototype.toISOString)) {
- // native implementation is ~50x faster, use it when we can
- if (utc) {
- return this.toDate().toISOString();
- } else {
- return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
- .toISOString()
- .replace('Z', formatMoment(m, 'Z'));
- }
- }
- return formatMoment(
- m,
- utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
- );
- }
-
- /**
- * Return a human readable representation of a moment that can
- * also be evaluated to get a new moment which is the same
- *
- * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
- */
- function inspect() {
- if (!this.isValid()) {
- return 'moment.invalid(/* ' + this._i + ' */)';
- }
- var func = 'moment',
- zone = '',
- prefix,
- year,
- datetime,
- suffix;
- if (!this.isLocal()) {
- func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
- zone = 'Z';
- }
- prefix = '[' + func + '("]';
- year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
- datetime = '-MM-DD[T]HH:mm:ss.SSS';
- suffix = zone + '[")]';
-
- return this.format(prefix + year + datetime + suffix);
- }
-
- function format(inputString) {
- if (!inputString) {
- inputString = this.isUtc()
- ? hooks.defaultFormatUtc
- : hooks.defaultFormat;
- }
- var output = formatMoment(this, inputString);
- return this.localeData().postformat(output);
- }
-
- function from(time, withoutSuffix) {
- if (
- this.isValid() &&
- ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
- ) {
- return createDuration({ to: this, from: time })
- .locale(this.locale())
- .humanize(!withoutSuffix);
- } else {
- return this.localeData().invalidDate();
- }
- }
-
- function fromNow(withoutSuffix) {
- return this.from(createLocal(), withoutSuffix);
- }
-
- function to(time, withoutSuffix) {
- if (
- this.isValid() &&
- ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
- ) {
- return createDuration({ from: this, to: time })
- .locale(this.locale())
- .humanize(!withoutSuffix);
- } else {
- return this.localeData().invalidDate();
- }
- }
-
- function toNow(withoutSuffix) {
- return this.to(createLocal(), withoutSuffix);
- }
-
- // If passed a locale key, it will set the locale for this
- // instance. Otherwise, it will return the locale configuration
- // variables for this instance.
- function locale(key) {
- var newLocaleData;
-
- if (key === undefined) {
- return this._locale._abbr;
- } else {
- newLocaleData = getLocale(key);
- if (newLocaleData != null) {
- this._locale = newLocaleData;
- }
- return this;
- }
- }
-
- var lang = deprecate(
- 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
- function (key) {
- if (key === undefined) {
- return this.localeData();
- } else {
- return this.locale(key);
- }
- }
- );
-
- function localeData() {
- return this._locale;
- }
-
- var MS_PER_SECOND = 1000,
- MS_PER_MINUTE = 60 * MS_PER_SECOND,
- MS_PER_HOUR = 60 * MS_PER_MINUTE,
- MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
-
- // actual modulo - handles negative numbers (for dates before 1970):
- function mod$1(dividend, divisor) {
- return ((dividend % divisor) + divisor) % divisor;
- }
-
- function localStartOfDate(y, m, d) {
- // the date constructor remaps years 0-99 to 1900-1999
- if (y < 100 && y >= 0) {
- // preserve leap years using a full 400 year cycle, then reset
- return new Date(y + 400, m, d) - MS_PER_400_YEARS;
- } else {
- return new Date(y, m, d).valueOf();
- }
- }
-
- function utcStartOfDate(y, m, d) {
- // Date.UTC remaps years 0-99 to 1900-1999
- if (y < 100 && y >= 0) {
- // preserve leap years using a full 400 year cycle, then reset
- return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
- } else {
- return Date.UTC(y, m, d);
- }
- }
-
- function startOf(units) {
- var time, startOfDate;
- units = normalizeUnits(units);
- if (units === undefined || units === 'millisecond' || !this.isValid()) {
- return this;
- }
-
- startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
-
- switch (units) {
- case 'year':
- time = startOfDate(this.year(), 0, 1);
- break;
- case 'quarter':
- time = startOfDate(
- this.year(),
- this.month() - (this.month() % 3),
- 1
- );
- break;
- case 'month':
- time = startOfDate(this.year(), this.month(), 1);
- break;
- case 'week':
- time = startOfDate(
- this.year(),
- this.month(),
- this.date() - this.weekday()
- );
- break;
- case 'isoWeek':
- time = startOfDate(
- this.year(),
- this.month(),
- this.date() - (this.isoWeekday() - 1)
- );
- break;
- case 'day':
- case 'date':
- time = startOfDate(this.year(), this.month(), this.date());
- break;
- case 'hour':
- time = this._d.valueOf();
- time -= mod$1(
- time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
- MS_PER_HOUR
- );
- break;
- case 'minute':
- time = this._d.valueOf();
- time -= mod$1(time, MS_PER_MINUTE);
- break;
- case 'second':
- time = this._d.valueOf();
- time -= mod$1(time, MS_PER_SECOND);
- break;
- }
-
- this._d.setTime(time);
- hooks.updateOffset(this, true);
- return this;
- }
-
- function endOf(units) {
- var time, startOfDate;
- units = normalizeUnits(units);
- if (units === undefined || units === 'millisecond' || !this.isValid()) {
- return this;
- }
-
- startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
-
- switch (units) {
- case 'year':
- time = startOfDate(this.year() + 1, 0, 1) - 1;
- break;
- case 'quarter':
- time =
- startOfDate(
- this.year(),
- this.month() - (this.month() % 3) + 3,
- 1
- ) - 1;
- break;
- case 'month':
- time = startOfDate(this.year(), this.month() + 1, 1) - 1;
- break;
- case 'week':
- time =
- startOfDate(
- this.year(),
- this.month(),
- this.date() - this.weekday() + 7
- ) - 1;
- break;
- case 'isoWeek':
- time =
- startOfDate(
- this.year(),
- this.month(),
- this.date() - (this.isoWeekday() - 1) + 7
- ) - 1;
- break;
- case 'day':
- case 'date':
- time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
- break;
- case 'hour':
- time = this._d.valueOf();
- time +=
- MS_PER_HOUR -
- mod$1(
- time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
- MS_PER_HOUR
- ) -
- 1;
- break;
- case 'minute':
- time = this._d.valueOf();
- time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
- break;
- case 'second':
- time = this._d.valueOf();
- time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
- break;
- }
-
- this._d.setTime(time);
- hooks.updateOffset(this, true);
- return this;
- }
-
- function valueOf() {
- return this._d.valueOf() - (this._offset || 0) * 60000;
- }
-
- function unix() {
- return Math.floor(this.valueOf() / 1000);
- }
-
- function toDate() {
- return new Date(this.valueOf());
- }
-
- function toArray() {
- var m = this;
- return [
- m.year(),
- m.month(),
- m.date(),
- m.hour(),
- m.minute(),
- m.second(),
- m.millisecond(),
- ];
- }
-
- function toObject() {
- var m = this;
- return {
- years: m.year(),
- months: m.month(),
- date: m.date(),
- hours: m.hours(),
- minutes: m.minutes(),
- seconds: m.seconds(),
- milliseconds: m.milliseconds(),
- };
- }
-
- function toJSON() {
- // new Date(NaN).toJSON() === null
- return this.isValid() ? this.toISOString() : null;
- }
-
- function isValid$2() {
- return isValid(this);
- }
-
- function parsingFlags() {
- return extend({}, getParsingFlags(this));
- }
-
- function invalidAt() {
- return getParsingFlags(this).overflow;
- }
-
- function creationData() {
- return {
- input: this._i,
- format: this._f,
- locale: this._locale,
- isUTC: this._isUTC,
- strict: this._strict,
- };
- }
-
- addFormatToken('N', 0, 0, 'eraAbbr');
- addFormatToken('NN', 0, 0, 'eraAbbr');
- addFormatToken('NNN', 0, 0, 'eraAbbr');
- addFormatToken('NNNN', 0, 0, 'eraName');
- addFormatToken('NNNNN', 0, 0, 'eraNarrow');
-
- addFormatToken('y', ['y', 1], 'yo', 'eraYear');
- addFormatToken('y', ['yy', 2], 0, 'eraYear');
- addFormatToken('y', ['yyy', 3], 0, 'eraYear');
- addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
-
- addRegexToken('N', matchEraAbbr);
- addRegexToken('NN', matchEraAbbr);
- addRegexToken('NNN', matchEraAbbr);
- addRegexToken('NNNN', matchEraName);
- addRegexToken('NNNNN', matchEraNarrow);
-
- addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
- input,
- array,
- config,
- token
- ) {
- var era = config._locale.erasParse(input, token, config._strict);
- if (era) {
- getParsingFlags(config).era = era;
- } else {
- getParsingFlags(config).invalidEra = input;
- }
- });
-
- addRegexToken('y', matchUnsigned);
- addRegexToken('yy', matchUnsigned);
- addRegexToken('yyy', matchUnsigned);
- addRegexToken('yyyy', matchUnsigned);
- addRegexToken('yo', matchEraYearOrdinal);
-
- addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
- addParseToken(['yo'], function (input, array, config, token) {
- var match;
- if (config._locale._eraYearOrdinalRegex) {
- match = input.match(config._locale._eraYearOrdinalRegex);
- }
-
- if (config._locale.eraYearOrdinalParse) {
- array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
- } else {
- array[YEAR] = parseInt(input, 10);
- }
- });
-
- function localeEras(m, format) {
- var i,
- l,
- date,
- eras = this._eras || getLocale('en')._eras;
- for (i = 0, l = eras.length; i < l; ++i) {
- switch (typeof eras[i].since) {
- case 'string':
- // truncate time
- date = hooks(eras[i].since).startOf('day');
- eras[i].since = date.valueOf();
- break;
- }
-
- switch (typeof eras[i].until) {
- case 'undefined':
- eras[i].until = +Infinity;
- break;
- case 'string':
- // truncate time
- date = hooks(eras[i].until).startOf('day').valueOf();
- eras[i].until = date.valueOf();
- break;
- }
- }
- return eras;
- }
-
- function localeErasParse(eraName, format, strict) {
- var i,
- l,
- eras = this.eras(),
- name,
- abbr,
- narrow;
- eraName = eraName.toUpperCase();
-
- for (i = 0, l = eras.length; i < l; ++i) {
- name = eras[i].name.toUpperCase();
- abbr = eras[i].abbr.toUpperCase();
- narrow = eras[i].narrow.toUpperCase();
-
- if (strict) {
- switch (format) {
- case 'N':
- case 'NN':
- case 'NNN':
- if (abbr === eraName) {
- return eras[i];
- }
- break;
-
- case 'NNNN':
- if (name === eraName) {
- return eras[i];
- }
- break;
-
- case 'NNNNN':
- if (narrow === eraName) {
- return eras[i];
- }
- break;
- }
- } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
- return eras[i];
- }
- }
- }
-
- function localeErasConvertYear(era, year) {
- var dir = era.since <= era.until ? +1 : -1;
- if (year === undefined) {
- return hooks(era.since).year();
- } else {
- return hooks(era.since).year() + (year - era.offset) * dir;
- }
- }
-
- function getEraName() {
- var i,
- l,
- val,
- eras = this.localeData().eras();
- for (i = 0, l = eras.length; i < l; ++i) {
- // truncate time
- val = this.clone().startOf('day').valueOf();
-
- if (eras[i].since <= val && val <= eras[i].until) {
- return eras[i].name;
- }
- if (eras[i].until <= val && val <= eras[i].since) {
- return eras[i].name;
- }
- }
-
- return '';
- }
-
- function getEraNarrow() {
- var i,
- l,
- val,
- eras = this.localeData().eras();
- for (i = 0, l = eras.length; i < l; ++i) {
- // truncate time
- val = this.clone().startOf('day').valueOf();
-
- if (eras[i].since <= val && val <= eras[i].until) {
- return eras[i].narrow;
- }
- if (eras[i].until <= val && val <= eras[i].since) {
- return eras[i].narrow;
- }
- }
-
- return '';
- }
-
- function getEraAbbr() {
- var i,
- l,
- val,
- eras = this.localeData().eras();
- for (i = 0, l = eras.length; i < l; ++i) {
- // truncate time
- val = this.clone().startOf('day').valueOf();
-
- if (eras[i].since <= val && val <= eras[i].until) {
- return eras[i].abbr;
- }
- if (eras[i].until <= val && val <= eras[i].since) {
- return eras[i].abbr;
- }
- }
-
- return '';
- }
-
- function getEraYear() {
- var i,
- l,
- dir,
- val,
- eras = this.localeData().eras();
- for (i = 0, l = eras.length; i < l; ++i) {
- dir = eras[i].since <= eras[i].until ? +1 : -1;
-
- // truncate time
- val = this.clone().startOf('day').valueOf();
-
- if (
- (eras[i].since <= val && val <= eras[i].until) ||
- (eras[i].until <= val && val <= eras[i].since)
- ) {
- return (
- (this.year() - hooks(eras[i].since).year()) * dir +
- eras[i].offset
- );
- }
- }
-
- return this.year();
- }
-
- function erasNameRegex(isStrict) {
- if (!hasOwnProp(this, '_erasNameRegex')) {
- computeErasParse.call(this);
- }
- return isStrict ? this._erasNameRegex : this._erasRegex;
- }
-
- function erasAbbrRegex(isStrict) {
- if (!hasOwnProp(this, '_erasAbbrRegex')) {
- computeErasParse.call(this);
- }
- return isStrict ? this._erasAbbrRegex : this._erasRegex;
- }
-
- function erasNarrowRegex(isStrict) {
- if (!hasOwnProp(this, '_erasNarrowRegex')) {
- computeErasParse.call(this);
- }
- return isStrict ? this._erasNarrowRegex : this._erasRegex;
- }
-
- function matchEraAbbr(isStrict, locale) {
- return locale.erasAbbrRegex(isStrict);
- }
-
- function matchEraName(isStrict, locale) {
- return locale.erasNameRegex(isStrict);
- }
-
- function matchEraNarrow(isStrict, locale) {
- return locale.erasNarrowRegex(isStrict);
- }
-
- function matchEraYearOrdinal(isStrict, locale) {
- return locale._eraYearOrdinalRegex || matchUnsigned;
- }
-
- function computeErasParse() {
- var abbrPieces = [],
- namePieces = [],
- narrowPieces = [],
- mixedPieces = [],
- i,
- l,
- eras = this.eras();
-
- for (i = 0, l = eras.length; i < l; ++i) {
- namePieces.push(regexEscape(eras[i].name));
- abbrPieces.push(regexEscape(eras[i].abbr));
- narrowPieces.push(regexEscape(eras[i].narrow));
-
- mixedPieces.push(regexEscape(eras[i].name));
- mixedPieces.push(regexEscape(eras[i].abbr));
- mixedPieces.push(regexEscape(eras[i].narrow));
- }
-
- this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
- this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
- this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
- this._erasNarrowRegex = new RegExp(
- '^(' + narrowPieces.join('|') + ')',
- 'i'
- );
- }
-
- // FORMATTING
-
- addFormatToken(0, ['gg', 2], 0, function () {
- return this.weekYear() % 100;
- });
-
- addFormatToken(0, ['GG', 2], 0, function () {
- return this.isoWeekYear() % 100;
- });
-
- function addWeekYearFormatToken(token, getter) {
- addFormatToken(0, [token, token.length], 0, getter);
- }
-
- addWeekYearFormatToken('gggg', 'weekYear');
- addWeekYearFormatToken('ggggg', 'weekYear');
- addWeekYearFormatToken('GGGG', 'isoWeekYear');
- addWeekYearFormatToken('GGGGG', 'isoWeekYear');
-
- // ALIASES
-
- addUnitAlias('weekYear', 'gg');
- addUnitAlias('isoWeekYear', 'GG');
-
- // PRIORITY
-
- addUnitPriority('weekYear', 1);
- addUnitPriority('isoWeekYear', 1);
-
- // PARSING
-
- addRegexToken('G', matchSigned);
- addRegexToken('g', matchSigned);
- addRegexToken('GG', match1to2, match2);
- addRegexToken('gg', match1to2, match2);
- addRegexToken('GGGG', match1to4, match4);
- addRegexToken('gggg', match1to4, match4);
- addRegexToken('GGGGG', match1to6, match6);
- addRegexToken('ggggg', match1to6, match6);
-
- addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
- input,
- week,
- config,
- token
- ) {
- week[token.substr(0, 2)] = toInt(input);
- });
-
- addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
- week[token] = hooks.parseTwoDigitYear(input);
- });
-
- // MOMENTS
-
- function getSetWeekYear(input) {
- return getSetWeekYearHelper.call(
- this,
- input,
- this.week(),
- this.weekday(),
- this.localeData()._week.dow,
- this.localeData()._week.doy
- );
- }
-
- function getSetISOWeekYear(input) {
- return getSetWeekYearHelper.call(
- this,
- input,
- this.isoWeek(),
- this.isoWeekday(),
- 1,
- 4
- );
- }
-
- function getISOWeeksInYear() {
- return weeksInYear(this.year(), 1, 4);
- }
-
- function getISOWeeksInISOWeekYear() {
- return weeksInYear(this.isoWeekYear(), 1, 4);
- }
-
- function getWeeksInYear() {
- var weekInfo = this.localeData()._week;
- return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
- }
-
- function getWeeksInWeekYear() {
- var weekInfo = this.localeData()._week;
- return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
- }
-
- function getSetWeekYearHelper(input, week, weekday, dow, doy) {
- var weeksTarget;
- if (input == null) {
- return weekOfYear(this, dow, doy).year;
- } else {
- weeksTarget = weeksInYear(input, dow, doy);
- if (week > weeksTarget) {
- week = weeksTarget;
- }
- return setWeekAll.call(this, input, week, weekday, dow, doy);
- }
- }
-
- function setWeekAll(weekYear, week, weekday, dow, doy) {
- var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
- date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
-
- this.year(date.getUTCFullYear());
- this.month(date.getUTCMonth());
- this.date(date.getUTCDate());
- return this;
- }
-
- // FORMATTING
-
- addFormatToken('Q', 0, 'Qo', 'quarter');
-
- // ALIASES
-
- addUnitAlias('quarter', 'Q');
-
- // PRIORITY
-
- addUnitPriority('quarter', 7);
-
- // PARSING
-
- addRegexToken('Q', match1);
- addParseToken('Q', function (input, array) {
- array[MONTH] = (toInt(input) - 1) * 3;
- });
-
- // MOMENTS
-
- function getSetQuarter(input) {
- return input == null
- ? Math.ceil((this.month() + 1) / 3)
- : this.month((input - 1) * 3 + (this.month() % 3));
- }
-
- // FORMATTING
-
- addFormatToken('D', ['DD', 2], 'Do', 'date');
-
- // ALIASES
-
- addUnitAlias('date', 'D');
-
- // PRIORITY
- addUnitPriority('date', 9);
-
- // PARSING
-
- addRegexToken('D', match1to2);
- addRegexToken('DD', match1to2, match2);
- addRegexToken('Do', function (isStrict, locale) {
- // TODO: Remove "ordinalParse" fallback in next major release.
- return isStrict
- ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
- : locale._dayOfMonthOrdinalParseLenient;
- });
-
- addParseToken(['D', 'DD'], DATE);
- addParseToken('Do', function (input, array) {
- array[DATE] = toInt(input.match(match1to2)[0]);
- });
-
- // MOMENTS
-
- var getSetDayOfMonth = makeGetSet('Date', true);
-
- // FORMATTING
-
- addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
-
- // ALIASES
-
- addUnitAlias('dayOfYear', 'DDD');
-
- // PRIORITY
- addUnitPriority('dayOfYear', 4);
-
- // PARSING
-
- addRegexToken('DDD', match1to3);
- addRegexToken('DDDD', match3);
- addParseToken(['DDD', 'DDDD'], function (input, array, config) {
- config._dayOfYear = toInt(input);
- });
-
- // HELPERS
-
- // MOMENTS
-
- function getSetDayOfYear(input) {
- var dayOfYear =
- Math.round(
- (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
- ) + 1;
- return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
- }
-
- // FORMATTING
-
- addFormatToken('m', ['mm', 2], 0, 'minute');
-
- // ALIASES
-
- addUnitAlias('minute', 'm');
-
- // PRIORITY
-
- addUnitPriority('minute', 14);
-
- // PARSING
-
- addRegexToken('m', match1to2);
- addRegexToken('mm', match1to2, match2);
- addParseToken(['m', 'mm'], MINUTE);
-
- // MOMENTS
-
- var getSetMinute = makeGetSet('Minutes', false);
-
- // FORMATTING
-
- addFormatToken('s', ['ss', 2], 0, 'second');
-
- // ALIASES
-
- addUnitAlias('second', 's');
-
- // PRIORITY
-
- addUnitPriority('second', 15);
-
- // PARSING
-
- addRegexToken('s', match1to2);
- addRegexToken('ss', match1to2, match2);
- addParseToken(['s', 'ss'], SECOND);
-
- // MOMENTS
-
- var getSetSecond = makeGetSet('Seconds', false);
-
- // FORMATTING
-
- addFormatToken('S', 0, 0, function () {
- return ~~(this.millisecond() / 100);
- });
-
- addFormatToken(0, ['SS', 2], 0, function () {
- return ~~(this.millisecond() / 10);
- });
-
- addFormatToken(0, ['SSS', 3], 0, 'millisecond');
- addFormatToken(0, ['SSSS', 4], 0, function () {
- return this.millisecond() * 10;
- });
- addFormatToken(0, ['SSSSS', 5], 0, function () {
- return this.millisecond() * 100;
- });
- addFormatToken(0, ['SSSSSS', 6], 0, function () {
- return this.millisecond() * 1000;
- });
- addFormatToken(0, ['SSSSSSS', 7], 0, function () {
- return this.millisecond() * 10000;
- });
- addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
- return this.millisecond() * 100000;
- });
- addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
- return this.millisecond() * 1000000;
- });
-
- // ALIASES
-
- addUnitAlias('millisecond', 'ms');
-
- // PRIORITY
-
- addUnitPriority('millisecond', 16);
-
- // PARSING
-
- addRegexToken('S', match1to3, match1);
- addRegexToken('SS', match1to3, match2);
- addRegexToken('SSS', match1to3, match3);
-
- var token, getSetMillisecond;
- for (token = 'SSSS'; token.length <= 9; token += 'S') {
- addRegexToken(token, matchUnsigned);
- }
-
- function parseMs(input, array) {
- array[MILLISECOND] = toInt(('0.' + input) * 1000);
- }
-
- for (token = 'S'; token.length <= 9; token += 'S') {
- addParseToken(token, parseMs);
- }
-
- getSetMillisecond = makeGetSet('Milliseconds', false);
-
- // FORMATTING
-
- addFormatToken('z', 0, 0, 'zoneAbbr');
- addFormatToken('zz', 0, 0, 'zoneName');
-
- // MOMENTS
-
- function getZoneAbbr() {
- return this._isUTC ? 'UTC' : '';
- }
-
- function getZoneName() {
- return this._isUTC ? 'Coordinated Universal Time' : '';
- }
-
- var proto = Moment.prototype;
-
- proto.add = add;
- proto.calendar = calendar$1;
- proto.clone = clone;
- proto.diff = diff;
- proto.endOf = endOf;
- proto.format = format;
- proto.from = from;
- proto.fromNow = fromNow;
- proto.to = to;
- proto.toNow = toNow;
- proto.get = stringGet;
- proto.invalidAt = invalidAt;
- proto.isAfter = isAfter;
- proto.isBefore = isBefore;
- proto.isBetween = isBetween;
- proto.isSame = isSame;
- proto.isSameOrAfter = isSameOrAfter;
- proto.isSameOrBefore = isSameOrBefore;
- proto.isValid = isValid$2;
- proto.lang = lang;
- proto.locale = locale;
- proto.localeData = localeData;
- proto.max = prototypeMax;
- proto.min = prototypeMin;
- proto.parsingFlags = parsingFlags;
- proto.set = stringSet;
- proto.startOf = startOf;
- proto.subtract = subtract;
- proto.toArray = toArray;
- proto.toObject = toObject;
- proto.toDate = toDate;
- proto.toISOString = toISOString;
- proto.inspect = inspect;
- if (typeof Symbol !== 'undefined' && Symbol.for != null) {
- proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
- return 'Moment<' + this.format() + '>';
- };
- }
- proto.toJSON = toJSON;
- proto.toString = toString;
- proto.unix = unix;
- proto.valueOf = valueOf;
- proto.creationData = creationData;
- proto.eraName = getEraName;
- proto.eraNarrow = getEraNarrow;
- proto.eraAbbr = getEraAbbr;
- proto.eraYear = getEraYear;
- proto.year = getSetYear;
- proto.isLeapYear = getIsLeapYear;
- proto.weekYear = getSetWeekYear;
- proto.isoWeekYear = getSetISOWeekYear;
- proto.quarter = proto.quarters = getSetQuarter;
- proto.month = getSetMonth;
- proto.daysInMonth = getDaysInMonth;
- proto.week = proto.weeks = getSetWeek;
- proto.isoWeek = proto.isoWeeks = getSetISOWeek;
- proto.weeksInYear = getWeeksInYear;
- proto.weeksInWeekYear = getWeeksInWeekYear;
- proto.isoWeeksInYear = getISOWeeksInYear;
- proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
- proto.date = getSetDayOfMonth;
- proto.day = proto.days = getSetDayOfWeek;
- proto.weekday = getSetLocaleDayOfWeek;
- proto.isoWeekday = getSetISODayOfWeek;
- proto.dayOfYear = getSetDayOfYear;
- proto.hour = proto.hours = getSetHour;
- proto.minute = proto.minutes = getSetMinute;
- proto.second = proto.seconds = getSetSecond;
- proto.millisecond = proto.milliseconds = getSetMillisecond;
- proto.utcOffset = getSetOffset;
- proto.utc = setOffsetToUTC;
- proto.local = setOffsetToLocal;
- proto.parseZone = setOffsetToParsedOffset;
- proto.hasAlignedHourOffset = hasAlignedHourOffset;
- proto.isDST = isDaylightSavingTime;
- proto.isLocal = isLocal;
- proto.isUtcOffset = isUtcOffset;
- proto.isUtc = isUtc;
- proto.isUTC = isUtc;
- proto.zoneAbbr = getZoneAbbr;
- proto.zoneName = getZoneName;
- proto.dates = deprecate(
- 'dates accessor is deprecated. Use date instead.',
- getSetDayOfMonth
- );
- proto.months = deprecate(
- 'months accessor is deprecated. Use month instead',
- getSetMonth
- );
- proto.years = deprecate(
- 'years accessor is deprecated. Use year instead',
- getSetYear
- );
- proto.zone = deprecate(
- 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
- getSetZone
- );
- proto.isDSTShifted = deprecate(
- 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
- isDaylightSavingTimeShifted
- );
-
- function createUnix(input) {
- return createLocal(input * 1000);
- }
-
- function createInZone() {
- return createLocal.apply(null, arguments).parseZone();
- }
-
- function preParsePostFormat(string) {
- return string;
- }
-
- var proto$1 = Locale.prototype;
-
- proto$1.calendar = calendar;
- proto$1.longDateFormat = longDateFormat;
- proto$1.invalidDate = invalidDate;
- proto$1.ordinal = ordinal;
- proto$1.preparse = preParsePostFormat;
- proto$1.postformat = preParsePostFormat;
- proto$1.relativeTime = relativeTime;
- proto$1.pastFuture = pastFuture;
- proto$1.set = set;
- proto$1.eras = localeEras;
- proto$1.erasParse = localeErasParse;
- proto$1.erasConvertYear = localeErasConvertYear;
- proto$1.erasAbbrRegex = erasAbbrRegex;
- proto$1.erasNameRegex = erasNameRegex;
- proto$1.erasNarrowRegex = erasNarrowRegex;
-
- proto$1.months = localeMonths;
- proto$1.monthsShort = localeMonthsShort;
- proto$1.monthsParse = localeMonthsParse;
- proto$1.monthsRegex = monthsRegex;
- proto$1.monthsShortRegex = monthsShortRegex;
- proto$1.week = localeWeek;
- proto$1.firstDayOfYear = localeFirstDayOfYear;
- proto$1.firstDayOfWeek = localeFirstDayOfWeek;
-
- proto$1.weekdays = localeWeekdays;
- proto$1.weekdaysMin = localeWeekdaysMin;
- proto$1.weekdaysShort = localeWeekdaysShort;
- proto$1.weekdaysParse = localeWeekdaysParse;
-
- proto$1.weekdaysRegex = weekdaysRegex;
- proto$1.weekdaysShortRegex = weekdaysShortRegex;
- proto$1.weekdaysMinRegex = weekdaysMinRegex;
-
- proto$1.isPM = localeIsPM;
- proto$1.meridiem = localeMeridiem;
-
- function get$1(format, index, field, setter) {
- var locale = getLocale(),
- utc = createUTC().set(setter, index);
- return locale[field](utc, format);
- }
-
- function listMonthsImpl(format, index, field) {
- if (isNumber(format)) {
- index = format;
- format = undefined;
- }
-
- format = format || '';
-
- if (index != null) {
- return get$1(format, index, field, 'month');
- }
-
- var i,
- out = [];
- for (i = 0; i < 12; i++) {
- out[i] = get$1(format, i, field, 'month');
- }
- return out;
- }
-
- // ()
- // (5)
- // (fmt, 5)
- // (fmt)
- // (true)
- // (true, 5)
- // (true, fmt, 5)
- // (true, fmt)
- function listWeekdaysImpl(localeSorted, format, index, field) {
- if (typeof localeSorted === 'boolean') {
- if (isNumber(format)) {
- index = format;
- format = undefined;
- }
-
- format = format || '';
- } else {
- format = localeSorted;
- index = format;
- localeSorted = false;
-
- if (isNumber(format)) {
- index = format;
- format = undefined;
- }
-
- format = format || '';
- }
-
- var locale = getLocale(),
- shift = localeSorted ? locale._week.dow : 0,
- i,
- out = [];
-
- if (index != null) {
- return get$1(format, (index + shift) % 7, field, 'day');
- }
-
- for (i = 0; i < 7; i++) {
- out[i] = get$1(format, (i + shift) % 7, field, 'day');
- }
- return out;
- }
-
- function listMonths(format, index) {
- return listMonthsImpl(format, index, 'months');
- }
-
- function listMonthsShort(format, index) {
- return listMonthsImpl(format, index, 'monthsShort');
- }
-
- function listWeekdays(localeSorted, format, index) {
- return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
- }
-
- function listWeekdaysShort(localeSorted, format, index) {
- return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
- }
-
- function listWeekdaysMin(localeSorted, format, index) {
- return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
- }
-
- getSetGlobalLocale('en', {
- eras: [
- {
- since: '0001-01-01',
- until: +Infinity,
- offset: 1,
- name: 'Anno Domini',
- narrow: 'AD',
- abbr: 'AD',
- },
- {
- since: '0000-12-31',
- until: -Infinity,
- offset: 1,
- name: 'Before Christ',
- narrow: 'BC',
- abbr: 'BC',
- },
- ],
- dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
- ordinal: function (number) {
- var b = number % 10,
- output =
- toInt((number % 100) / 10) === 1
- ? 'th'
- : b === 1
- ? 'st'
- : b === 2
- ? 'nd'
- : b === 3
- ? 'rd'
- : 'th';
- return number + output;
- },
- });
-
- // Side effect imports
-
- hooks.lang = deprecate(
- 'moment.lang is deprecated. Use moment.locale instead.',
- getSetGlobalLocale
- );
- hooks.langData = deprecate(
- 'moment.langData is deprecated. Use moment.localeData instead.',
- getLocale
- );
-
- var mathAbs = Math.abs;
-
- function abs() {
- var data = this._data;
-
- this._milliseconds = mathAbs(this._milliseconds);
- this._days = mathAbs(this._days);
- this._months = mathAbs(this._months);
-
- data.milliseconds = mathAbs(data.milliseconds);
- data.seconds = mathAbs(data.seconds);
- data.minutes = mathAbs(data.minutes);
- data.hours = mathAbs(data.hours);
- data.months = mathAbs(data.months);
- data.years = mathAbs(data.years);
-
- return this;
- }
-
- function addSubtract$1(duration, input, value, direction) {
- var other = createDuration(input, value);
-
- duration._milliseconds += direction * other._milliseconds;
- duration._days += direction * other._days;
- duration._months += direction * other._months;
-
- return duration._bubble();
- }
-
- // supports only 2.0-style add(1, 's') or add(duration)
- function add$1(input, value) {
- return addSubtract$1(this, input, value, 1);
- }
-
- // supports only 2.0-style subtract(1, 's') or subtract(duration)
- function subtract$1(input, value) {
- return addSubtract$1(this, input, value, -1);
- }
-
- function absCeil(number) {
- if (number < 0) {
- return Math.floor(number);
- } else {
- return Math.ceil(number);
- }
- }
-
- function bubble() {
- var milliseconds = this._milliseconds,
- days = this._days,
- months = this._months,
- data = this._data,
- seconds,
- minutes,
- hours,
- years,
- monthsFromDays;
-
- // if we have a mix of positive and negative values, bubble down first
- // check: https://github.com/moment/moment/issues/2166
- if (
- !(
- (milliseconds >= 0 && days >= 0 && months >= 0) ||
- (milliseconds <= 0 && days <= 0 && months <= 0)
- )
- ) {
- milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
- days = 0;
- months = 0;
- }
-
- // The following code bubbles up values, see the tests for
- // examples of what that means.
- data.milliseconds = milliseconds % 1000;
-
- seconds = absFloor(milliseconds / 1000);
- data.seconds = seconds % 60;
-
- minutes = absFloor(seconds / 60);
- data.minutes = minutes % 60;
-
- hours = absFloor(minutes / 60);
- data.hours = hours % 24;
-
- days += absFloor(hours / 24);
-
- // convert days to months
- monthsFromDays = absFloor(daysToMonths(days));
- months += monthsFromDays;
- days -= absCeil(monthsToDays(monthsFromDays));
-
- // 12 months -> 1 year
- years = absFloor(months / 12);
- months %= 12;
-
- data.days = days;
- data.months = months;
- data.years = years;
-
- return this;
- }
-
- function daysToMonths(days) {
- // 400 years have 146097 days (taking into account leap year rules)
- // 400 years have 12 months === 4800
- return (days * 4800) / 146097;
- }
-
- function monthsToDays(months) {
- // the reverse of daysToMonths
- return (months * 146097) / 4800;
- }
-
- function as(units) {
- if (!this.isValid()) {
- return NaN;
- }
- var days,
- months,
- milliseconds = this._milliseconds;
-
- units = normalizeUnits(units);
-
- if (units === 'month' || units === 'quarter' || units === 'year') {
- days = this._days + milliseconds / 864e5;
- months = this._months + daysToMonths(days);
- switch (units) {
- case 'month':
- return months;
- case 'quarter':
- return months / 3;
- case 'year':
- return months / 12;
- }
- } else {
- // handle milliseconds separately because of floating point math errors (issue #1867)
- days = this._days + Math.round(monthsToDays(this._months));
- switch (units) {
- case 'week':
- return days / 7 + milliseconds / 6048e5;
- case 'day':
- return days + milliseconds / 864e5;
- case 'hour':
- return days * 24 + milliseconds / 36e5;
- case 'minute':
- return days * 1440 + milliseconds / 6e4;
- case 'second':
- return days * 86400 + milliseconds / 1000;
- // Math.floor prevents floating point math errors here
- case 'millisecond':
- return Math.floor(days * 864e5) + milliseconds;
- default:
- throw new Error('Unknown unit ' + units);
- }
- }
- }
-
- // TODO: Use this.as('ms')?
- function valueOf$1() {
- if (!this.isValid()) {
- return NaN;
- }
- return (
- this._milliseconds +
- this._days * 864e5 +
- (this._months % 12) * 2592e6 +
- toInt(this._months / 12) * 31536e6
- );
- }
-
- function makeAs(alias) {
- return function () {
- return this.as(alias);
- };
- }
-
- var asMilliseconds = makeAs('ms'),
- asSeconds = makeAs('s'),
- asMinutes = makeAs('m'),
- asHours = makeAs('h'),
- asDays = makeAs('d'),
- asWeeks = makeAs('w'),
- asMonths = makeAs('M'),
- asQuarters = makeAs('Q'),
- asYears = makeAs('y');
-
- function clone$1() {
- return createDuration(this);
- }
-
- function get$2(units) {
- units = normalizeUnits(units);
- return this.isValid() ? this[units + 's']() : NaN;
- }
-
- function makeGetter(name) {
- return function () {
- return this.isValid() ? this._data[name] : NaN;
- };
- }
-
- var milliseconds = makeGetter('milliseconds'),
- seconds = makeGetter('seconds'),
- minutes = makeGetter('minutes'),
- hours = makeGetter('hours'),
- days = makeGetter('days'),
- months = makeGetter('months'),
- years = makeGetter('years');
-
- function weeks() {
- return absFloor(this.days() / 7);
- }
-
- var round = Math.round,
- thresholds = {
- ss: 44, // a few seconds to seconds
- s: 45, // seconds to minute
- m: 45, // minutes to hour
- h: 22, // hours to day
- d: 26, // days to month/week
- w: null, // weeks to month
- M: 11, // months to year
- };
-
- // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
- function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
- return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
- }
-
- function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
- var duration = createDuration(posNegDuration).abs(),
- seconds = round(duration.as('s')),
- minutes = round(duration.as('m')),
- hours = round(duration.as('h')),
- days = round(duration.as('d')),
- months = round(duration.as('M')),
- weeks = round(duration.as('w')),
- years = round(duration.as('y')),
- a =
- (seconds <= thresholds.ss && ['s', seconds]) ||
- (seconds < thresholds.s && ['ss', seconds]) ||
- (minutes <= 1 && ['m']) ||
- (minutes < thresholds.m && ['mm', minutes]) ||
- (hours <= 1 && ['h']) ||
- (hours < thresholds.h && ['hh', hours]) ||
- (days <= 1 && ['d']) ||
- (days < thresholds.d && ['dd', days]);
-
- if (thresholds.w != null) {
- a =
- a ||
- (weeks <= 1 && ['w']) ||
- (weeks < thresholds.w && ['ww', weeks]);
- }
- a = a ||
- (months <= 1 && ['M']) ||
- (months < thresholds.M && ['MM', months]) ||
- (years <= 1 && ['y']) || ['yy', years];
-
- a[2] = withoutSuffix;
- a[3] = +posNegDuration > 0;
- a[4] = locale;
- return substituteTimeAgo.apply(null, a);
- }
-
- // This function allows you to set the rounding function for relative time strings
- function getSetRelativeTimeRounding(roundingFunction) {
- if (roundingFunction === undefined) {
- return round;
- }
- if (typeof roundingFunction === 'function') {
- round = roundingFunction;
- return true;
- }
- return false;
- }
-
- // This function allows you to set a threshold for relative time strings
- function getSetRelativeTimeThreshold(threshold, limit) {
- if (thresholds[threshold] === undefined) {
- return false;
- }
- if (limit === undefined) {
- return thresholds[threshold];
- }
- thresholds[threshold] = limit;
- if (threshold === 's') {
- thresholds.ss = limit - 1;
- }
- return true;
- }
-
- function humanize(argWithSuffix, argThresholds) {
- if (!this.isValid()) {
- return this.localeData().invalidDate();
- }
-
- var withSuffix = false,
- th = thresholds,
- locale,
- output;
-
- if (typeof argWithSuffix === 'object') {
- argThresholds = argWithSuffix;
- argWithSuffix = false;
- }
- if (typeof argWithSuffix === 'boolean') {
- withSuffix = argWithSuffix;
- }
- if (typeof argThresholds === 'object') {
- th = Object.assign({}, thresholds, argThresholds);
- if (argThresholds.s != null && argThresholds.ss == null) {
- th.ss = argThresholds.s - 1;
- }
- }
-
- locale = this.localeData();
- output = relativeTime$1(this, !withSuffix, th, locale);
-
- if (withSuffix) {
- output = locale.pastFuture(+this, output);
- }
-
- return locale.postformat(output);
- }
-
- var abs$1 = Math.abs;
-
- function sign(x) {
- return (x > 0) - (x < 0) || +x;
- }
-
- function toISOString$1() {
- // for ISO strings we do not use the normal bubbling rules:
- // * milliseconds bubble up until they become hours
- // * days do not bubble at all
- // * months bubble up until they become years
- // This is because there is no context-free conversion between hours and days
- // (think of clock changes)
- // and also not between days and months (28-31 days per month)
- if (!this.isValid()) {
- return this.localeData().invalidDate();
- }
-
- var seconds = abs$1(this._milliseconds) / 1000,
- days = abs$1(this._days),
- months = abs$1(this._months),
- minutes,
- hours,
- years,
- s,
- total = this.asSeconds(),
- totalSign,
- ymSign,
- daysSign,
- hmsSign;
-
- if (!total) {
- // this is the same as C#'s (Noda) and python (isodate)...
- // but not other JS (goog.date)
- return 'P0D';
- }
-
- // 3600 seconds -> 60 minutes -> 1 hour
- minutes = absFloor(seconds / 60);
- hours = absFloor(minutes / 60);
- seconds %= 60;
- minutes %= 60;
-
- // 12 months -> 1 year
- years = absFloor(months / 12);
- months %= 12;
-
- // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
- s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
-
- totalSign = total < 0 ? '-' : '';
- ymSign = sign(this._months) !== sign(total) ? '-' : '';
- daysSign = sign(this._days) !== sign(total) ? '-' : '';
- hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
-
- return (
- totalSign +
- 'P' +
- (years ? ymSign + years + 'Y' : '') +
- (months ? ymSign + months + 'M' : '') +
- (days ? daysSign + days + 'D' : '') +
- (hours || minutes || seconds ? 'T' : '') +
- (hours ? hmsSign + hours + 'H' : '') +
- (minutes ? hmsSign + minutes + 'M' : '') +
- (seconds ? hmsSign + s + 'S' : '')
- );
- }
-
- var proto$2 = Duration.prototype;
-
- proto$2.isValid = isValid$1;
- proto$2.abs = abs;
- proto$2.add = add$1;
- proto$2.subtract = subtract$1;
- proto$2.as = as;
- proto$2.asMilliseconds = asMilliseconds;
- proto$2.asSeconds = asSeconds;
- proto$2.asMinutes = asMinutes;
- proto$2.asHours = asHours;
- proto$2.asDays = asDays;
- proto$2.asWeeks = asWeeks;
- proto$2.asMonths = asMonths;
- proto$2.asQuarters = asQuarters;
- proto$2.asYears = asYears;
- proto$2.valueOf = valueOf$1;
- proto$2._bubble = bubble;
- proto$2.clone = clone$1;
- proto$2.get = get$2;
- proto$2.milliseconds = milliseconds;
- proto$2.seconds = seconds;
- proto$2.minutes = minutes;
- proto$2.hours = hours;
- proto$2.days = days;
- proto$2.weeks = weeks;
- proto$2.months = months;
- proto$2.years = years;
- proto$2.humanize = humanize;
- proto$2.toISOString = toISOString$1;
- proto$2.toString = toISOString$1;
- proto$2.toJSON = toISOString$1;
- proto$2.locale = locale;
- proto$2.localeData = localeData;
-
- proto$2.toIsoString = deprecate(
- 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
- toISOString$1
- );
- proto$2.lang = lang;
-
- // FORMATTING
-
- addFormatToken('X', 0, 0, 'unix');
- addFormatToken('x', 0, 0, 'valueOf');
-
- // PARSING
-
- addRegexToken('x', matchSigned);
- addRegexToken('X', matchTimestamp);
- addParseToken('X', function (input, array, config) {
- config._d = new Date(parseFloat(input) * 1000);
- });
- addParseToken('x', function (input, array, config) {
- config._d = new Date(toInt(input));
- });
-
- //! moment.js
-
- hooks.version = '2.29.1';
-
- setHookCallback(createLocal);
-
- hooks.fn = proto;
- hooks.min = min;
- hooks.max = max;
- hooks.now = now;
- hooks.utc = createUTC;
- hooks.unix = createUnix;
- hooks.months = listMonths;
- hooks.isDate = isDate;
- hooks.locale = getSetGlobalLocale;
- hooks.invalid = createInvalid;
- hooks.duration = createDuration;
- hooks.isMoment = isMoment;
- hooks.weekdays = listWeekdays;
- hooks.parseZone = createInZone;
- hooks.localeData = getLocale;
- hooks.isDuration = isDuration;
- hooks.monthsShort = listMonthsShort;
- hooks.weekdaysMin = listWeekdaysMin;
- hooks.defineLocale = defineLocale;
- hooks.updateLocale = updateLocale;
- hooks.locales = listLocales;
- hooks.weekdaysShort = listWeekdaysShort;
- hooks.normalizeUnits = normalizeUnits;
- hooks.relativeTimeRounding = getSetRelativeTimeRounding;
- hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
- hooks.calendarFormat = getCalendarFormat;
- hooks.prototype = proto;
-
- // currently HTML5 input type only supports 24-hour formats
- hooks.HTML5_FMT = {
- DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
- DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
- DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
- DATE: 'YYYY-MM-DD', // <input type="date" />
- TIME: 'HH:mm', // <input type="time" />
- TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
- TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
- WEEK: 'GGGG-[W]WW', // <input type="week" />
- MONTH: 'YYYY-MM', // <input type="month" />
- };
-
- return hooks;
-
- })));
- }, "/$$rollup_base$$/node_modules/moment");
-
- let array8 = arrayUntyped,
- array16 = arrayUntyped,
- array32 = arrayUntyped,
- arrayLengthen = arrayLengthenUntyped,
- arrayWiden = arrayWidenUntyped;
- if (typeof Uint8Array !== "undefined") {
- array8 = function(n) { return new Uint8Array(n); };
- array16 = function(n) { return new Uint16Array(n); };
- array32 = function(n) { return new Uint32Array(n); };
-
- arrayLengthen = function(array, length) {
- if (array.length >= length) return array;
- var copy = new array.constructor(length);
- copy.set(array);
- return copy;
- };
-
- arrayWiden = function(array, width) {
- var copy;
- switch (width) {
- case 16: copy = array16(array.length); break;
- case 32: copy = array32(array.length); break;
- default: throw new Error("invalid array width!");
- }
- copy.set(array);
- return copy;
- };
- }
-
- function arrayUntyped(n) {
- var array = new Array(n), i = -1;
- while (++i < n) array[i] = 0;
- return array;
- }
-
- function arrayLengthenUntyped(array, length) {
- var n = array.length;
- while (n < length) array[n++] = 0;
- return array;
- }
-
- function arrayWidenUntyped(array, width) {
- if (width > 32) throw new Error("invalid array width!");
- return array;
- }
-
- // An arbitrarily-wide array of bitmasks
- function bitarray(n) {
- this.length = n;
- this.subarrays = 1;
- this.width = 8;
- this.masks = {
- 0: 0
- };
-
- this[0] = array8(n);
- }
-
- bitarray.prototype.lengthen = function(n) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- this[i] = arrayLengthen(this[i], n);
- }
- this.length = n;
- };
-
- // Reserve a new bit index in the array, returns {offset, one}
- bitarray.prototype.add = function() {
- var m, w, one, i, len;
-
- for (i = 0, len = this.subarrays; i < len; ++i) {
- m = this.masks[i];
- w = this.width - (32 * i);
- // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
- one = (~m & (m + 1)) >>> 0;
-
- if (w >= 32 && !one) {
- continue;
- }
-
- if (w < 32 && (one & (1 << w))) {
- // widen this subarray
- this[i] = arrayWiden(this[i], w <<= 1);
- this.width = 32 * i + w;
- }
-
- this.masks[i] |= one;
-
- return {
- offset: i,
- one: one
- };
- }
-
- // add a new subarray
- this[this.subarrays] = array8(this.length);
- this.masks[this.subarrays] = 1;
- this.width += 8;
- return {
- offset: this.subarrays++,
- one: 1
- };
- };
-
- // Copy record from index src to index dest
- bitarray.prototype.copy = function(dest, src) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- this[i][dest] = this[i][src];
- }
- };
-
- // Truncate the array to the given length
- bitarray.prototype.truncate = function(n) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- for (var j = this.length - 1; j >= n; j--) {
- this[i][j] = 0;
- }
- }
- this.length = n;
- };
-
- // Checks that all bits for the given index are 0
- bitarray.prototype.zero = function(n) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- if (this[i][n]) {
- return false;
- }
- }
- return true;
- };
-
- // Checks that all bits for the given index are 0 except for possibly one
- bitarray.prototype.zeroExcept = function(n, offset, zero) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- if (i === offset ? this[i][n] & zero : this[i][n]) {
- return false;
- }
- }
- return true;
- };
-
- // Checks that all bits for the given index are 0 except for the specified mask.
- // The mask should be an array of the same size as the filter subarrays width.
- bitarray.prototype.zeroExceptMask = function(n, mask) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- if (this[i][n] & mask[i]) {
- return false;
- }
- }
- return true;
- };
-
- // Checks that only the specified bit is set for the given index
- bitarray.prototype.only = function(n, offset, one) {
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- if (this[i][n] != (i === offset ? one : 0)) {
- return false;
- }
- }
- return true;
- };
-
- // Checks that only the specified bit is set for the given index except for possibly one other
- bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
- var mask;
- var i, len;
- for (i = 0, len = this.subarrays; i < len; ++i) {
- mask = this[i][n];
- if (i === offset)
- mask = (mask & zero) >>> 0;
- if (mask != (i === onlyOffset ? onlyOne : 0)) {
- return false;
- }
- }
- return true;
- };
-
- var xfilterArray = {
- array8: arrayUntyped,
- array16: arrayUntyped,
- array32: arrayUntyped,
- arrayLengthen: arrayLengthenUntyped,
- arrayWiden: arrayWidenUntyped,
- bitarray: bitarray
- };
-
- const filterExact = (bisect, value) => {
- return function(values) {
- var n = values.length;
- return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
- };
- };
-
- const filterRange = (bisect, range) => {
- var min = range[0],
- max = range[1];
- return function(values) {
- var n = values.length;
- return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
- };
- };
-
- const filterAll = values => {
- return [0, values.length];
- };
-
- var xfilterFilter = {
- filterExact,
- filterRange,
- filterAll
- };
-
- var cr_identity = d => {
- return d;
- };
-
- var cr_null = () => {
- return null;
- };
-
- var cr_zero = () => {
- return 0;
- };
-
- function heap_by(f) {
-
- // Builds a binary heap within the specified array a[lo:hi]. The heap has the
- // property such that the parent a[lo+i] is always less than or equal to its
- // two children: a[lo+2*i+1] and a[lo+2*i+2].
- function heap(a, lo, hi) {
- var n = hi - lo,
- i = (n >>> 1) + 1;
- while (--i > 0) sift(a, i, n, lo);
- return a;
- }
-
- // Sorts the specified array a[lo:hi] in descending order, assuming it is
- // already a heap.
- function sort(a, lo, hi) {
- var n = hi - lo,
- t;
- while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
- return a;
- }
-
- // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
- // slice of array a[lo:lo+n]. This method can also be used to update the heap
- // incrementally, without incurring the full cost of reconstructing the heap.
- function sift(a, i, n, lo) {
- var d = a[--lo + i],
- x = f(d),
- child;
- while ((child = i << 1) <= n) {
- if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
- if (x <= f(a[lo + child])) break;
- a[lo + i] = a[lo + child];
- i = child;
- }
- a[lo + i] = d;
- }
-
- heap.sort = sort;
- return heap;
- }
-
- const h$1 = heap_by(cr_identity);
- h$1.by = heap_by;
-
- function heapselect_by(f) {
- var heap = h$1.by(f);
-
- // Returns a new array containing the top k elements in the array a[lo:hi].
- // The returned array is not sorted, but maintains the heap property. If k is
- // greater than hi - lo, then fewer than k elements will be returned. The
- // order of elements in a is unchanged by this operation.
- function heapselect(a, lo, hi, k) {
- var queue = new Array(k = Math.min(hi - lo, k)),
- min,
- i,
- d;
-
- for (i = 0; i < k; ++i) queue[i] = a[lo++];
- heap(queue, 0, k);
-
- if (lo < hi) {
- min = f(queue[0]);
- do {
- if (f(d = a[lo]) > min) {
- queue[0] = d;
- min = f(heap(queue, 0, k)[0]);
- }
- } while (++lo < hi);
- }
-
- return queue;
- }
-
- return heapselect;
- }
-
-
- const h = heapselect_by(cr_identity);
- h.by = heapselect_by; // assign the raw function to the export as well
-
- function bisect_by(f) {
-
- // Locate the insertion point for x in a to maintain sorted order. The
- // arguments lo and hi may be used to specify a subset of the array which
- // should be considered; by default the entire array is used. If x is already
- // present in a, the insertion point will be before (to the left of) any
- // existing entries. The return value is suitable for use as the first
- // argument to `array.splice` assuming that a is already sorted.
- //
- // The returned insertion point i partitions the array a into two halves so
- // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
- // a[i:hi] for the right side.
- function bisectLeft(a, x, lo, hi) {
- while (lo < hi) {
- var mid = lo + hi >>> 1;
- if (f(a[mid]) < x) lo = mid + 1;
- else hi = mid;
- }
- return lo;
- }
-
- // Similar to bisectLeft, but returns an insertion point which comes after (to
- // the right of) any existing entries of x in a.
- //
- // The returned insertion point i partitions the array into two halves so that
- // all v <= x for v in a[lo:i] for the left side and all v > x for v in
- // a[i:hi] for the right side.
- function bisectRight(a, x, lo, hi) {
- while (lo < hi) {
- var mid = lo + hi >>> 1;
- if (x < f(a[mid])) hi = mid;
- else lo = mid + 1;
- }
- return lo;
- }
-
- bisectRight.right = bisectRight;
- bisectRight.left = bisectLeft;
- return bisectRight;
- }
-
- const bisect = bisect_by(cr_identity);
- bisect.by = bisect_by; // assign the raw function to the export as well
-
- var permute = (array, index, deep) => {
- for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
- copy[i] = array[index[i]];
- }
- return copy;
- };
-
- const reduceIncrement = p => {
- return p + 1;
- };
-
- const reduceDecrement = p => {
- return p - 1;
- };
-
- const reduceAdd = f => {
- return function(p, v) {
- return p + +f(v);
- };
- };
-
- const reduceSubtract = f => {
- return function(p, v) {
- return p - f(v);
- };
- };
-
- var xfilterReduce = {
- reduceIncrement,
- reduceDecrement,
- reduceAdd,
- reduceSubtract
- };
-
- 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)}
-
- // Note(cg): result was previsouly using lodash.result, not ESM compatible.
-
- const get = (obj, prop) => {
- const value = obj[prop];
- return (typeof value === 'function') ? value.call(obj) : value;
- };
-
- /**
- * get value of object at a deep path.
- * if the resolved value is a function,
- * it's invoked with the `this` binding of
- * its parent object and its result is returned.
- *
- * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
- * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
- * @return {Any} the resolved value
- */
- const reg = /\[([\w\d]+)\]/g;
- var result = (obj, path) => {
- return deep(get, obj, path.replace(reg, '.$1'))
- };
-
- // constants
- var REMOVED_INDEX = -1;
-
- crossfilter$1.heap = h$1;
- crossfilter$1.heapselect = h;
- crossfilter$1.bisect = bisect;
- crossfilter$1.permute = permute;
-
- function crossfilter$1() {
- var crossfilter = {
- add: add,
- remove: removeData,
- dimension: dimension,
- groupAll: groupAll,
- size: size,
- all: all,
- allFiltered: allFiltered,
- onChange: onChange,
- isElementFiltered: isElementFiltered
- };
-
- var data = [], // the records
- n = 0, // the number of records; data.length
- filters, // 1 is filtered out
- filterListeners = [], // when the filters change
- dataListeners = [], // when data is added
- removeDataListeners = [], // when data is removed
- callbacks = [];
-
- filters = new xfilterArray.bitarray(0);
-
- // Adds the specified new records to this crossfilter.
- function add(newData) {
- var n0 = n,
- n1 = newData.length;
-
- // If there's actually new data to add…
- // Merge the new data into the existing data.
- // Lengthen the filter bitset to handle the new records.
- // Notify listeners (dimensions and groups) that new data is available.
- if (n1) {
- data = data.concat(newData);
- filters.lengthen(n += n1);
- dataListeners.forEach(function(l) { l(newData, n0, n1); });
- triggerOnChange('dataAdded');
- }
-
- return crossfilter;
- }
-
- // Removes all records that match the current filters, or if a predicate function is passed,
- // removes all records matching the predicate (ignoring filters).
- function removeData(predicate) {
- var // Mapping from old record indexes to new indexes (after records removed)
- newIndex = new Array(n),
- removed = [],
- usePred = typeof predicate === 'function',
- shouldRemove = function (i) {
- return usePred ? predicate(data[i], i) : filters.zero(i)
- };
-
- for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
- if ( shouldRemove(index1) ) {
- removed.push(index1);
- newIndex[index1] = REMOVED_INDEX;
- } else {
- newIndex[index1] = index2++;
- }
- }
-
- // Remove all matching records from groups.
- filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
-
- // Update indexes.
- removeDataListeners.forEach(function(l) { l(newIndex); });
-
- // Remove old filters and data by overwriting.
- for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
- if ( newIndex[index3] !== REMOVED_INDEX ) {
- if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
- ++index4;
- }
- }
-
- data.length = n = index4;
- filters.truncate(index4);
- triggerOnChange('dataRemoved');
- }
-
- function maskForDimensions(dimensions) {
- var n,
- d,
- len,
- id,
- mask = Array(filters.subarrays);
- for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
- for (d = 0, len = dimensions.length; d < len; d++) {
- // The top bits of the ID are the subarray offset and the lower bits are the bit
- // offset of the "one" mask.
- id = dimensions[d].id();
- mask[id >> 7] &= ~(0x1 << (id & 0x3f));
- }
- return mask;
- }
-
- // Return true if the data element at index i is filtered IN.
- // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
- function isElementFiltered(i, ignore_dimensions) {
- var mask = maskForDimensions(ignore_dimensions || []);
- return filters.zeroExceptMask(i,mask);
- }
-
- // Adds a new dimension with the specified value accessor function.
- function dimension(value, iterable) {
-
- if (typeof value === 'string') {
- var accessorPath = value;
- value = function(d) { return result(d, accessorPath); };
- }
-
- var dimension = {
- filter: filter,
- filterExact: filterExact,
- filterRange: filterRange,
- filterFunction: filterFunction,
- filterAll: filterAll,
- currentFilter: currentFilter,
- hasCurrentFilter: hasCurrentFilter,
- top: top,
- bottom: bottom,
- group: group,
- groupAll: groupAll,
- dispose: dispose,
- remove: dispose, // for backwards-compatibility
- accessor: value,
- id: function() { return id; }
- };
-
- var one, // lowest unset bit as mask, e.g., 00001000
- zero, // inverted one, e.g., 11110111
- offset, // offset into the filters arrays
- id, // unique ID for this dimension (reused when dimensions are disposed)
- values, // sorted, cached array
- index, // maps sorted value index -> record index (in data)
- newValues, // temporary array storing newly-added values
- newIndex, // temporary array storing newly-added index
- iterablesIndexCount,
- iterablesIndexFilterStatus,
- iterablesEmptyRows = [],
- sortRange = function(n) {
- return cr_range(n).sort(function(A, B) {
- var a = newValues[A], b = newValues[B];
- return a < b ? -1 : a > b ? 1 : A - B;
- });
- },
- refilter = xfilterFilter.filterAll, // for recomputing filter
- refilterFunction, // the custom filter function in use
- filterValue, // the value used for filtering (value, array, function or undefined)
- filterValuePresent, // true if filterValue contains something
- indexListeners = [], // when data is added
- dimensionGroups = [],
- lo0 = 0,
- hi0 = 0,
- t = 0,
- k;
-
- // Updating a dimension is a two-stage process. First, we must update the
- // associated filters for the newly-added records. Once all dimensions have
- // updated their filters, the groups are notified to update.
- dataListeners.unshift(preAdd);
- dataListeners.push(postAdd);
-
- removeDataListeners.push(removeData);
-
- // Add a new dimension in the filter bitmap and store the offset and bitmask.
- var tmp = filters.add();
- offset = tmp.offset;
- one = tmp.one;
- zero = ~one;
-
- // Create a unique ID for the dimension
- // IDs will be re-used if dimensions are disposed.
- // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
- // bit offset of the set bit in the dimension's "one" mask.
- id = (offset << 7) | (Math.log(one) / Math.log(2));
-
- preAdd(data, 0, n);
- postAdd(data, 0, n);
-
- // Incorporates the specified new records into this dimension.
- // This function is responsible for updating filters, values, and index.
- function preAdd(newData, n0, n1) {
- var newIterablesIndexCount,
- newIterablesIndexFilterStatus;
-
- if (iterable){
- // Count all the values
- t = 0;
- j = 0;
- k = [];
-
- for (var i0 = 0; i0 < newData.length; i0++) {
- for(j = 0, k = value(newData[i0]); j < k.length; j++) {
- t++;
- }
- }
-
- newValues = [];
- newIterablesIndexCount = cr_range(newData.length);
- newIterablesIndexFilterStatus = cr_index(t,1);
- var unsortedIndex = cr_range(t);
-
- for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
- k = value(newData[index1]);
- //
- if(!k.length){
- newIterablesIndexCount[index1] = 0;
- iterablesEmptyRows.push(index1 + n0);
- continue;
- }
- newIterablesIndexCount[index1] = k.length;
- for (j = 0; j < k.length; j++) {
- newValues.push(k[j]);
- unsortedIndex[l] = index1;
- l++;
- }
- }
-
- // Create the Sort map used to sort both the values and the valueToData indices
- var sortMap = sortRange(t);
-
- // Use the sortMap to sort the newValues
- newValues = permute(newValues, sortMap);
-
-
- // Use the sortMap to sort the unsortedIndex map
- // newIndex should be a map of sortedValue -> crossfilterData
- newIndex = permute(unsortedIndex, sortMap);
-
- } else {
- // Permute new values into natural order using a standard sorted index.
- newValues = newData.map(value);
- newIndex = sortRange(n1);
- newValues = permute(newValues, newIndex);
- }
-
- // Bisect newValues to determine which new records are selected.
- var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
-
- var index2, index3, index4;
- if(iterable) {
- n1 = t;
- if (refilterFunction) {
- for (index2 = 0; index2 < n1; ++index2) {
- if (!refilterFunction(newValues[index2], index2)) {
- if(--newIterablesIndexCount[newIndex[index2]] === 0) {
- filters[offset][newIndex[index2] + n0] |= one;
- }
- newIterablesIndexFilterStatus[index2] = 1;
- }
- }
- } else {
- for (index3 = 0; index3 < lo1; ++index3) {
- if(--newIterablesIndexCount[newIndex[index3]] === 0) {
- filters[offset][newIndex[index3] + n0] |= one;
- }
- newIterablesIndexFilterStatus[index3] = 1;
- }
- for (index4 = hi1; index4 < n1; ++index4) {
- if(--newIterablesIndexCount[newIndex[index4]] === 0) {
- filters[offset][newIndex[index4] + n0] |= one;
- }
- newIterablesIndexFilterStatus[index4] = 1;
- }
- }
- } else {
- if (refilterFunction) {
- for (index2 = 0; index2 < n1; ++index2) {
- if (!refilterFunction(newValues[index2], index2)) {
- filters[offset][newIndex[index2] + n0] |= one;
- }
- }
- } else {
- for (index3 = 0; index3 < lo1; ++index3) {
- filters[offset][newIndex[index3] + n0] |= one;
- }
- for (index4 = hi1; index4 < n1; ++index4) {
- filters[offset][newIndex[index4] + n0] |= one;
- }
- }
- }
-
- // If this dimension previously had no data, then we don't need to do the
- // more expensive merge operation; use the new values and index as-is.
- if (!n0) {
- values = newValues;
- index = newIndex;
- iterablesIndexCount = newIterablesIndexCount;
- iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
- lo0 = lo1;
- hi0 = hi1;
- return;
- }
-
-
-
- var oldValues = values,
- oldIndex = index,
- oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
- old_n0,
- i1 = 0;
-
- i0 = 0;
-
- if(iterable){
- old_n0 = n0;
- n0 = oldValues.length;
- n1 = t;
- }
-
- // Otherwise, create new arrays into which to merge new and old.
- values = iterable ? new Array(n0 + n1) : new Array(n);
- index = iterable ? new Array(n0 + n1) : cr_index(n, n);
- if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
-
- // Concatenate the newIterablesIndexCount onto the old one.
- if(iterable) {
- var oldiiclength = iterablesIndexCount.length;
- iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
- for(var j=0; j+oldiiclength < n; j++) {
- iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
- }
- }
-
- // Merge the old and new sorted values, and old and new index.
- var index5 = 0;
- for (; i0 < n0 && i1 < n1; ++index5) {
- if (oldValues[i0] < newValues[i1]) {
- values[index5] = oldValues[i0];
- if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
- index[index5] = oldIndex[i0++];
- } else {
- values[index5] = newValues[i1];
- if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
- index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
- }
- }
-
- // Add any remaining old values.
- for (; i0 < n0; ++i0, ++index5) {
- values[index5] = oldValues[i0];
- if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
- index[index5] = oldIndex[i0];
- }
-
- // Add any remaining new values.
- for (; i1 < n1; ++i1, ++index5) {
- values[index5] = newValues[i1];
- if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
- index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
- }
-
- // Bisect again to recompute lo0 and hi0.
- bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
- }
-
- // When all filters have updated, notify index listeners of the new values.
- function postAdd(newData, n0, n1) {
- indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
- newValues = newIndex = null;
- }
-
- function removeData(reIndex) {
- if (iterable) {
- for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
- if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
- iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
- i1++;
- }
- }
- iterablesEmptyRows.length = i1;
- for (i0 = 0, i1 = 0; i0 < n; i0++) {
- if (reIndex[i0] !== REMOVED_INDEX) {
- if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
- i1++;
- }
- }
- iterablesIndexCount = iterablesIndexCount.slice(0, i1);
- }
- // Rewrite our index, overwriting removed values
- var n0 = values.length;
- for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
- oldDataIndex = index[i];
- if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
- if (i !== j) values[j] = values[i];
- index[j] = reIndex[oldDataIndex];
- if (iterable) {
- iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
- }
- ++j;
- }
- }
- values.length = j;
- if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
- while (j < n0) index[j++] = 0;
-
- // Bisect again to recompute lo0 and hi0.
- var bounds = refilter(values);
- lo0 = bounds[0], hi0 = bounds[1];
- }
-
- // Updates the selected values based on the specified bounds [lo, hi].
- // This implementation is used by all the public filter methods.
- function filterIndexBounds(bounds) {
-
- var lo1 = bounds[0],
- hi1 = bounds[1];
-
- if (refilterFunction) {
- refilterFunction = null;
- filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
- lo0 = lo1;
- hi0 = hi1;
- return dimension;
- }
-
- var i,
- j,
- k,
- added = [],
- removed = [],
- valueIndexAdded = [],
- valueIndexRemoved = [];
-
-
- // Fast incremental update based on previous lo index.
- if (lo1 < lo0) {
- for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
- added.push(index[i]);
- valueIndexAdded.push(i);
- }
- } else if (lo1 > lo0) {
- for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
- removed.push(index[i]);
- valueIndexRemoved.push(i);
- }
- }
-
- // Fast incremental update based on previous hi index.
- if (hi1 > hi0) {
- for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
- added.push(index[i]);
- valueIndexAdded.push(i);
- }
- } else if (hi1 < hi0) {
- for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
- removed.push(index[i]);
- valueIndexRemoved.push(i);
- }
- }
-
- if(!iterable) {
- // Flip filters normally.
-
- for(i=0; i<added.length; i++) {
- filters[offset][added[i]] ^= one;
- }
-
- for(i=0; i<removed.length; i++) {
- filters[offset][removed[i]] ^= one;
- }
-
- } else {
- // For iterables, we need to figure out if the row has been completely removed vs partially included
- // Only count a row as added if it is not already being aggregated. Only count a row
- // as removed if the last element being aggregated is removed.
-
- var newAdded = [];
- var newRemoved = [];
- for (i = 0; i < added.length; i++) {
- iterablesIndexCount[added[i]]++;
- iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
- if(iterablesIndexCount[added[i]] === 1) {
- filters[offset][added[i]] ^= one;
- newAdded.push(added[i]);
- }
- }
- for (i = 0; i < removed.length; i++) {
- iterablesIndexCount[removed[i]]--;
- iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
- if(iterablesIndexCount[removed[i]] === 0) {
- filters[offset][removed[i]] ^= one;
- newRemoved.push(removed[i]);
- }
- }
-
- added = newAdded;
- removed = newRemoved;
-
- // Now handle empty rows.
- if(refilter === xfilterFilter.filterAll) {
- for(i = 0; i < iterablesEmptyRows.length; i++) {
- if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
- // Was not in the filter, so set the filter and add
- filters[offset][k] ^= one;
- added.push(k);
- }
- }
- } else {
- // filter in place - remove empty rows if necessary
- for(i = 0; i < iterablesEmptyRows.length; i++) {
- if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
- // Was in the filter, so set the filter and remove
- filters[offset][k] ^= one;
- removed.push(k);
- }
- }
- }
- }
-
- lo0 = lo1;
- hi0 = hi1;
- filterListeners.forEach(function(l) { l(one, offset, added, removed); });
- triggerOnChange('filtered');
- return dimension;
- }
-
- // Filters this dimension using the specified range, value, or null.
- // If the range is null, this is equivalent to filterAll.
- // If the range is an array, this is equivalent to filterRange.
- // Otherwise, this is equivalent to filterExact.
- function filter(range) {
- return range == null
- ? filterAll() : Array.isArray(range)
- ? filterRange(range) : typeof range === "function"
- ? filterFunction(range)
- : filterExact(range);
- }
-
- // Filters this dimension to select the exact value.
- function filterExact(value) {
- filterValue = value;
- filterValuePresent = true;
- return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
- }
-
- // Filters this dimension to select the specified range [lo, hi].
- // The lower bound is inclusive, and the upper bound is exclusive.
- function filterRange(range) {
- filterValue = range;
- filterValuePresent = true;
- return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
- }
-
- // Clears any filters on this dimension.
- function filterAll() {
- filterValue = undefined;
- filterValuePresent = false;
- return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
- }
-
- // Filters this dimension using an arbitrary function.
- function filterFunction(f) {
- filterValue = f;
- filterValuePresent = true;
-
- refilterFunction = f;
- refilter = xfilterFilter.filterAll;
-
- filterIndexFunction(f, false);
-
- var bounds = refilter(values);
- lo0 = bounds[0], hi0 = bounds[1];
-
- return dimension;
- }
-
- function filterIndexFunction(f, filterAll) {
- var i,
- k,
- x,
- added = [],
- removed = [],
- valueIndexAdded = [],
- valueIndexRemoved = [],
- indexLength = values.length;
-
- if(!iterable) {
- for (i = 0; i < indexLength; ++i) {
- if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
- if (x) added.push(k);
- else removed.push(k);
- }
- }
- }
-
- if(iterable) {
- for(i=0; i < indexLength; ++i) {
- if(f(values[i], i)) {
- added.push(index[i]);
- valueIndexAdded.push(i);
- } else {
- removed.push(index[i]);
- valueIndexRemoved.push(i);
- }
- }
- }
-
- if(!iterable) {
- for(i=0; i<added.length; i++) {
- if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
- }
-
- for(i=0; i<removed.length; i++) {
- if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
- }
- } else {
-
- var newAdded = [];
- var newRemoved = [];
- for (i = 0; i < added.length; i++) {
- // First check this particular value needs to be added
- if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
- iterablesIndexCount[added[i]]++;
- iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
- if(iterablesIndexCount[added[i]] === 1) {
- filters[offset][added[i]] ^= one;
- newAdded.push(added[i]);
- }
- }
- }
- for (i = 0; i < removed.length; i++) {
- // First check this particular value needs to be removed
- if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
- iterablesIndexCount[removed[i]]--;
- iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
- if(iterablesIndexCount[removed[i]] === 0) {
- filters[offset][removed[i]] ^= one;
- newRemoved.push(removed[i]);
- }
- }
- }
-
- added = newAdded;
- removed = newRemoved;
-
- // Now handle empty rows.
- if(filterAll) {
- for(i = 0; i < iterablesEmptyRows.length; i++) {
- if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
- // Was not in the filter, so set the filter and add
- filters[offset][k] ^= one;
- added.push(k);
- }
- }
- } else {
- // filter in place - remove empty rows if necessary
- for(i = 0; i < iterablesEmptyRows.length; i++) {
- if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
- // Was in the filter, so set the filter and remove
- filters[offset][k] ^= one;
- removed.push(k);
- }
- }
- }
- }
-
- filterListeners.forEach(function(l) { l(one, offset, added, removed); });
- triggerOnChange('filtered');
- }
-
- function currentFilter() {
- return filterValue;
- }
-
- function hasCurrentFilter() {
- return filterValuePresent;
- }
-
- // Returns the top K selected records based on this dimension's order.
- // Note: observes this dimension's filter, unlike group and groupAll.
- function top(k, top_offset) {
- var array = [],
- i = hi0,
- j,
- toSkip = 0;
-
- if(top_offset && top_offset > 0) toSkip = top_offset;
-
- while (--i >= lo0 && k > 0) {
- if (filters.zero(j = index[i])) {
- if(toSkip > 0) {
- //skip matching row
- --toSkip;
- } else {
- array.push(data[j]);
- --k;
- }
- }
- }
-
- if(iterable){
- for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
- // Add row with empty iterable column at the end
- if(filters.zero(j = iterablesEmptyRows[i])) {
- if(toSkip > 0) {
- //skip matching row
- --toSkip;
- } else {
- array.push(data[j]);
- --k;
- }
- }
- }
- }
-
- return array;
- }
-
- // Returns the bottom K selected records based on this dimension's order.
- // Note: observes this dimension's filter, unlike group and groupAll.
- function bottom(k, bottom_offset) {
- var array = [],
- i,
- j,
- toSkip = 0;
-
- if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
-
- if(iterable) {
- // Add row with empty iterable column at the top
- for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
- if(filters.zero(j = iterablesEmptyRows[i])) {
- if(toSkip > 0) {
- //skip matching row
- --toSkip;
- } else {
- array.push(data[j]);
- --k;
- }
- }
- }
- }
-
- i = lo0;
-
- while (i < hi0 && k > 0) {
- if (filters.zero(j = index[i])) {
- if(toSkip > 0) {
- //skip matching row
- --toSkip;
- } else {
- array.push(data[j]);
- --k;
- }
- }
- i++;
- }
-
- return array;
- }
-
- // Adds a new group to this dimension, using the specified key function.
- function group(key) {
- var group = {
- top: top,
- all: all,
- reduce: reduce,
- reduceCount: reduceCount,
- reduceSum: reduceSum,
- order: order,
- orderNatural: orderNatural,
- size: size,
- dispose: dispose,
- remove: dispose // for backwards-compatibility
- };
-
- // Ensure that this group will be removed when the dimension is removed.
- dimensionGroups.push(group);
-
- var groups, // array of {key, value}
- groupIndex, // object id ↦ group id
- groupWidth = 8,
- groupCapacity = capacity(groupWidth),
- k = 0, // cardinality
- select,
- heap,
- reduceAdd,
- reduceRemove,
- reduceInitial,
- update = cr_null,
- reset = cr_null,
- resetNeeded = true,
- groupAll = key === cr_null,
- n0old;
-
- if (arguments.length < 1) key = cr_identity;
-
- // The group listens to the crossfilter for when any dimension changes, so
- // that it can update the associated reduce values. It must also listen to
- // the parent dimension for when data is added, and compute new keys.
- filterListeners.push(update);
- indexListeners.push(add);
- removeDataListeners.push(removeData);
-
- // Incorporate any existing data into the grouping.
- add(values, index, 0, n);
-
- // Incorporates the specified new values into this group.
- // This function is responsible for updating groups and groupIndex.
- function add(newValues, newIndex, n0, n1) {
-
- if(iterable) {
- n0old = n0;
- n0 = values.length - newValues.length;
- n1 = newValues.length;
- }
-
- var oldGroups = groups,
- reIndex = iterable ? [] : cr_index(k, groupCapacity),
- add = reduceAdd,
- remove = reduceRemove,
- initial = reduceInitial,
- k0 = k, // old cardinality
- i0 = 0, // index of old group
- i1 = 0, // index of new record
- j, // object id
- g0, // old group
- x0, // old key
- x1, // new key
- g, // group to add
- x; // key of group to add
-
- // If a reset is needed, we don't need to update the reduce values.
- if (resetNeeded) add = initial = cr_null;
- if (resetNeeded) remove = initial = cr_null;
-
- // Reset the new groups (k is a lower bound).
- // Also, make sure that groupIndex exists and is long enough.
- groups = new Array(k), k = 0;
- if(iterable){
- groupIndex = k0 ? groupIndex : [];
- }
- else {
- groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
- }
-
-
- // Get the first old key (x0 of g0), if it exists.
- if (k0) x0 = (g0 = oldGroups[0]).key;
-
- // Find the first new key (x1), skipping NaN keys.
- while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
-
- // While new keys remain…
- while (i1 < n1) {
-
- // Determine the lesser of the two current keys; new and old.
- // If there are no old keys remaining, then always add the new key.
- if (g0 && x0 <= x1) {
- g = g0, x = x0;
-
- // Record the new index of the old group.
- reIndex[i0] = k;
-
- // Retrieve the next old key.
- g0 = oldGroups[++i0];
- if (g0) x0 = g0.key;
- } else {
- g = {key: x1, value: initial()}, x = x1;
- }
-
- // Add the lesser group.
- groups[k] = g;
-
- // Add any selected records belonging to the added group, while
- // advancing the new key and populating the associated group index.
-
- while (x1 <= x) {
- j = newIndex[i1] + (iterable ? n0old : n0);
-
-
- if(iterable){
- if(groupIndex[j]){
- groupIndex[j].push(k);
- }
- else {
- groupIndex[j] = [k];
- }
- }
- else {
- groupIndex[j] = k;
- }
-
- // Always add new values to groups. Only remove when not in filter.
- // This gives groups full information on data life-cycle.
- g.value = add(g.value, data[j], true);
- if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
- if (++i1 >= n1) break;
- x1 = key(newValues[i1]);
- }
-
- groupIncrement();
- }
-
- // Add any remaining old groups that were greater th1an all new keys.
- // No incremental reduce is needed; these groups have no new records.
- // Also record the new index of the old group.
- while (i0 < k0) {
- groups[reIndex[i0] = k] = oldGroups[i0++];
- groupIncrement();
- }
-
-
- // Fill in gaps with empty arrays where there may have been rows with empty iterables
- if(iterable){
- for (var index1 = 0; index1 < n; index1++) {
- if(!groupIndex[index1]){
- groupIndex[index1] = [];
- }
- }
- }
-
- // If we added any new groups before any old groups,
- // update the group index of all the old records.
- if(k > i0){
- if(iterable){
- for (i0 = 0; i0 < n0old; ++i0) {
- for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
- groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
- }
- }
- }
- else {
- for (i0 = 0; i0 < n0; ++i0) {
- groupIndex[i0] = reIndex[groupIndex[i0]];
- }
- }
- }
-
- // Modify the update and reset behavior based on the cardinality.
- // If the cardinality is less than or equal to one, then the groupIndex
- // is not needed. If the cardinality is zero, then there are no records
- // and therefore no groups to update or reset. Note that we also must
- // change the registered listener to point to the new method.
- j = filterListeners.indexOf(update);
- if (k > 1 || iterable) {
- update = updateMany;
- reset = resetMany;
- } else {
- if (!k && groupAll) {
- k = 1;
- groups = [{key: null, value: initial()}];
- }
- if (k === 1) {
- update = updateOne;
- reset = resetOne;
- } else {
- update = cr_null;
- reset = cr_null;
- }
- groupIndex = null;
- }
- filterListeners[j] = update;
-
- // Count the number of added groups,
- // and widen the group index as needed.
- function groupIncrement() {
- if(iterable){
- k++;
- return
- }
- if (++k === groupCapacity) {
- reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
- groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
- groupCapacity = capacity(groupWidth);
- }
- }
- }
-
- function removeData(reIndex) {
- if (k > 1 || iterable) {
- var oldK = k,
- oldGroups = groups,
- seenGroups = cr_index(oldK, oldK),
- i,
- i0,
- j;
-
- // Filter out non-matches by copying matching group index entries to
- // the beginning of the array.
- if (!iterable) {
- for (i = 0, j = 0; i < n; ++i) {
- if (reIndex[i] !== REMOVED_INDEX) {
- seenGroups[groupIndex[j] = groupIndex[i]] = 1;
- ++j;
- }
- }
- } else {
- for (i = 0, j = 0; i < n; ++i) {
- if (reIndex[i] !== REMOVED_INDEX) {
- groupIndex[j] = groupIndex[i];
- for (i0 = 0; i0 < groupIndex[j].length; i0++) {
- seenGroups[groupIndex[j][i0]] = 1;
- }
- ++j;
- }
- }
- groupIndex = groupIndex.slice(0, j);
- }
-
- // Reassemble groups including only those groups that were referred
- // to by matching group index entries. Note the new group index in
- // seenGroups.
- groups = [], k = 0;
- for (i = 0; i < oldK; ++i) {
- if (seenGroups[i]) {
- seenGroups[i] = k++;
- groups.push(oldGroups[i]);
- }
- }
-
- if (k > 1 || iterable) {
- // Reindex the group index using seenGroups to find the new index.
- if (!iterable) {
- for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
- } else {
- for (i = 0; i < j; ++i) {
- for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
- groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
- }
- }
- }
- } else {
- groupIndex = null;
- }
- filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
- ? (reset = resetMany, update = updateMany)
- : k === 1 ? (reset = resetOne, update = updateOne)
- : reset = update = cr_null;
- } else if (k === 1) {
- if (groupAll) return;
- for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
- groups = [], k = 0;
- filterListeners[filterListeners.indexOf(update)] =
- update = reset = cr_null;
- }
- }
-
- // Reduces the specified selected or deselected records.
- // This function is only used when the cardinality is greater than 1.
- // notFilter indicates a crossfilter.add/remove operation.
- function updateMany(filterOne, filterOffset, added, removed, notFilter) {
-
- if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
-
- var i,
- j,
- k,
- n,
- g;
-
- if(iterable){
- // Add the added values.
- for (i = 0, n = added.length; i < n; ++i) {
- if (filters.zeroExcept(k = added[i], offset, zero)) {
- for (j = 0; j < groupIndex[k].length; j++) {
- g = groups[groupIndex[k][j]];
- g.value = reduceAdd(g.value, data[k], false, j);
- }
- }
- }
-
- // Remove the removed values.
- for (i = 0, n = removed.length; i < n; ++i) {
- if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
- for (j = 0; j < groupIndex[k].length; j++) {
- g = groups[groupIndex[k][j]];
- g.value = reduceRemove(g.value, data[k], notFilter, j);
- }
- }
- }
- return;
- }
-
- // Add the added values.
- for (i = 0, n = added.length; i < n; ++i) {
- if (filters.zeroExcept(k = added[i], offset, zero)) {
- g = groups[groupIndex[k]];
- g.value = reduceAdd(g.value, data[k], false);
- }
- }
-
- // Remove the removed values.
- for (i = 0, n = removed.length; i < n; ++i) {
- if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
- g = groups[groupIndex[k]];
- g.value = reduceRemove(g.value, data[k], notFilter);
- }
- }
- }
-
- // Reduces the specified selected or deselected records.
- // This function is only used when the cardinality is 1.
- // notFilter indicates a crossfilter.add/remove operation.
- function updateOne(filterOne, filterOffset, added, removed, notFilter) {
- if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
-
- var i,
- k,
- n,
- g = groups[0];
-
- // Add the added values.
- for (i = 0, n = added.length; i < n; ++i) {
- if (filters.zeroExcept(k = added[i], offset, zero)) {
- g.value = reduceAdd(g.value, data[k], false);
- }
- }
-
- // Remove the removed values.
- for (i = 0, n = removed.length; i < n; ++i) {
- if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
- g.value = reduceRemove(g.value, data[k], notFilter);
- }
- }
- }
-
- // Recomputes the group reduce values from scratch.
- // This function is only used when the cardinality is greater than 1.
- function resetMany() {
- var i,
- j,
- g;
-
- // Reset all group values.
- for (i = 0; i < k; ++i) {
- groups[i].value = reduceInitial();
- }
-
- // We add all records and then remove filtered records so that reducers
- // can build an 'unfiltered' view even if there are already filters in
- // place on other dimensions.
- if(iterable){
- for (i = 0; i < n; ++i) {
- for (j = 0; j < groupIndex[i].length; j++) {
- g = groups[groupIndex[i][j]];
- g.value = reduceAdd(g.value, data[i], true, j);
- }
- }
- for (i = 0; i < n; ++i) {
- if (!filters.zeroExcept(i, offset, zero)) {
- for (j = 0; j < groupIndex[i].length; j++) {
- g = groups[groupIndex[i][j]];
- g.value = reduceRemove(g.value, data[i], false, j);
- }
- }
- }
- return;
- }
-
- for (i = 0; i < n; ++i) {
- g = groups[groupIndex[i]];
- g.value = reduceAdd(g.value, data[i], true);
- }
- for (i = 0; i < n; ++i) {
- if (!filters.zeroExcept(i, offset, zero)) {
- g = groups[groupIndex[i]];
- g.value = reduceRemove(g.value, data[i], false);
- }
- }
- }
-
- // Recomputes the group reduce values from scratch.
- // This function is only used when the cardinality is 1.
- function resetOne() {
- var i,
- g = groups[0];
-
- // Reset the singleton group values.
- g.value = reduceInitial();
-
- // We add all records and then remove filtered records so that reducers
- // can build an 'unfiltered' view even if there are already filters in
- // place on other dimensions.
- for (i = 0; i < n; ++i) {
- g.value = reduceAdd(g.value, data[i], true);
- }
-
- for (i = 0; i < n; ++i) {
- if (!filters.zeroExcept(i, offset, zero)) {
- g.value = reduceRemove(g.value, data[i], false);
- }
- }
- }
-
- // Returns the array of group values, in the dimension's natural order.
- function all() {
- if (resetNeeded) reset(), resetNeeded = false;
- return groups;
- }
-
- // Returns a new array containing the top K group values, in reduce order.
- function top(k) {
- var top = select(all(), 0, groups.length, k);
- return heap.sort(top, 0, top.length);
- }
-
- // Sets the reduce behavior for this group to use the specified functions.
- // This method lazily recomputes the reduce values, waiting until needed.
- function reduce(add, remove, initial) {
- reduceAdd = add;
- reduceRemove = remove;
- reduceInitial = initial;
- resetNeeded = true;
- return group;
- }
-
- // A convenience method for reducing by count.
- function reduceCount() {
- return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
- }
-
- // A convenience method for reducing by sum(value).
- function reduceSum(value) {
- return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
- }
-
- // Sets the reduce order, using the specified accessor.
- function order(value) {
- select = h.by(valueOf);
- heap = h$1.by(valueOf);
- function valueOf(d) { return value(d.value); }
- return group;
- }
-
- // A convenience method for natural ordering by reduce value.
- function orderNatural() {
- return order(cr_identity);
- }
-
- // Returns the cardinality of this group, irrespective of any filters.
- function size() {
- return k;
- }
-
- // Removes this group and associated event listeners.
- function dispose() {
- var i = filterListeners.indexOf(update);
- if (i >= 0) filterListeners.splice(i, 1);
- i = indexListeners.indexOf(add);
- if (i >= 0) indexListeners.splice(i, 1);
- i = removeDataListeners.indexOf(removeData);
- if (i >= 0) removeDataListeners.splice(i, 1);
- i = dimensionGroups.indexOf(group);
- if (i >= 0) dimensionGroups.splice(i, 1);
- return group;
- }
-
- return reduceCount().orderNatural();
- }
-
- // A convenience function for generating a singleton group.
- function groupAll() {
- var g = group(cr_null), all = g.all;
- delete g.all;
- delete g.top;
- delete g.order;
- delete g.orderNatural;
- delete g.size;
- g.value = function() { return all()[0].value; };
- return g;
- }
-
- // Removes this dimension and associated groups and event listeners.
- function dispose() {
- dimensionGroups.forEach(function(group) { group.dispose(); });
- var i = dataListeners.indexOf(preAdd);
- if (i >= 0) dataListeners.splice(i, 1);
- i = dataListeners.indexOf(postAdd);
- if (i >= 0) dataListeners.splice(i, 1);
- i = removeDataListeners.indexOf(removeData);
- if (i >= 0) removeDataListeners.splice(i, 1);
- filters.masks[offset] &= zero;
- return filterAll();
- }
-
- return dimension;
- }
-
- // A convenience method for groupAll on a dummy dimension.
- // This implementation can be optimized since it always has cardinality 1.
- function groupAll() {
- var group = {
- reduce: reduce,
- reduceCount: reduceCount,
- reduceSum: reduceSum,
- value: value,
- dispose: dispose,
- remove: dispose // for backwards-compatibility
- };
-
- var reduceValue,
- reduceAdd,
- reduceRemove,
- reduceInitial,
- resetNeeded = true;
-
- // The group listens to the crossfilter for when any dimension changes, so
- // that it can update the reduce value. It must also listen to the parent
- // dimension for when data is added.
- filterListeners.push(update);
- dataListeners.push(add);
-
- // For consistency; actually a no-op since resetNeeded is true.
- add(data, 0);
-
- // Incorporates the specified new values into this group.
- function add(newData, n0) {
- var i;
-
- if (resetNeeded) return;
-
- // Cycle through all the values.
- for (i = n0; i < n; ++i) {
-
- // Add all values all the time.
- reduceValue = reduceAdd(reduceValue, data[i], true);
-
- // Remove the value if filtered.
- if (!filters.zero(i)) {
- reduceValue = reduceRemove(reduceValue, data[i], false);
- }
- }
- }
-
- // Reduces the specified selected or deselected records.
- function update(filterOne, filterOffset, added, removed, notFilter) {
- var i,
- k,
- n;
-
- if (resetNeeded) return;
-
- // Add the added values.
- for (i = 0, n = added.length; i < n; ++i) {
- if (filters.zero(k = added[i])) {
- reduceValue = reduceAdd(reduceValue, data[k], notFilter);
- }
- }
-
- // Remove the removed values.
- for (i = 0, n = removed.length; i < n; ++i) {
- if (filters.only(k = removed[i], filterOffset, filterOne)) {
- reduceValue = reduceRemove(reduceValue, data[k], notFilter);
- }
- }
- }
-
- // Recomputes the group reduce value from scratch.
- function reset() {
- var i;
-
- reduceValue = reduceInitial();
-
- // Cycle through all the values.
- for (i = 0; i < n; ++i) {
-
- // Add all values all the time.
- reduceValue = reduceAdd(reduceValue, data[i], true);
-
- // Remove the value if it is filtered.
- if (!filters.zero(i)) {
- reduceValue = reduceRemove(reduceValue, data[i], false);
- }
- }
- }
-
- // Sets the reduce behavior for this group to use the specified functions.
- // This method lazily recomputes the reduce value, waiting until needed.
- function reduce(add, remove, initial) {
- reduceAdd = add;
- reduceRemove = remove;
- reduceInitial = initial;
- resetNeeded = true;
- return group;
- }
-
- // A convenience method for reducing by count.
- function reduceCount() {
- return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
- }
-
- // A convenience method for reducing by sum(value).
- function reduceSum(value) {
- return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
- }
-
- // Returns the computed reduce value.
- function value() {
- if (resetNeeded) reset(), resetNeeded = false;
- return reduceValue;
- }
-
- // Removes this group and associated event listeners.
- function dispose() {
- var i = filterListeners.indexOf(update);
- if (i >= 0) filterListeners.splice(i, 1);
- i = dataListeners.indexOf(add);
- if (i >= 0) dataListeners.splice(i, 1);
- return group;
- }
-
- return reduceCount();
- }
-
- // Returns the number of records in this crossfilter, irrespective of any filters.
- function size() {
- return n;
- }
-
- // Returns the raw row data contained in this crossfilter
- function all(){
- return data;
- }
-
- // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
- function allFiltered(ignore_dimensions) {
- var array = [],
- i = 0,
- mask = maskForDimensions(ignore_dimensions || []);
-
- for (i = 0; i < n; i++) {
- if (filters.zeroExceptMask(i, mask)) {
- array.push(data[i]);
- }
- }
-
- return array;
- }
-
- function onChange(cb){
- if(typeof cb !== 'function'){
- /* eslint no-console: 0 */
- console.warn('onChange callback parameter must be a function!');
- return;
- }
- callbacks.push(cb);
- return function(){
- callbacks.splice(callbacks.indexOf(cb), 1);
- };
- }
-
- function triggerOnChange(eventName){
- for (var i = 0; i < callbacks.length; i++) {
- callbacks[i](eventName);
- }
- }
-
- return arguments.length
- ? add(arguments[0])
- : crossfilter;
- }
-
- // Returns an array of size n, big enough to store ids up to m.
- function cr_index(n, m) {
- return (m < 0x101
- ? xfilterArray.array8 : m < 0x10001
- ? xfilterArray.array16
- : xfilterArray.array32)(n);
- }
-
- // Constructs a new array of size n, with sequential values from 0 to n - 1.
- function cr_range(n) {
- var range = cr_index(n, n);
- for (var i = -1; ++i < n;) range[i] = i;
- return range;
- }
-
- function capacity(w) {
- return w === 8
- ? 0x100 : w === 16
- ? 0x10000
- : 0x100000000;
- }
-
- var main = /*#__PURE__*/Object.freeze({
- __proto__: null,
- 'default': crossfilter$1
- });
-
- var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
-
- const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
- // -------------------------------------------------------------------
- // dx = multidimensional Crossfilter = Wrapper for crossfilter
- var dx = {
- indexFns : { id : function (d) { return d.id || "" } }
- , createIndexFn : function(indexFn, dim){
-
- var indexFns = {
- dim : function(d) { return d[dim] || "" }
- , dimId : function(d) { return d[dim + 'Id'] || "" }
- };
- if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
- if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
-
- indexFn = function(d){
- // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
- // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
- console.error('default generated indexFn on non existence of model property is dangerous.');
- indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
- dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
- // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
- // We therefore switch the function that will get called from next time onwards.
- return indexFn(d); //
- };
-
- return function(d){ return indexFn(d) }
- }
-
- , filter : function(filter, dim){
- // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
- if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
-
- var filterable = dim ? this.dims[dim] : this;
- // Filters are shared between master and dimension on data.
- if(!filterable.wkFilters.get(filter)) {
- filterable.wkFilters.set(filter, true);
- filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
- }
-
- // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
- if(filterable.dxFd){
- // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
- filterable.dxFd.filter( filterable.__filter );
- }
- filterable.dxF.filter(filterable.__filter);
-
- // If it does re-evaluate following cascade code is not required.
- // Cascade to all nested dimensions which are implicitly bound.
- // Object.keys(specs.dims).forEach((dim)=>{
- // this.dims[dim].dxF.filter( this.dims[dim].__filter )
- // })
-
- // Handle other custom bound Dimensions on this dimension.
- // Master and Data crossfilters are implicitly bound.
- // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
- // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
-
- }
- , filterAll : function(dim){
-
- var filterable = dim ? this.dims[dim] : this;
-
- if(filterable.dxFd){
- // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
- filterable.dxFd.filterAll();
- }
- filterable.dxF.filterAll( );
-
- // Cascade to all nested dimensions.
- // Object.keys(specs.dims).forEach((dim)=>{
- // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
- // dx.__createPairedDx(specs, dim);
- // })
- }
- , addFilter : function(filter, dim) {
- dim = dim || 'id';
- this.dims[dim].filters.push(filter);
- }
- , __initDim : function(oDim){
- var __filter = function(d){
- for(var f=0; f < oDim.filters.length; f++) {
- // Filter function will be called on the dimension.
- // PB : TODO accept any scope instead of only the dimension.
- if(!oDim.filters[f].call(oDim, d)) return false;
- }
- return true;
- };
- return oDim ? (()=>{
- oDim.wkFilters = new(WeakMap);
- oDim.filters = []; oDim.__filter = __filter;
- return oDim
- })()
- : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
- }
- , __createPairedDx : function(specs, dim, idxFn){
- var oDim = dim === 'id' ? specs : specs.dims[dim];
- idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
-
- oDim.dxU = specs.ndxU.dimension( idxFn );
- oDim.dxF = specs.ndxF.dimension( idxFn );
- }
- , create : function( specs ){
-
- specs.ndxF = crossfilter(specs.data);
- specs.ndxU = crossfilter(specs.data);
-
- // specs.dims ? null : specs.dims = { 'id' : null }
- // specs.dims['id'] = dx.__initDim(specs.dims['id'])
- dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
- dx.__createPairedDx(specs, 'id', dx.indexFns.id);
-
- specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
- specs.dims[dim].data ? (()=>{
- // We have some master data for this dimension.
- dx.create( specs.dims[dim] );
- // PB : TODO -- We should probably bind the an array dx's ...
- // Eg: An array of master dx's for a fact dx...
- // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
-
- })()
- : dx.__initDim(specs.dims[dim]);
-
- var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
- specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
- specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
-
- }) : null;
-
- specs.filter = this.filter;
- specs.filterAll = this.filterAll;
- return specs;
- }
- // , exclude : ( dxU, dxF, filterFn )=>{
- // // Excludes filtered from unfiltered.
- // var filterFn = null;
- // if(this.get('selected_doctor.id')) {
-
- // }
- // else {
-
- // var __inclusions = [];
- // var __exclusions = [];
-
- // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
- // // Per Doc
- // ndxFiltered.filterAll()
- // practitionersDimFiltered.filter(availablePractitioner.id);
- // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
- // if(freeTimes.length > 0) { /*available*/
- // __inclusions.push(availablePractitioner) }
- // else {
- // __exclusions.push(availablePractitioner)
- // }
-
- // })
-
- // filterFn = ()=> { return ((inclusions, exclusions)=>{
- // for(var f in filters) {
- // if(!filters[f]) return false;
- // }
- // return true;
- // })(__inclusions, __exclusions) } ;
-
- // practitionersDimFiltered.filter(filterFn);
- // }
- // return filterFn;
- // }
- };
-
- var dx_1 = dx;
-
- var commonmasks = {
- "bed":{
- "wards":{
- "Bone Marrow Transplantation Unit":{
- "title":"Bone Marrow Transplantation Unit",
- "v1wardId":"BMTU",
- "mask":"1"
- },
- "BRB (Birthing Room A-Big)":{
- "title":"BRB (Birthing Room A-Big)",
- "v1wardId":"BRB",
- "mask":"2"
- },
- "BRSP (Birthing Room-Special Private Ward)":{
- "title":"BRSP (Birthing Room-Special Private Ward)",
- "v1wardId":"BRSP",
- "mask":"4"
- },
- "CCU (Coronary Care Unit)":{
- "title":"CCU (Coronary Care Unit)",
- "v1wardId":"CCU",
- "mask":"8"
- },
- "Chemotherapy Unit":{
- "title":"Chemotherapy Unit",
- "v1wardId":"CHEMOTHERAPY",
- "mask":"16"
- },
- "High Intensive Care Unit":{
- "title":"High Intensive Care Unit",
- "v1wardId":"HICU",
- "mask":"32"
- },
- "ICU (Intensive Care Unit )":{
- "title":"ICU (Intensive Care Unit )",
- "v1wardId":"ICU",
- "mask":"64"
- },
- "Labour Room A":{
- "title":"Labour Room A",
- "v1wardId":"LDPRA",
- "mask":"128"
- },
- "Labour Room B":{
- "title":"Labour Room B",
- "v1wardId":"LDPRB",
- "mask":"256"
- },
- "LLC Covid Ward":{
- "title":"LLC Covid Ward",
- "v1wardId":"LLCCOVIDWARD",
- "mask":"512"
- },
- "Mortury":{
- "title":"Mortury",
- "v1wardId":"MORTURY",
- "mask":"1024"
- },
- "NCU (Neonetal Care Unit)":{
- "title":"NCU (Neonetal Care Unit)",
- "v1wardId":"NCU",
- "mask":"2048"
- },
- "Neonatal Intensive Care unit2":{
- "title":"Neonatal Intensive Care unit2",
- "v1wardId":"NICU2",
- "mask":"4096"
- },
- "Operation Theatre":{
- "title":"Operation Theatre",
- "v1wardId":"OT",
- "mask":"8192"
- },
- "Patient Parking Area":{
- "title":"Patient Parking Area",
- "v1wardId":"PARKING",
- "mask":"16384"
- },
- "PCU (Peadiatric Care Unit)":{
- "title":"PCU (Peadiatric Care Unit)",
- "v1wardId":"PCU",
- "mask":"32768"
- },
- "Private Ward":{
- "title":"Private Ward",
- "v1wardId":"PVTWARD",
- "mask":"65536"
- },
- "SPPVT (Special Private)":{
- "title":"SPPVT (Special Private)",
- "v1wardId":"SPLPVT",
- "mask":"131072"
- },
- "Special Private":{
- "title":"Special Private",
- "v1wardId":"SPPVT",
- "mask":"262144"
- },
- "Wing 01-Female":{
- "title":"Wing 01-Female",
- "v1wardId":"W1FEMALE",
- "mask":"524288"
- },
- "Wing 01-Maternity":{
- "title":"Wing 01-Maternity",
- "v1wardId":"W1MATERNITY",
- "mask":"1048576"
- },
- "Wing 01-SP":{
- "title":"Wing 01-SP",
- "v1wardId":"W1SEMIPRIVATE",
- "mask":"2097152"
- },
- "Wing 02-Female":{
- "title":"Wing 02-Female",
- "v1wardId":"WING02",
- "mask":"4194304"
- },
- "Wing 02-Paediatric":{
- "title":"Wing 02-Paediatric",
- "v1wardId":"WING02PED",
- "mask":"8388608"
- },
- "Wing 03":{
- "title":"Wing 03",
- "v1wardId":"WING03",
- "mask":"16777216"
- },
- "Wing 04":{
- "title":"Wing 04",
- "v1wardId":"WING04",
- "mask":"33554432"
- },
- "Wing 05":{
- "title":"Wing 05",
- "v1wardId":"WING05",
- "mask":"67108864"
- },
- "Wing 06":{
- "title":"Wing 06",
- "v1wardId":"WING06",
- "mask":"134217728"
- },
- "PVTWR (Private Wad)":{
- "title":"PVTWR (Private Wad)",
- "v1wardId":"WINGPC",
- "read":4,
- "write":4,
- "mask":"268435456"
- },
- "Inactive":{
- "title":"Inactive",
- "v1wardId":"Inactive",
- "mask":"536870912"
- }
- },
- "bedclassifications":{
- "Bassinet":{
- "v1bedclassificationId":"BNT",
- "title":"Bassinet",
- "category":"Ward Type",
- "read":4,
- "write":4,
- "mask":"1"
- },
- "Birthing Room":{
- "v1bedclassificationId":"BRB",
- "title":"Birthing Room",
- "category":"Ward Type",
- "mask":"2"
- },
- "Casualty":{
- "v1bedclassificationId":"CASUALTY",
- "title":"Casualty",
- "category":"Ward Type",
- "mask":"4"
- },
- "Coronary Care Unit":{
- "v1bedclassificationId":"CCU",
- "title":"Coronary Care Unit",
- "category":"Ward Type",
- "mask":"8"
- },
- "Chemotherapy":{
- "v1bedclassificationId":"CHEMO",
- "title":"Chemotherapy",
- "category":"Ward Type",
- "mask":"16"
- },
- "Day Care":{
- "v1bedclassificationId":"DAYCAR",
- "title":"Day Care",
- "category":"Ward Type",
- "mask":"32"
- },
- "Geriatric":{
- "v1bedclassificationId":"GER",
- "title":"Geriatric",
- "category":"Ward Type",
- "mask":"64"
- },
- "Labour Room":{
- "v1bedclassificationId":"LBR",
- "title":"Labour Room",
- "category":"Ward Type",
- "mask":"128"
- },
- "High Dependency Care Unit":{
- "v1bedclassificationId":"HDU",
- "title":"High Dependency Care Unit",
- "category":"Ward Type",
- "mask":"256"
- },
- "Intensive Care Unit":{
- "v1bedclassificationId":"Intensive Care Unit",
- "title":"Intensive Care Unit",
- "category":"Ward Type",
- "mask":"512"
- },
- "High Risk Labour Room":{
- "v1bedclassificationId":"HRLBR",
- "title":"High Risk Labour Room",
- "category":"Ward Type",
- "mask":"1024"
- },
- "High Intensive Care Unit":{
- "v1bedclassificationId":"HICU",
- "title":"High Intensive Care Unit",
- "category":"Ward Type",
- "mask":"2048"
- },
- "Neonatal Intensive Care Unit":{
- "v1bedclassificationId":"NCU",
- "title":"Neonatal Intensive Care Unit",
- "category":"Ward Type",
- "mask":"4096"
- },
- "Paediatric Intensive Care Unit":{
- "v1bedclassificationId":"PCU",
- "title":"Paediatric Intensive Care Unit",
- "category":"Ward Type",
- "mask":"8192"
- },
- "With TV":{
- "v1bedclassificationId":"WTV",
- "title":"With TV",
- "category":"Amenities",
- "mask":"16384"
- },
- "With AC":{
- "v1bedclassificationId":"WAC",
- "title":"With AC",
- "category":"Amenities",
- "mask":"32768"
- },
- "General Semi Private":{
- "v1bedclassificationId":"GSP",
- "title":"General Semi Private",
- "category":"Bill Category",
- "mask":"65536"
- },
- "General":{
- "v1bedclassificationId":"GEN",
- "title":"General",
- "category":"Bill Category",
- "mask":"131072"
- },
- "Private":{
- "v1bedclassificationId":"PVT",
- "title":"Private",
- "category":"Bill Category",
- "mask":"262144"
- },
- "Delux":{
- "v1bedclassificationId":"DLX",
- "title":"Delux",
- "category":"Bill Category",
- "mask":"524288"
- },
- "VIP":{
- "v1bedclassificationId":"VIP",
- "title":"VIP",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"1048576"
- },
- "Regular":{
- "v1bedclassificationId":"Regular",
- "title":"Regular",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"2097152"
- },
- "Premium Economy":{
- "v1bedclassificationId":"Premium Economy",
- "title":"Premium Economy",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"4194304"
- },
- "Economy":{
- "v1bedclassificationId":"Economy",
- "title":"Economy",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"8388608"
- },
- "Full room":{
- "v1bedclassificationId":"FULL",
- "title":"Full room",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"16777216"
- },
- "Triple Share":{
- "v1bedclassificationId":"TIO",
- "title":"Triple Share",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"33554432"
- },
- "Twin Share":{
- "v1bedclassificationId":"TWIN",
- "title":"Twin Share",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"67108864"
- },
- "Special Private":{
- "v1bedclassificationId":"SPPVT",
- "title":"Special Private",
- "category":"Bill Category",
- "mask":"134217728"
- },
- "Male":{
- "v1bedclassificationId":"MALE",
- "title":"Male",
- "read":4,
- "category":"Gender Type",
- "mask":"268435456"
- },
- "Female":{
- "v1bedclassificationId":"FEMALE",
- "title":"Female",
- "read":4,
- "category":"Gender Type",
- "mask":"536870912"
- },
- "Other":{
- "v1bedclassificationId":"OTHGEN",
- "title":"Other",
- "read":4,
- "category":"Gender Type",
- "mask":"1073741824"
- },
- "Adult":{
- "v1bedclassificationId":"ADLT",
- "title":"Adult",
- "category":"Age Based",
- "mask":"2147483648"
- },
- "Paediatric":{
- "v1bedclassificationId":"PAD",
- "title":"Paediatric",
- "category":"Age Based",
- "mask":"4294967296"
- },
- "Neonatal":{
- "v1bedclassificationId":"NEO",
- "title":"Neonatal",
- "category":"Age Based",
- "mask":"8589934592"
- },
- "Admissible Bed":{
- "v1bedclassificationId":"ADM",
- "title":"Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"17179869184"
- },
- "Non Admissible Bed":{
- "v1bedclassificationId":"NAADM",
- "title":"Non Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"34359738368"
- },
- "Limited Admissible Bed":{
- "v1bedclassificationId":"LMADM",
- "title":"Limited Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"68719476736"
- },
- "Infected":{
- "v1bedclassificationId":"INFECTED",
- "title":"Infected",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"137438953472"
- },
- "Clean":{
- "v1bedclassificationId":"CLEAN",
- "title":"Clean",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"274877906944"
- },
- "Isolation":{
- "v1bedclassificationId":"ISOLATION",
- "title":"Isolation",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"549755813888"
- },
- "Ward":{
- "v1bedclassificationId":"Ward",
- "title":"Ward",
- "category":"Uncategorized",
- "read":4,
- "write":4,
- "mask":"1099511627776"
- },
- "ICU":{
- "v1bedclassificationId":"ICU",
- "title":"ICU",
- "category":"Uncategorized",
- "read":4,
- "write":4,
- "mask":"2199023255552"
- },
- "Inactive":{
- "title":"Inactive",
- "v1bedclassificationId":"Inactive",
- "read":4,
- "write":4,
- "mask":"4398046511104"
- }
- },
- "bedoccupancyclassifications":{
- "Bassinet":{
- "v1bedclassificationId":"BNT",
- "title":"Bassinet",
- "category":"Ward Type",
- "read":4,
- "write":4,
- "mask":"1"
- },
- "Birthing Room":{
- "v1bedclassificationId":"BRB",
- "title":"Birthing Room",
- "category":"Ward Type",
- "mask":"2"
- },
- "Casualty":{
- "v1bedclassificationId":"CASUALTY",
- "title":"Casualty",
- "category":"Ward Type",
- "mask":"4"
- },
- "Coronary Care Unit":{
- "v1bedclassificationId":"CCU",
- "title":"Coronary Care Unit",
- "category":"Ward Type",
- "mask":"8"
- },
- "Chemotherapy":{
- "v1bedclassificationId":"CHEMO",
- "title":"Chemotherapy",
- "category":"Ward Type",
- "mask":"16"
- },
- "Day Care":{
- "v1bedclassificationId":"DAYCAR",
- "title":"Day Care",
- "category":"Ward Type",
- "mask":"32"
- },
- "Geriatric":{
- "v1bedclassificationId":"GER",
- "title":"Geriatric",
- "category":"Ward Type",
- "mask":"64"
- },
- "Labour Room":{
- "v1bedclassificationId":"LBR",
- "title":"Labour Room",
- "category":"Ward Type",
- "mask":"128"
- },
- "High Dependency Care Unit":{
- "v1bedclassificationId":"HDU",
- "title":"High Dependency Care Unit",
- "category":"Ward Type",
- "mask":"256"
- },
- "Intensive Care Unit":{
- "v1bedclassificationId":"Intensive Care Unit",
- "title":"Intensive Care Unit",
- "category":"Ward Type",
- "mask":"512"
- },
- "High Risk Labour Room":{
- "v1bedclassificationId":"HRLBR",
- "title":"High Risk Labour Room",
- "category":"Ward Type",
- "mask":"1024"
- },
- "High Intensive Care Unit":{
- "v1bedclassificationId":"HICU",
- "title":"High Intensive Care Unit",
- "category":"Ward Type",
- "mask":"2048"
- },
- "Neonatal Intensive Care Unit":{
- "v1bedclassificationId":"NCU",
- "title":"Neonatal Intensive Care Unit",
- "category":"Ward Type",
- "mask":"4096"
- },
- "Paediatric Intensive Care Unit":{
- "v1bedclassificationId":"PCU",
- "title":"Paediatric Intensive Care Unit",
- "category":"Ward Type",
- "mask":"8192"
- },
- "With TV":{
- "v1bedclassificationId":"WTV",
- "title":"With TV",
- "category":"Amenities",
- "mask":"16384"
- },
- "With AC":{
- "v1bedclassificationId":"WAC",
- "title":"With AC",
- "category":"Amenities",
- "mask":"32768"
- },
- "General Semi Private":{
- "v1bedclassificationId":"GSP",
- "title":"General Semi Private",
- "category":"Bill Category",
- "mask":"65536"
- },
- "General":{
- "v1bedclassificationId":"GEN",
- "title":"General",
- "category":"Bill Category",
- "mask":"131072"
- },
- "Private":{
- "v1bedclassificationId":"PVT",
- "title":"Private",
- "category":"Bill Category",
- "mask":"262144"
- },
- "Delux":{
- "v1bedclassificationId":"DLX",
- "title":"Delux",
- "category":"Bill Category",
- "mask":"524288"
- },
- "VIP":{
- "v1bedclassificationId":"VIP",
- "title":"VIP",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"1048576"
- },
- "Regular":{
- "v1bedclassificationId":"Regular",
- "title":"Regular",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"2097152"
- },
- "Premium Economy":{
- "v1bedclassificationId":"Premium Economy",
- "title":"Premium Economy",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"4194304"
- },
- "Economy":{
- "v1bedclassificationId":"Economy",
- "title":"Economy",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"8388608"
- },
- "Full room":{
- "v1bedclassificationId":"FULL",
- "title":"Full room",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"16777216"
- },
- "Triple Share":{
- "v1bedclassificationId":"TIO",
- "title":"Triple Share",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"33554432"
- },
- "Twin Share":{
- "v1bedclassificationId":"TWIN",
- "title":"Twin Share",
- "category":"Bed Type",
- "read":4,
- "write":4,
- "mask":"67108864"
- },
- "Special Private":{
- "v1bedclassificationId":"SPPVT",
- "title":"Special Private",
- "category":"Bill Category",
- "mask":"134217728"
- },
- "Male":{
- "v1bedclassificationId":"MALE",
- "title":"Male",
- "read":4,
- "category":"Gender Type",
- "mask":"268435456"
- },
- "Female":{
- "v1bedclassificationId":"FEMALE",
- "title":"Female",
- "read":4,
- "category":"Gender Type",
- "mask":"536870912"
- },
- "Other":{
- "v1bedclassificationId":"OTHGEN",
- "title":"Other",
- "read":4,
- "category":"Gender Type",
- "mask":"1073741824"
- },
- "Adult":{
- "v1bedclassificationId":"ADLT",
- "title":"Adult",
- "category":"Age Based",
- "mask":"2147483648"
- },
- "Paediatric":{
- "v1bedclassificationId":"PAD",
- "title":"Paediatric",
- "category":"Age Based",
- "mask":"4294967296"
- },
- "Neonatal":{
- "v1bedclassificationId":"NEO",
- "title":"Neonatal",
- "category":"Age Based",
- "mask":"8589934592"
- },
- "Admissible Bed":{
- "v1bedclassificationId":"ADM",
- "title":"Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"17179869184"
- },
- "Non Admissible Bed":{
- "v1bedclassificationId":"NAADM",
- "title":"Non Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"34359738368"
- },
- "Limited Admissible Bed":{
- "v1bedclassificationId":"LMADM",
- "title":"Limited Admissible Bed",
- "category":"Admissible Category",
- "read":4,
- "write":4,
- "mask":"68719476736"
- },
- "Infected":{
- "v1bedclassificationId":"INFECTED",
- "title":"Infected",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"137438953472"
- },
- "Clean":{
- "v1bedclassificationId":"CLEAN",
- "title":"Clean",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"274877906944"
- },
- "Isolation":{
- "v1bedclassificationId":"ISOLATION",
- "title":"Isolation",
- "category":"Clinical",
- "read":8,
- "write":8,
- "mask":"549755813888"
- },
- "Ward":{
- "v1bedclassificationId":"Ward",
- "title":"Ward",
- "category":"Uncategorized",
- "read":4,
- "write":4,
- "mask":"1099511627776"
- },
- "ICU":{
- "v1bedclassificationId":"ICU",
- "title":"ICU",
- "category":"Uncategorized",
- "read":4,
- "write":4,
- "mask":"2199023255552"
- },
- "Inactive":{
- "title":"Inactive",
- "v1bedclassificationId":"Inactive",
- "read":4,
- "write":4,
- "mask":"4398046511104"
- }
- }
- },
- "dentalmr":{
- "habits":{
- "Chewing":{
- "title":"Chewing",
- "mask":"1"
- },
- "Smoking":{
- "title":"Smoking",
- "mask":"2"
- },
- "Alchohol":{
- "title":"Alchohol",
- "mask":"4"
- },
- "Other":{
- "title":"Other",
- "mask":"8"
- }
- },
- "oralhygienestatuses":{
- "Calculus":{
- "title":"Calculus",
- "mask":"1"
- },
- "Strain":{
- "title":"Strain",
- "mask":"2"
- },
- "Debris":{
- "title":"Debris",
- "mask":"4"
- },
- "Sub-gingival-calculus":{
- "title":"Sub-gingival-calculus",
- "mask":"8"
- }
- },
- "periodontiums":{
- "Mobility":{
- "title":"Mobility",
- "mask":"1"
- },
- "GR":{
- "title":"GR",
- "mask":"2"
- },
- "PP":{
- "title":"PP",
- "mask":"4"
- },
- "BOP":{
- "title":"BOP",
- "mask":"8"
- },
- "Gingival-inflamation":{
- "title":"Gingival-inflamation",
- "mask":"16"
- }
- },
- "abbreviations":{
- "AA":{
- "title":"AA",
- "mask":"1"
- },
- "AS#":{
- "title":"AS#",
- "mask":"2"
- },
- "AP#":{
- "title":"AP#",
- "mask":"4"
- },
- "AV":{
- "title":"AV",
- "mask":"8"
- },
- "BoP":{
- "title":"BoP",
- "mask":"16"
- },
- "MA":{
- "title":"MA",
- "mask":"32"
- },
- "DA":{
- "title":"DA",
- "mask":"64"
- },
- "H":{
- "title":"H",
- "mask":"128"
- },
- "V":{
- "title":"V",
- "mask":"256"
- },
- "D1":{
- "title":"D1",
- "mask":"512"
- },
- "D2":{
- "title":"D2",
- "mask":"1024"
- },
- "D3":{
- "title":"D3",
- "mask":"2048"
- },
- "D4":{
- "title":"D4",
- "mask":"4096"
- },
- "C":{
- "title":"C",
- "mask":"8192"
- },
- "DT":{
- "title":"DT",
- "mask":"16384"
- },
- "CRF":{
- "title":"CRF",
- "mask":"32768"
- },
- "EX":{
- "title":"EX",
- "mask":"65536"
- },
- "EF":{
- "title":"EF",
- "mask":"131072"
- },
- "EDF":{
- "title":"EDF",
- "mask":"262144"
- },
- "EDP":{
- "title":"EDP",
- "mask":"524288"
- },
- "#EDP":{
- "title":"#EDP",
- "mask":"1048576"
- },
- "E":{
- "title":"E",
- "mask":"2097152"
- },
- "ED":{
- "title":"ED",
- "mask":"4194304"
- },
- "F1":{
- "title":"F1",
- "mask":"8388608"
- },
- "F2":{
- "title":"F2",
- "mask":"16777216"
- },
- "F3":{
- "title":"F3",
- "mask":"33554432"
- },
- "GH":{
- "title":"GH",
- "mask":"67108864"
- },
- "IMP":{
- "title":"IMP",
- "mask":"134217728"
- },
- "IL":{
- "title":"IL",
- "mask":"268435456"
- },
- "LL":{
- "title":"LL",
- "mask":"536870912"
- },
- "MO&DO":{
- "title":"MO&DO",
- "mask":"1073741824"
- },
- "AC":{
- "title":"AC",
- "mask":"2147483648"
- },
- "AT":{
- "title":"AT",
- "mask":"4294967296"
- },
- "BR":{
- "title":"BR",
- "mask":"8589934592"
- },
- "CR":{
- "title":"CR",
- "mask":"17179869184"
- },
- "#E":{
- "title":"#E",
- "mask":"34359738368"
- },
- "F":{
- "title":"F",
- "mask":"68719476736"
- },
- "#F":{
- "title":"#F",
- "mask":"137438953472"
- },
- "FD":{
- "title":"FD",
- "mask":"274877906944"
- },
- "GR":{
- "title":"GR",
- "mask":"549755813888"
- },
- "X":{
- "title":"X",
- "mask":"1099511627776"
- },
- "M1":{
- "title":"M1",
- "mask":"2199023255552"
- },
- "M2":{
- "title":"M2",
- "mask":"4398046511104"
- },
- "M3":{
- "title":"M3",
- "mask":"8796093022208"
- }
- },
- "teethposition":{
- "upperleft":{
- "title":"upperleft",
- "mask":"1"
- },
- "upperright":{
- "title":"upperright",
- "mask":"2"
- },
- "lowerleft":{
- "title":"lowerleft",
- "mask":"4"
- },
- "lowerright":{
- "title":"lowerright",
- "mask":"8"
- },
- "position1":{
- "title":"position1",
- "mask":"16"
- },
- "position2":{
- "title":"position2",
- "mask":"32"
- },
- "position3":{
- "title":"position3",
- "mask":"64"
- },
- "position4":{
- "title":"position4",
- "mask":"128"
- },
- "position5":{
- "title":"position5",
- "mask":"256"
- },
- "position6":{
- "title":"position6",
- "mask":"512"
- },
- "position7":{
- "title":"position7",
- "mask":"1024"
- },
- "position8":{
- "title":"position8",
- "mask":"2048"
- },
- "ischildteeth":{
- "title":"ischildteeth",
- "mask":"4096"
- }
- }
- },
- "item":{
- "ITEMCLASS":{
- "HIGHRISK":{
- "title":"HIGHRISK",
- "mask":"1"
- },
- "ANTIBIOTICUSAGE":{
- "title":"ANTIBIOTICUSAGE",
- "mask":"2"
- },
- "PURCHASABLE":{
- "title":"PURCHASABLE",
- "mask":"4"
- },
- "SERVICES":{
- "title":"SERVICES",
- "mask":"8"
- },
- "GOODS":{
- "title":"GOODS",
- "mask":"16"
- },
- "SALEABLE":{
- "title":"SALEABLE",
- "mask":"32"
- },
- "CONSUMABLE":{
- "title":"CONSUMABLE",
- "mask":"64"
- },
- "STOCKABLE":{
- "title":"STOCKABLE",
- "mask":"128"
- },
- "PHARMACEUTICALS":{
- "title":"PHARMACEUTICALS",
- "mask":"256"
- },
- "NONSTOCK":{
- "title":"NONSTOCK",
- "mask":"512"
- },
- "DISCOUNTS":{
- "title":"DISCOUNTS",
- "mask":"1024"
- },
- "GENERALITEMS":{
- "title":"GENERALITEMS",
- "mask":"2048"
- },
- "TERMS":{
- "title":"TERMS",
- "mask":"4096"
- },
- "SHEETITEMS":{
- "title":"SHEETITEMS",
- "mask":"8192"
- },
- "CAPITALITEM":{
- "title":"CAPITALITEM",
- "mask":"16384"
- },
- "PURCHASEINACTIVATED":{
- "title":"PURCHASABLE",
- "mask":"32768"
- },
- "SALEINACTIVATED":{
- "title":"PURCHASABLE",
- "mask":"65536"
- }
- }
- },
- "location":{
- "locationclass":{
- "Main Store":{
- "title":"Main Store",
- "mask":"1"
- },
- "SALEABLE":{
- "title":"SALEABLE",
- "mask":"2"
- },
- "CONSUMABLE":{
- "title":"CONSUMABLE",
- "mask":"4"
- },
- "STOCKABLE":{
- "title":"STOCKABLE",
- "mask":"8"
- },
- "PHARMACEUTICALS":{
- "title":"PHARMACEUTICALS",
- "mask":"16"
- },
- "GENERAL ITEMS":{
- "title":"GENERAL ITEMS",
- "mask":"32"
- }
- }
- },
- "user":{
- "roles":{
- "guest":{
- "title":"guest",
- "mask":"1"
- },
- "superadmin":{
- "title":"superadmin",
- "mask":"2"
- },
- "nurseadmin":{
- "title":"nurseadmin",
- "mask":"4"
- },
- "nurse":{
- "title":"nurse",
- "mask":"8"
- },
- "bedadmin":{
- "title":"bedadmin",
- "mask":"16"
- }
- }
- }
- };
- var m_common = commonmasks ;
-
- var helpers$1 = {
-
- islengthgreaterthan : function(value, maxlength){
- if(value && value.length < maxlength){
- return true;
- }
- else {
- return false;
- }
- }
- ,
- isnumbercheck : function (value) {
- if ( typeof(value) === 'string' || typeof(value) === 'number') {
- var re = new RegExp(/^[0-9]+$/);
- if (re.test(value) ) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false
- }
- }
- ,
- isintcheck : function (value) {
- if ( typeof(value) === 'string' || typeof(value) === 'number') {
- var re = new RegExp(/^[1-9]\d*$/);
- if (re.test(value) ) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false
- }
- }
- ,
- isguidcheck : function (value) {
- if ( typeof(value) === 'string' || typeof(value) === 'number') {
- // 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);
- 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');
- if (re.test(value) ) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false
- }
- }
- };
-
- var validationhelpers = helpers$1;
-
- try {
- var x = BigInt(0);
- }
- catch(e){
- console.warn('BigInt check failed. Falling back to Number');
- // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
- // Eg : Older Safari versions will not work
- // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
- BigInt = Number;
- }
-
- // -------------------------------
- // Command line option parsing
- // -------------------------------
- function cliargs$1(args, opts) {
- if (!opts) opts = {};
-
- var flags = { bools : {}, strings : {}, unknownFn: null };
-
- if (typeof opts['unknown'] === 'function') {
- flags.unknownFn = opts['unknown'];
- }
-
- if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
- flags.allBools = true;
- } else {
- [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
- flags.bools[key] = true;
- });
- }
-
- var aliases = {};
- Object.keys(opts.alias || {}).forEach(function (key) {
- aliases[key] = [].concat(opts.alias[key]);
- aliases[key].forEach(function (x) {
- aliases[x] = [key].concat(aliases[key].filter(function (y) {
- return x !== y;
- }));
- });
- });
-
- [].concat(opts.string).filter(Boolean).forEach(function (key) {
- flags.strings[key] = true;
- if (aliases[key]) {
- flags.strings[aliases[key]] = true;
- }
- });
-
- var defaults = opts['default'] || {};
-
- var argv = { _ : [] };
- Object.keys(flags.bools).forEach(function (key) {
- setArg(key, defaults[key] === undefined ? false : defaults[key]);
- });
-
- var notFlags = [];
-
- if (args.indexOf('--') !== -1) {
- notFlags = args.slice(args.indexOf('--')+1);
- args = args.slice(0, args.indexOf('--'));
- }
-
- function argDefined(key, arg) {
- return (flags.allBools && /^--[^=]+$/.test(arg)) ||
- flags.strings[key] || flags.bools[key] || aliases[key];
- }
-
- function setArg (key, val, arg) {
- if (arg && flags.unknownFn && !argDefined(key, arg)) {
- if (flags.unknownFn(arg) === false) return;
- }
-
- var value = !flags.strings[key] && isNumber(val)
- ? Number(val) : val
- ;
- setKey(argv, key.split('.'), value);
-
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), value);
- });
- }
-
- function setKey (obj, keys, value) {
- var o = obj;
- keys.slice(0,-1).forEach(function (key) {
- if (o[key] === undefined) o[key] = {};
- o = o[key];
- });
-
- var key = keys[keys.length - 1];
- if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
- o[key] = value;
- }
- else if (Array.isArray(o[key])) {
- o[key].push(value);
- }
- else {
- o[key] = [ o[key], value ];
- }
- }
-
- function aliasIsBoolean(key) {
- return aliases[key].some(function (x) {
- return flags.bools[x];
- });
- }
-
- for (var i = 0; i < args.length; i++) {
- var arg = args[i];
-
- if (/^--.+=/.test(arg)) {
- // Using [\s\S] instead of . because js doesn't support the
- // 'dotall' regex modifier. See:
- // http://stackoverflow.com/a/1068308/13216
- var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
- var key = m[1];
- var value = m[2];
- if (flags.bools[key]) {
- value = value !== 'false';
- }
- setArg(key, value, arg);
- }
- else if (/^--no-.+/.test(arg)) {
- var key = arg.match(/^--no-(.+)/)[1];
- setArg(key, false, arg);
- }
- else if (/^--.+/.test(arg)) {
- var key = arg.match(/^--(.+)/)[1];
- var next = args[i + 1];
- if (next !== undefined && !/^-/.test(next)
- && !flags.bools[key]
- && !flags.allBools
- && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, next, arg);
- i++;
- }
- else if (/^(true|false)$/.test(next)) {
- setArg(key, next === 'true', arg);
- i++;
- }
- else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- }
- else if (/^-[^-]+/.test(arg)) {
- var letters = arg.slice(1,-1).split('');
-
- var broken = false;
- for (var j = 0; j < letters.length; j++) {
- var next = arg.slice(j+2);
-
- if (next === '-') {
- setArg(letters[j], next, arg);
- continue;
- }
-
- if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
- setArg(letters[j], next.split('=')[1], arg);
- broken = true;
- break;
- }
-
- if (/[A-Za-z]/.test(letters[j])
- && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
- setArg(letters[j], next, arg);
- broken = true;
- break;
- }
-
- if (letters[j+1] && letters[j+1].match(/\W/)) {
- setArg(letters[j], arg.slice(j+2), arg);
- broken = true;
- break;
- }
- else {
- setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
- }
- }
-
- var key = arg.slice(-1)[0];
- if (!broken && key !== '-') {
- if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
- && !flags.bools[key]
- && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, args[i+1], arg);
- i++;
- }
- else if (args[i+1] && /true|false/.test(args[i+1])) {
- setArg(key, args[i+1] === 'true', arg);
- i++;
- }
- else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- }
- }
- else {
- if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
- argv._.push(
- flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
- );
- }
- if (opts.stopEarly) {
- argv._.push.apply(argv._, args.slice(i + 1));
- break;
- }
- }
- }
-
- Object.keys(defaults).forEach(function (key) {
- if (!hasKey(argv, key.split('.'))) {
- setKey(argv, key.split('.'), defaults[key]);
-
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), defaults[key]);
- });
- }
- });
-
- if (opts['--']) {
- argv['--'] = new Array();
- notFlags.forEach(function(key) {
- argv['--'].push(key);
- });
- }
- else {
- notFlags.forEach(function(key) {
- argv._.push(key);
- });
- }
-
- return argv;
- }
- /*
- Iterable task should return either truthy or false
- Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
- If all succeed , the return value will be true.
- If continueOnFailure is false, an execption is raised on any one failure
- */
- var any$1 = function(iterable, continueOnFailure) {
- var cancelsignal = Symbol();
- return iterable.reduce(
- function(p, tasq, i ,a) {
- var handleError = function(err, pVal){
- if(err !== cancelsignal) {
- // Cancel only once on first failure.
- console.log('Failed : ' + err.message + ' ' + JSON.stringify(pVal));
- console.dir(p);
- console.warn('Possible failure for task with result : ' + JSON.stringify(pVal));
- if(i>0 && a[i-1].info) console.dir(a[i-1].info);
- console.error('Error : ' + err.stack);
- console.error(a[i-1]);
- a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
- if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
- else return pVal;
- // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
- }
- };
-
- if(Promise.resolve(p) === p ) {
- if(i>0 && a[i-1].info) p.info = a[i-1].info;
- return p.then( function(pVal){
- // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
- // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
- // Failures are known for promises on reject.
- // In future if we support direct sync function execution with a result examination for failure
- // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
- // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
-
- // Truthy values are failures if obj has error=true.
- if(pVal && pVal.error) handleError(pVal, pVal);
-
- var trycall = function(tasq){
- try {
- var result = tasq(); // PB : TODO -- Handle scope for call
- if(tasq.resultHandler) return tasq.resultHandler(result)
- // if(!result) throw result; // Default failure detection for functions is falsy values.
- return result
- } catch (error) {
- console.error(error);
- console.error('Error : ' + error ? error.stack : 'No stack');
- if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
- }
- };
-
- var handleNext = function(){
- console.log('Task finished with result : ' + JSON.stringify(pVal));
- if(i>0 && a[i-1].info) console.dir(a[i-1].info);
- if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
- else if(!tasq) { console.log('Error : No task specified.'); return false;}
- return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
- };
-
- if(Promise.resolve(pVal) === pVal) {
- // Passed in function retured a promise. We still need to wait for it.
- pVal.then(function(pVal){ return handleNext(); });
- }
- else return handleNext()
-
- })['catch'](function(error) {
- if(error !== cancelsignal) {
- console.log(`E3 : i = ${i} `);
- if(error.result) console.error(error.result);
- console.error('Error : ' + (error.message || error.messages));
- console.error('Error : ' + error.stack);
- tasq ? console.log("tasq : " + tasq.toString()) : null;
- console.log('debugData 3-------------------------');
- // handleError()
- throw error
- }
- else throw cancelsignal;
- })
- }
- else if(!p) {
- handleError({ error : true, message : 'Failed without result' }, pVal);
- console.log("Bypass remaining on prior failure");
- return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
- }
- else return p; // A truthy value
- }
- , Promise.resolve(true)
- );
- };
-
- function hasKey (obj, keys) {
- var o = obj;
- keys.slice(0,-1).forEach(function (key) {
- o = (o[key] || {});
- });
-
- var key = keys[keys.length - 1];
- return key in o;
- }
-
- function isNumber (x) {
- if (typeof x === 'number') return true;
- if (/^0x[0-9a-f]+$/i.test(x)) return true;
- return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
- }
-
-
- // {{from}}, {{to}}
- // -- Extraday bounding range limits
- // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
-
- // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
- // -- Therefore the bounded range is the SINGULAR event
- // -- => {{start}} === {{from}} and {{end}} === {{to}}
-
- // {{recurring}} = {{pattern}}
- // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
- // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
- // -- A paterrn of all bits daysbits or datesbits turned on is all days.
- // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
- // Additional Time and frequence information will be found in
- // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
-
- // -- Irregular Time Patterns within a day are currently not supported but can be supported
- // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
- // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
- // -- 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.
-
- // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
-
- // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
- // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
- // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
-
- // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
- // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
- // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
- // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
- // -- for which day ? => at a minimum {{from}} should not be null
- // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
- // -- We only present a windowed set of events for the range being queried.
- // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
- // -- Usually an Intraday bounding range but can span multiple days.
- // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
- // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
- // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
- // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
- // -- {{recurring}} === 0
- // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
- // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
- // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
- // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
- // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
- // -- single events are better specified as {{from}} and {{to}}
- // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
- // -- {{every}} => intraday regular frequency of every
- // -- Eg : 2 hours
- // -- {{for}} => for a period of
- // -- Eg : 75 minutes
- // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
- // -- {{duration}} => with an event duration of
- // -- Eg : 15 minutes
- // -- equally distributed and occupying {{for}} without intermediate gaps
- // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
- // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
- // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
- // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
- // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
- // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
- // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
- // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
- //
- // -- Irregular intraday time frequencies. See discussion above.
-
- // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
- // The same effect can be achieved with a subdivision of granular time slots
- // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
-
- // {{available}}
- // -- 0 => Unavialability Pattern
- // -- 1 => Availability Pattern
-
- // -------------------------------------------------------------------
- // timeUtils
- const daysbits = 7;
- const datesbits = 31;
- const monthsbits = 12;
-
- // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
- // 7 + 31 + 12 = 50 bits which fits.
- const datebitOffset = daysbits;
- const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
-
- const monthsMask = 0b111111111111 * 2** (monthbitOffset);
- const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
- const daysMask = 0b1111111;
-
- var timeUtils = {
- // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
- toRecurringPattern( event ){
- var dayBitToSet = event.from.getDay(); // 0 based Index
- var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
- var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
-
- var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
- // PB : TODO -- loop through all matching masks until the end.
- return {
- from : event.from, to : event.to, recurring: recurring
- , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
- , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
- }
- }
- , getSkipFunction(r, boundedRange){
- var areMonthsSelected = monthsMask & r.recurring;
- var areDatesSelected = datesMask & r.recurring;
- var areDaysSelected = daysMask & r.recurring;
-
- if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
- console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
- return null;
- }
-
- var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
-
- // Returns how much to skip for next available value for a dimension.
- var reset = Symbol('reset');
- var stop = Symbol('stop');
- var skipFn = {
- create : (options)=>{
- var startFrom = options.startFrom;
- options.nBits;
- return {
- originOffset : null // From the origin.
- , getSkipGenerator : (selected)=>{
- var startOffset = null; // From position to start from.
-
- // var cycleEntryPoint = null;
- var nextCycleIndex = 0;
- var incrementCycle = [];
- var previous = 0;
- // Discover the cycle from the bitmask.
- for(var b = 0; b < nBits; b++) {
- if(selected & 1) {
- if(utils.js.isNull(originOffset)) this.originOffset = b;
- if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
- // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
- startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
- // cycleEntryPoint = b
- nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
- }
- incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
- previous = 1 + b; // Minimum incrment is always 1;
- }
- }
- // Due to the cyclical nature incrementCycle[0] has the increment to the second item
- // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
- incrementCycle.push(incrementCycle.splice(0,1));
- if(nextCycleIndex < 0) nextCycleIndex = 0;
- return function*(){
- var signal = false;
- signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
- var i = nextCycleIndex;
- for(;;){
- for(; i < incrementCycle.length; i++ ) {
- signal = yield incrementCycle[i];
- if(reset === signal) { signal = yield this.originOffset; break; }
- if(signal === stop || signal.done) return null;
- }
- i = 0;
- }
- }
- }
-
- // Generator for Irregular boundaries.
- , getNextDateGenerator(selection){
- var iterator = this.getSkipGenerator(selection);
-
- return function*(){
- var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
- if(nextPotentialDate.month() != potentialDate.getMonth()) {
- // Handle month boundary increments.
- nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
- }
- var potentialDate = nextPotentialDate;
- yield nextPotentialDate;
- }
- }
- // Cyclical Generator.
- , getNextGenerator(options, selection){
- this.getSkipGenerator(selection);
- var next = filter.from;
-
- return function*(){
- yield next = moment(next).add(dayIterator.next(), 'd');
- }
- }
- }
- }
- };
- var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
- var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
- var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
-
- if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
- else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
- else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
- else {
- if(!areMonthsSelected) {
- // Dates, Days are selected.
- return function*(){
-
- var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
- var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
-
- var potentialDay = null;
- var potentialDate = dateIterator.next(); // Irregular cycle end...
- if(isAnd) {
- // Both day and date shuld match.
- for(;;){
-
- for(; (potentialDay = dayIterator.next()) < potentialDate ;);
- // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
- // If both are integer skips we will have a LCM and therefore hit this condition.
- // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
- // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
- // In such cases we need to protect from an infinite loop that will never yield.
- // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
- if(potentialDay == potentialDate) {
- yield potentialDay;
- potentialDate = dateIterator.next();
- continue;
- }
- for(; (potentialDate = dateIterator.next()) < potentialDay;);
- }
- }
- else {
-
- for(;;){
-
- for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
- if(stop === (yield potentialDay)) return null;
- }
- if(potentialDay == potentialDate) {
- potentialDate = dateIterator.next();
- continue; // We need to yield in sorted sequence.
- }
- for(; (potentialDate = dateIterator.next()) < potentialDay;) {
- if(stop === (yield potentialDate)) return null;
- }
- }
- }
- }
- }
-
- }
- }
- , skipThisRecurrable : Symbol('skipThisRecurrable')
- , stopThisIterator : Symbol('stopThisIterator')
- , toEvents( r, boundedRange){
- if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
- ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
- }
- , jsstart : function(){
- return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
- }
- // Returns the whole event that is qualified even by a partial intersection.
- , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
-
-
- getEvent = getEvent || function(r, startOfDayFrom, start, end) {
- var event = Object.assign( {}, r);
- delete event.recurring;
-
-
- event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
- event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
- // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
- return event
- };
-
- var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
-
- // We need to start somewhere. We dont need an end as we keep generating perpetually.
- var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
- for(var gIdx=0; gIdx < recurrables.length; gIdx++){
- // Explode eachRecurrable to list of qualified events
- var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
- if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
-
- var startFrom = filter.from;
-
- if( eachRecurrable.from) {
- if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
- if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
- }
-
- var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
- var next = null;
-
- var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
- var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
-
- // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
- // which implies there is no need to test the rest of the recurring patterns until end of the boundary
- if(filter.to && eachRecurrable.to) {
- var stopAt = new Date(Min(filter.to, eachRecurrable.to));
- shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
- }
-
- var start = eachRecurrable.start || this.jsstart();
- var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
-
- var option = true;
- next = getEvent(eachRecurrable, startOfDayFrom, start, end);
-
- while( !shouldStop() ) {
- // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
- var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
- if(patternMatched) option = yield next;
- if(option === this.stopThisIterator) return null;
- // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
- startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
- next = getEvent(eachRecurrable, startOfDayFrom, start, end);
- }
- }
- }
-
- // PB : TODO -- Generator that returns a series of intersections events.
- // , recurringIntersectionsG : ()=>{}
-
- , isEvent : function(obj){
- return !obj.recurring
- }
- , isRecurringPattern : function(obj){
- return obj.recurring
- }
- , hasEventIntersection( e1Orr1, e2Orr2 ){
- return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
- : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
- : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
- : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
- }
-
- , __hasPatternIntersection( e1, p2 ){
-
- var areMonthsSelected = monthsMask & p2.recurring;
- var areDatesSelected = datesMask & p2.recurring;
- var areDaysSelected = daysMask & p2.recurring;
-
- // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
-
- if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
- console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
- return null; // Null patterns result in null intersection.
- }
-
- var isAnd = false;
- if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
- else {
- isAnd = p2.isAnd;
- }
-
- var p1 = this.toRecurringPattern(e1);
- var patternMatched = p1.recurring & p2.recurring;
- // 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.
- // And that is what is being queried... for any degree of usefulness.
- return ( isAnd ? p1.recurring === patternMatched : patternMatched );
- // returns truthy pattern that intersects.
- }
-
- , __willPatternsIntersect( p1, p2 ){
-
- if(p1.from && p2.to && p2.to <= p1.from) return false;
- if(p2.from && p1.to && p1.to <= p2.from) return false;
-
- var areMonthsSelected = monthsMask & p2.recurring;
- var areDatesSelected = datesMask & p2.recurring;
- var areDaysSelected = daysMask & p2.recurring;
-
- // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
-
- if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
- console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
- return null; // Null patterns result in null intersection.
- }
-
- var isAnd = false;
- if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
- else {
- isAnd = p2.isAnd;
- }
-
- var areP1MonthsSelected = monthsMask & p1.recurring;
- var areP1DatesSelected = datesMask & p1.recurring;
- var areP1DaysSelected = daysMask & p1.recurring;
-
- // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
-
- if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
- console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
- return null; // Null patterns result in null intersection.
- }
-
- var isP1And = false;
- if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
- else {
- isP1And = p1.isAnd;
- }
-
-
- if(isAnd && isP1And === isAnd ) {
- return p1.recurring === p2.recurring;
- }
- else if(isAnd) {
- matchtarget = p2.recurring ;
- }
- else if(isP1And ) {
- matchtarget = p1.recurring ;
- }
-
- var patternMatched = p1.recurring & p2.recurring;
- // 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.
- // And that is what is being queried... for any degree of usefulness.
-
- var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
-
- if(__patternMatched) {
- if(p1.start && p2.end && p2.end <= p1.start) return false;
- if(p2.start && p1.end && p1.end <= p2.start) return false;
-
- return true;
-
- }
- else {
- return false
- }
- // returns truthy pattern that intersects.
- }
- , __recurringHasIntersection(e1, r1){
-
- // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
- // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
- if(e1.from && r1.to && r1.to <= e1.from) return false;
- if(r1.from && e1.to && e1.to <= r1.from) return false;
- // Returns intersection or false.
- return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
- // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
-
- var startOfe1 = new Date( moment(e1.from).startOf('day') );
- var r1E = {
- from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
- , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
- };
- return utils.timeUtils.__hasEventIntersection(e1, r1E)
- })()
- : false
- }
-
- // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
- , __hasEventIntersection(e1, e2){
-
- // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
- if(!e1.from && !e1.to) return e2;
- if(!e2.from && !e2.to) return e1;
-
- var e1FromAnde2To = e1.from && e2.to;
- var e2FromAnde1To = e2.from && e1.to;
-
- var __aFrombTo = (a, b)=>{
- // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
- return (a.from >= b.to ? false
- : a.to && a.to > b.to || !a.to ?
- { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
- : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
- )
- };
-
- var result = e1FromAnde2To ? __aFrombTo(e1, e2)
- :( e2FromAnde1To ? __aFrombTo(e2, e1)
- : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
- e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
-
- return result
- }
-
- , exludeIntersection(freeTimes, e) {
- // Removal of unavilable times will split and splice into the same freeTimes array.
- for(var i =0; i < freeTimes.length; i++) {
- var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
- if(intersection) {
- // Edit freetime to correct for current collision.
- if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
- freeTimes.splice(i,1); i = i-1;
- }
- else {
- var right = Object.assign({}, freeTimes[i]);
- right.from = intersection.to;
- freeTimes[i].to = intersection.from;
- if( right.from < right.to ) {
- freeTimes.splice(++i,0, right); // Skip this we have already processed it.
- }
- }
- }
- }
- }
-
- , getFreeTimes( tRange, events, dimensions) {
- var freeTimes = [tRange];
- for(var eIdx = 0; eIdx < events.length; eIdx++) {
- var e = events[eIdx];
- timeUtils.exludeIntersection(freeTimes, e);
- if(freeTimes.length === 0) break;
- }
- // { result : freeTimes.length > 0, freeTimes : freeTimes}
- return freeTimes;
- }
-
- // PB : TODO -- Timeutils Test cases. Comment in production.
- , testAll(){
-
- // // Disjoint
- // var expected = false
- // var actual = null;
-
- expected = 2**4 + 2**(6+21) + 2**(5+31+6);
- actual = this.toRecurringPattern(
- { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
- if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
-
- // actual = this.__hasEventIntersection(
- // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
- // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
- // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
-
- // // Interleaved
- // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
- // actual = this.__hasEventIntersection(
- // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
- // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
- // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
-
- // // Subset
- // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
- // actual = this.__hasEventIntersection(
- // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
- // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
- // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
-
- // Null
-
- // Boundary Test Cases....
-
- var r1 = {
- end: new Date("1970-01-01T11:00:00.000Z")
- , every: null
- , from: new Date("2020-06-04T06:30:00.000Z")
- , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
- , migrationstate: 1
- , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
- , purpose: "Meeting"
- , recurring: 106
- , start: new Date("1970-01-01T06:30:00.000Z")
- , status: "SCHEDULED"
- , to: null
- };
- var e1 = {
- availability: false
- , end: null
- , every: null
- , for: null
- , from: new Date("2020-06-08T11:00:00.000Z")
- , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
- , migrationstate: 8
- , patientId: "271F4970-F173-4530-A894-68F520BF7945"
- , patientmob: "9944715969"
- , patientname: "SAMUEL RAJA DURAI J"
- , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
- , purpose: "Appointment"
- , start: null
- , status: "SCHEDULED"
- , to: new Date("2020-06-08T11:15:00.000Z")
- };
-
- this.hasEventIntersection(e1, r1);
- debugger
- // Iterators
- var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
- for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
- console.dir(e);
- }
-
- }
- };
-
- function promisify(ctx, asyncoperation, arraylikearguments) {
- var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
- return new Promise(function(resolve, reject) {
- asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
- if (err) return reject(arguments);
- resolve(arguments);
- });
- }).then((aArr)=>{
- originalcallback(...aArr);
- return aArr[1]
- }).catch(function(aArr){
- originalcallback(...aArr);
- throw aArr[0];
- });
- }
-
-
-
- var Tasq$1 = (function(){
-
- var __proto__ = {
- };
-
- var listeners = [];
-
- function Tasq(first, ...rest){
- first.info = utils.assign({ args : rest }, __proto__);
- return first
- }
- Tasq.create = Tasq;
- Tasq.addlistener = (l)=>{ listeners.push(l); };
- Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
- Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
- return Tasq
- })();
-
-
-
- var Traq$1 = (function(){
- var __proto__ = {};
-
- var log = {
- SUCCESS : []
- , FAILURE : []
- , SKIPPED : []
- };
-
- Traq$1 = function(){ return utils.assign({}, __proto__) };
- Traq$1.create = Traq$1;
- Traq$1.statuslog = statuslog;
- function statuslog(err, data){
- if(err) log.FAILURE.push( {err, data} );
- else log.SUCCESS.push(data);
- }
- Traq$1.notify = (event)=>{
- if(event.error) log.FAILURE.push( event );
- else log.SUCCESS.push(event);
- };
- Traq$1.finally = ()=>{
- console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
- console.log('Pass : ' + log.SUCCESS.length );
- console.log('Fail : ' + log.FAILURE.length);
- console.log('Skipped : ' + log.SKIPPED.length);
-
- console.log('FAILURES');
- console.log([JSON.stringify(log.FAILURE)]);
- };
- return Traq$1
- })();
-
-
- var tzoffset = 0;
- var utils = {
- commonmasks : m_common,
- escapeRegExp(string) {
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
- }
-
- , getTZOffsetMilliseconds : (()=>{
- var d = new Date();
- var t1 = d.toISOString().replace('Z','');
- var t2 = d.toISOString();
- tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
- return ()=>{ return tzoffset}
- })()
-
- , getLocalDateYYYYMMDD(date){
- var d = new Date();
- d.setTime(tzoffset + new Date(date).getTime());
- return d.toISOString().slice(0,10).replace(/-/g,"")
- }
-
- , assign(target /** , ...sources */) {
- return utils.assign_core(false, ...arguments)
- }
-
- , assign_caseless(target /** , ...sources */) {
- return utils.assign_core(true, ...arguments)
- }
-
- // assign
- , assign_core(ignorecase, target /** , ...sources */) {
- // Important use this instead of Object.assign.
- // Object.assign has several limitations.
- // 1) It doesn't skip intermediates if the final overriden value is already determined.
- // This implementation address this.
- // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
- // This implementation deep clones objects arrays and other types with some limitations.
- // 3) Does not merge but allways overrides.
- // Merges objects and arrays. Overides primitives.
- // Array merge is by default a concatenation.
- // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
- // 4) Does not retain non writable and configurable attributes.
- // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
- // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
- // Detects and avides ininite recursion.
-
- 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.
- var getNormalizedKey = ignorecase ? (key)=>key : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
-
- // We do a right to left iterations!
- // overrideKeys = true;
-
- // PB : Note -- IMPORTANT alreadyScanned has side effects..
- var alreadyScanned = (key)=>{
-
- Object.keys(target).forEach(k => {
- cpi[k.toLowerCase()] = k;
-
- if(cpi[k.toLowerCase()] !== k){
- Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
- delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
- }
- });
- alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
- // Its not necessary that we found it.
- cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
- return false;
- };
-
- // PB : Note -- IMPORTANT findEqualKey has side effects..
- var findEqualKey = (key) => {
- // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
- // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
- {
-
- if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
- var targetKey = cpi[key.toLowerCase()];
- return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
- };
-
- var hOP = Object.prototype.hasOwnProperty;
-
- var __assign = function(ignorecase, target /** , ...sources */) {
-
- if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
-
- // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
- // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
- var undef = 0;
- for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
- if(undef === arguments.length-1) return target;
-
- if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
- else {
- // PB : TODO -- Primitive targets cannot be preserved.
- // Target should be decided on first non primitive discovery.
- // Arrays don't work properly yet...
- // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
- // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
- if(utils.js.isPrimitive(target)) {
- target = {};
- } }
-
- for(var
- finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
- , overrideOrMerge = function (originalkey) {
- // Decision merge or override default to the following.
- // Primitives are overridden by non Primitives ( arrays or objects )
- // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
- // Objects assigned to Objects will be merged.
- // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
-
- // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
- // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
- // Currently assuming simple use cases at this point...
- // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
-
- var { targetKey, dL } = findEqualKey(originalkey);
- var dR = Object.getOwnPropertyDescriptor(this, originalkey);
-
- if(!dL) {
- // target did not have what it should be according to what was specifed. Lets check for other possibilities.
- dL = Object.getOwnPropertyDescriptor(target, originalkey);
- if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
- }
-
- if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
- var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
- if(utils.js.isPrimitive( valR )) {
- finalized[targetKey] = true;
-
- // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
- // Advantage is writable / configurable permissions are retained instead of simple assignment.
- Object.defineProperty( target, targetKey, dR );
- return
- }
- // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
- }
-
- // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
- if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
- // One or both of them is an accessor descriptor.
- // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
-
- var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
-
- // Accessor Descriptors cannot be examined due to possible side effects and possible differences
- // in the value and its type at the point of execution.
- // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
- // real program code needs the value !!!
- // There are 2 options
- // 1) we could do a decoupling here (at clone time) and capture the value.
- // 2) or we could postpone until run time evaluation.
- // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
- // Although decoupling is important and better done as early as possible the delayed value is more important.
- // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
- // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
- // -- Causing unexpected values specifically when the delayed override value from the source is expected.
- // Ideally the value that was set intermediately should supercede.
- // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
- // Original getter needs to access value in original context.
- // Setters need to be redirected to "cloned setter" in current context.
- var ctx = this;
- var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
- var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
- var valForSetter = null;
- dR.configurable;
-
- if(!utils.js.isUndefined( dL.writable )) {
- // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
- // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
- // These getters are still valid until such a first set happens until which time the valL remains
- // It is therefore possible to cache the valL and use it instead of target[key] at access time....
- var valL = target[targetKey];
- if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
- else { dChosen.get = function(){
- // In this case decoupling could happen on first access instead of first set.
- return utils.assign_core(ignorecase, valL, dRGetter.call(ctx))
- };
- }
- }
- else {
- // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
- dChosen.get = function(){ return utils.assign_core(ignorecase, dLGetter.call(target), dRGetter.call(ctx)) };
- }
-
- // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
- // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
- // but we need to do a one time read in any case wheter at clone time or at access time.
- dChosen.set = function(val) {
- // First time set on clone decouples
- dChosen.get = function() { return valForSetter};
- dChosen.set = function(val) { return valForSetter = val };
- dChosen.configurable = true;
- Object.defineProperty( target, targetKey, dChosen );
- return valForSetter = val
- };
- dChosen.configurable = true;
- Object.defineProperty( target, targetKey, dChosen );
- finalized[targetKey] = true;
- return
- }
-
- // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
- // Target is also a Data Descriptor. We can examine it as well to take a decision.
- var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
- if(utils.js.isPrimitive( valL )) {
- if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
- finalized[targetKey] = true;
- Object.defineProperty( target, targetKey, dR );
- }
- return
- }
- else {
- // Neither is Primitive.
- // console.log('Assign Iter...')
- if(valL === valR) { finalized[targetKey] = true; return true;}
- if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(ignorecase, valL, valR ); finalized[targetKey] = true; return;}
- if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
- if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
- if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
-
- // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
- // However if such bound functions are being used the intention must be retention of such linkage.
- if(utils.js.isFunction( valL ) && utils.js.isFunction( valR )) { target[targetKey] = valR; return;}
-
- // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
- // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
- // SAM : TODO dates are not getting merged.
- if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
-
- var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
- console.error(msg);
- throw msg;
- }
- }
- , appendmissing = function (originalkey) {
- var standardizedKey = getNormalizedKey(originalkey);
- if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
- }
- // Start from the rightmost and override or merge.
- , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
- , i = arguments.length-1-undef;
- 2 < i--;
- utils.js.isUndefined(arguments[i]) ? null :
- // Intermediate primitives are useless. Skipped coz the target has already been assigned.
- utils.js.isPrimitive(arguments[i]) ? null
- : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
- ){}
-
-
- return target;
- };
-
- return __assign(...arguments)
- }
-
-
- // PB : TODO -- Proper type checking.
- // , __TPL__typeHandlers : {
- // '[object String]' : defaultFn
- // , '[object Array]' : defaultFn
- // , '[object Object]' : defaultFn
- // , '[object Null]' : defaultFn
- // , '[object Undefined]' : defaultFn
- // , '[object Date]' : defaultFn
- // , '[object RegExp]' : defaultFn
- // , '[object Function]' : defaultFn
- // }
-
- // PB : TODO -- Proper type checking.
- // Javascript language utilities that should have been really in the language itself.
- , js : {
-
- typeInstances : [
- ""
- , 0
- , true
- , null
- , // undefined
- , []
- , {}
- , Symbol()
- , new Date()
- , /.*/
- , Promise.resolve(true)
- , function() {}
- , BigInt(0)
- ]
- , proxyable : []
- , nonproxyable : []
-
- , isString(x) {
- return Object.prototype.toString.call(x) === "[object String]"
- }
- , isNumber(x) {
- return Object.prototype.toString.call(x) === '[object Number]'
- }
- , isBoolean(x) {
- return Object.prototype.toString.call(x) === '[object Boolean]'
- }
- , isNull(x) {
- return Object.prototype.toString.call(x) === '[object Null]'
- }
- , isUndefined(x) {
- return Object.prototype.toString.call(x) === '[object Undefined]'
- }
- , isArray(x) {
- return Object.prototype.toString.call(x) === '[object Array]'
- }
- , isObject(x) {
- return Object.prototype.toString.call(x) === '[object Object]'
- }
- , isSymbol(x) {
- return Object.prototype.toString.call(x) === '[object Symbol]'
- }
- , isDate(x) {
- return Object.prototype.toString.call(x) === '[object Date]'
- }
- , isRegExp(x) {
- return Object.prototype.toString.call(x) === '[object RegExp]'
- }
- , isPromise(x) {
- return Promise.resolve(x) === x
- }
- , isPromiseOrFunction(o) {
- if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
- return false;
- }
- , isFunction(x) {
- return Object.prototype.toString.call(x) === '[object Function]'
- }
- , isBigInt(x) {
- return Object.prototype.toString.call(x) === '[object BigInt]'
- }
-
- , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
-
- // Grouping JS Types into 4 Groups
- // Primitives
- // -- boolean, String, Number
- // Arrays
- // Objects
- // Special
- // -- date, regexp, function ... and other unkown types
- , typeGroups() {
- return [
- '[Primitive]'
- , '[Null]'
- , '[Undefined]'
- , '[Symbol]'
- , '[Array]'
- , '[Object]'
- , '[Special]'
- ]
- }
-
- , typeGroup(x) {
- var tgMap = {
- '[object String]' : '[Primitive]'
- , '[object Number]' : '[Primitive]'
- , '[object Boolean]' : '[Primitive]'
- , '[object Null]' : '[Null]'
- , '[object Undefined]' : '[Undefined]'
- , '[object Symbol]' : '[Symbol]'
- , '[object BigInt]' : '[BigInt]'
-
- , '[object Array]' : '[Array]'
- , '[object Object]' : '[Object]'
- , '[object Date]' : '[Special]'
- , '[object RegExp]' : '[Special]'
- , '[object Function]' : '[Special]'
- , '[object Promise]' : '[Special]'
- };
- return tgMap[Object.prototype.toString.call(x)]
- }
-
- , getTypeInfo(x) {
-
- var typeMap = {
- '[object String]' : //__assign(typeInfo,
- { typeGroup : '[Primitive]', isString : true, isPrimitive : true
- , create : ()=>{return ""} }
- //)
- , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
- , create : ()=>{return 1}}
- , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
- , create : ()=>{return true}}
- , '[object Null]' : { typeGroup : '[Null]', isNull : true
- , create : ()=>{return null}}
- , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
- , create : ()=>{return }}
- , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
- , create : ()=>{return new Symbol()}}
- , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
- , create : ()=>{return new BigInt()}}
-
- , '[object Array]' : { typeGroup : '[Array]', isArray : true
- , create : ()=>{return []}}
- , '[object Object]' : { typeGroup : '[Object]', isObject : true
- , create : ()=>{return {}}}
- , '[object Date]' : { typeGroup : '[Special]', isDate : true
- , create : ()=>{return new Date}}
- , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
- , create : ()=>{return new RegExp}}
- , '[object Function]' : { typeGroup : '[Special]', isFunction : true
- , create : ()=>{return new Function}}
- , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
- , create : ()=>{ throw "Blank promise cannot be created."}}
- };
- return typeMap[Object.prototype.toString.call(x)]
- }
-
- , isPrimitive(x) {
- var xType = this.nativeType(x);
- return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
- xType === '[object BigInt]'
- }
-
- , isSpecial(x) {
- return !isArray(x) && !isObject(x) && !isPrimitive(x)
- }
-
- , nativeTypes() {
- return [
- // Primitives
- '[object String]'
- , '[object Number]'
- , '[object Boolean]'
- , '[object Null]'
- , '[object Undefined]'
- , '[object Symbol]'
- , '[object BigInt]'
-
- // Non Primitives.
- , '[object Array]'
- , '[object Object]'
- , '[object Date]'
- , '[object RegExp]'
- , '[object Function]'
- , '[object Promise]'
- ]
- }
-
- , nativeType(x) { return Object.prototype.toString.call(x) }
-
- }
-
- // Upsert for a hash ??
- , hashupsert : function(oA, oB){
- Object.keys(oA).forEach(( oAKey )=>{
- if(oB[oAKey]) {
- var distinct = new Set(oA[oAKey]);
- oB[oAKey].forEach((each)=>{
- distinct.add(each);
- });
- oA[oAKey] = Array.from(distinct);
- }
- });
- }
-
- // Upsert for an array.
- // Also the same as pushdistinct. Target is expected to have only one instance.
- , upsert(arr, val) {
- // 0 -- did nothing
- // 2 -- inserted
- // 3 -- updated
- // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
- var found = arr.find((element)=>{ return element === val});
- return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
- : (arr.push(val), 2) ;
- }
-
- // accumulate
- // o[toVectorPropName] which is an array
- // and o[propName] which is a string
- // into vectorTarget which is an array
- // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
-
- // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
- // 1 -- created target and inserted val
- // 2 -- didn't create target but inserted val
- // 3 -- didn't create target but updated val and also handled o[propName].
- , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
- identityEvaluator
- ){
- var created = 0;
-
- if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
- if(val === o[propName]) return; // Nothing to do.
-
- var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
- if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
- return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
-
- var vectorTarget = vectorTargetContainer[o["id"]];
-
- if(!vectorTarget) {
- created = 1;
- vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
- }
-
- if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
-
- var upsertResult = 0;
- if(!created && !utils.js.isUndefined(o[propName])) {
- if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
- upsertResult = utils.upsert(vectorTarget, o[propName]);
- }
- }
- upsertResult = utils.upsert(vectorTarget, val);
- return created ? created : upsertResult;
- }
-
- // async Utils
- , async : {
- all(list, task){
- var queueditems=[];
- list.forEach(function(v, i, a) {
- queueditems.push(task(v, i, a));
- });
- return Promise.all(queueditems)
- }
- }
-
-
- // PB : TODO -- Remove these.
- // , fsdb : require('./fsdb/fsdb')
- // , xlsx : require('./fsdb/xlsx')
- // , xlsxvalidator : require('./fsdb/xlsxvalidator')
-
- , timeUtils
- , dx: dx_1
- , cliargs: cliargs$1
- , any: any$1
- , promisify
- , moment
- , Tasq: Tasq$1
- , Traq: Traq$1
- , validationhelpers : validationhelpers
- };
-
- var utils_1 = utils;
-
- var naiveFallback = function () {
- if (typeof self === "object" && self) return self;
- if (typeof window === "object" && window) return window;
- throw new Error("Unable to resolve global `this`");
- };
-
-
- // https://mathiasbynens.be/notes/globalthis
- var globalThis_1 = (function () {
- if (this) return this;
-
- // Unexpected strict mode (may happen if e.g. bundled into ESM module)
-
- // Fallback to standard globalThis if available
- if (typeof globalThis === "object" && globalThis) return globalThis;
-
- // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
- // In all ES5+ engines global object inherits from Object.prototype
- // (if you approached one that doesn't please report)
- try {
-
- Object.prototype.__defineGetter__('__global__', function() {
- return this;
- });
- __global__.globalThis = __global__; // lolwat
-
- } catch (error) {
- // Unfortunate case of updates to Object.prototype being restricted
- // via preventExtensions, seal or freeze
- return naiveFallback();
- }
- try {
- // Safari case (window.__global__ works, but __global__ does not)
- if (!__global__) return naiveFallback();
- return __global__;
- } finally {
- delete Object.prototype.__global__;
- }
- })();
-
- // A selector based channels implementation as compared to a simple array.
- var channelMixin = (function() {
-
- // get channels that qualify for a selector.
- function getSubscriptions(selector) {
- console.dir(this.__channels);
- var filtered = this.__channels; // start with the world...
- // Selector is a simple list of tags.
- for(var select in selector) {
- if(!filtered[selector[select]]) {
- // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
- return []; // We are looking for all selectors therefore if even one fails we don't have anything.
- }
- filtered = filtered[selector[select]];
- }
-
- return filtered['__data']; // Flattened array
- }
-
- function addSubscription(selector, func, context) {
-
- var unfulfilled = selector.splice(0);
- var filtered = this.__channels; // start with the world...
- console.log(filtered);
- for(var select in unfulfilled) {
- if(!filtered[unfulfilled[select]]) {
- filtered[unfulfilled[select]] = { __data : [] };
- }
- filtered = filtered[unfulfilled[select]];
- unfulfilled = unfulfilled.splice(0,1);
- }
-
- // PB : TODO -- All accessor paths need to be indexed !
- // Will currently fail if not published and queried in the same order.
- filtered.__data.push({context: context, callback: func});
- }
-
- return function(){
- this.__channels = {};
- this.getSubscriptions = getSubscriptions;
- this.addSubscription = addSubscription;
- return this;
- }
- })();
-
- // Mediator pattern.
- var mediator = (function() {
-
- var __subscribe = function(selector, func, context) {
- var subscriptions = this.channels.getSubscriptions(selector);
-
- if(subscriptions.length < 1){
- this.channels.addSubscription(selector, func, context);
- }
-
- return this;
- };
-
- var __publish = function(selector) {
- console.log('publishing for selector ' + selector);
- var subscriptions = this.channels.getSubscriptions(selector);
- console.log(subscriptions);
- if(subscriptions.length < 1){ return; }
- var args = Array.prototype.slice.call(arguments, 1);
- for(i=0; i < subscriptions.length; i++) {
- subscription = subscriptions[i];
- subscription.callback.apply(subscription.context, args);
- }
- return this;
- };
-
- return function mediator() {
- var thisObj = this ? this : {};
- Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
- thisObj.publish = __publish;
- thisObj.subscribe = __subscribe;
- return thisObj;
- };
- })();
-
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
- // require the crypto API and do not support built-in fallback to lower quality random number
- // generators (like Math.random()).
- var getRandomValues;
- var rnds8 = new Uint8Array(16);
- function rng() {
- // lazy load so that environments that need to polyfill have a chance to do so
- if (!getRandomValues) {
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
- // find the complete implementation of crypto (msCrypto) on IE11.
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
-
- if (!getRandomValues) {
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
- }
- }
-
- return getRandomValues(rnds8);
- }
-
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
-
- function validate(uuid) {
- return typeof uuid === 'string' && REGEX.test(uuid);
- }
-
- /**
- * Convert array of 16 byte values to UUID string format of the form:
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
- */
-
- var byteToHex = [];
-
- for (var i$1 = 0; i$1 < 256; ++i$1) {
- byteToHex.push((i$1 + 0x100).toString(16).substr(1));
- }
-
- function stringify(arr) {
- var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- // Note: Be careful editing this code! It's been tuned for performance
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
- var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
- // of the following:
- // - One or more input array values don't map to a hex octet (leading to
- // "undefined" in the uuid)
- // - Invalid input values for the RFC `version` or `variant` fields
-
- if (!validate(uuid)) {
- throw TypeError('Stringified UUID is invalid');
- }
-
- return uuid;
- }
-
- //
- // Inspired by https://github.com/LiosK/UUID.js
- // and http://docs.python.org/library/uuid.html
-
- var _nodeId;
-
- var _clockseq; // Previous uuid creation time
-
-
- var _lastMSecs = 0;
- var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
-
- function v1(options, buf, offset) {
- var i = buf && offset || 0;
- var b = buf || new Array(16);
- options = options || {};
- var node = options.node || _nodeId;
- var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
- // specified. We do this lazily to minimize issues related to insufficient
- // system entropy. See #189
-
- if (node == null || clockseq == null) {
- var seedBytes = options.random || (options.rng || rng)();
-
- if (node == null) {
- // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
- node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
- }
-
- if (clockseq == null) {
- // Per 4.2.2, randomize (14 bit) clockseq
- clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
- }
- } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
- // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
- // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
- // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
-
-
- var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
- // cycle to simulate higher resolution clock
-
- var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
-
- var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
-
- if (dt < 0 && options.clockseq === undefined) {
- clockseq = clockseq + 1 & 0x3fff;
- } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
- // time interval
-
-
- if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
- nsecs = 0;
- } // Per 4.2.1.2 Throw error if too many uuids are requested
-
-
- if (nsecs >= 10000) {
- throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
- }
-
- _lastMSecs = msecs;
- _lastNSecs = nsecs;
- _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
-
- msecs += 12219292800000; // `time_low`
-
- var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
- b[i++] = tl >>> 24 & 0xff;
- b[i++] = tl >>> 16 & 0xff;
- b[i++] = tl >>> 8 & 0xff;
- b[i++] = tl & 0xff; // `time_mid`
-
- var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
- b[i++] = tmh >>> 8 & 0xff;
- b[i++] = tmh & 0xff; // `time_high_and_version`
-
- b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
-
- b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
-
- b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
-
- b[i++] = clockseq & 0xff; // `node`
-
- for (var n = 0; n < 6; ++n) {
- b[i + n] = node[n];
- }
-
- return buf || stringify(b);
- }
-
- function parse$1(uuid) {
- if (!validate(uuid)) {
- throw TypeError('Invalid UUID');
- }
-
- var v;
- var arr = new Uint8Array(16); // Parse ########-....-....-....-............
-
- arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
- arr[1] = v >>> 16 & 0xff;
- arr[2] = v >>> 8 & 0xff;
- arr[3] = v & 0xff; // Parse ........-####-....-....-............
-
- arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
- arr[5] = v & 0xff; // Parse ........-....-####-....-............
-
- arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
- arr[7] = v & 0xff; // Parse ........-....-....-####-............
-
- arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
- arr[9] = v & 0xff; // Parse ........-....-....-....-############
- // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
-
- arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
- arr[11] = v / 0x100000000 & 0xff;
- arr[12] = v >>> 24 & 0xff;
- arr[13] = v >>> 16 & 0xff;
- arr[14] = v >>> 8 & 0xff;
- arr[15] = v & 0xff;
- return arr;
- }
-
- function stringToBytes(str) {
- str = unescape(encodeURIComponent(str)); // UTF8 escape
-
- var bytes = [];
-
- for (var i = 0; i < str.length; ++i) {
- bytes.push(str.charCodeAt(i));
- }
-
- return bytes;
- }
-
- var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
- var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
- function v35 (name, version, hashfunc) {
- function generateUUID(value, namespace, buf, offset) {
- if (typeof value === 'string') {
- value = stringToBytes(value);
- }
-
- if (typeof namespace === 'string') {
- namespace = parse$1(namespace);
- }
-
- if (namespace.length !== 16) {
- throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
- } // Compute hash of namespace and value, Per 4.3
- // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
- // hashfunc([...namespace, ... value])`
-
-
- var bytes = new Uint8Array(16 + value.length);
- bytes.set(namespace);
- bytes.set(value, namespace.length);
- bytes = hashfunc(bytes);
- bytes[6] = bytes[6] & 0x0f | version;
- bytes[8] = bytes[8] & 0x3f | 0x80;
-
- if (buf) {
- offset = offset || 0;
-
- for (var i = 0; i < 16; ++i) {
- buf[offset + i] = bytes[i];
- }
-
- return buf;
- }
-
- return stringify(bytes);
- } // Function#name is not settable on some platforms (#270)
-
-
- try {
- generateUUID.name = name; // eslint-disable-next-line no-empty
- } catch (err) {} // For CommonJS default export support
-
-
- generateUUID.DNS = DNS;
- generateUUID.URL = URL;
- return generateUUID;
- }
-
- /*
- * Browser-compatible JavaScript MD5
- *
- * Modification of JavaScript MD5
- * https://github.com/blueimp/JavaScript-MD5
- *
- * Copyright 2011, Sebastian Tschan
- * https://blueimp.net
- *
- * Licensed under the MIT license:
- * https://opensource.org/licenses/MIT
- *
- * Based on
- * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
- * Digest Algorithm, as defined in RFC 1321.
- * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for more info.
- */
- function md5(bytes) {
- if (typeof bytes === 'string') {
- var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
-
- bytes = new Uint8Array(msg.length);
-
- for (var i = 0; i < msg.length; ++i) {
- bytes[i] = msg.charCodeAt(i);
- }
- }
-
- return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
- }
- /*
- * Convert an array of little-endian words to an array of bytes
- */
-
-
- function md5ToHexEncodedArray(input) {
- var output = [];
- var length32 = input.length * 32;
- var hexTab = '0123456789abcdef';
-
- for (var i = 0; i < length32; i += 8) {
- var x = input[i >> 5] >>> i % 32 & 0xff;
- var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
- output.push(hex);
- }
-
- return output;
- }
- /**
- * Calculate output length with padding and bit length
- */
-
-
- function getOutputLength(inputLength8) {
- return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
- }
- /*
- * Calculate the MD5 of an array of little-endian words, and a bit length.
- */
-
-
- function wordsToMd5(x, len) {
- /* append padding */
- x[len >> 5] |= 0x80 << len % 32;
- x[getOutputLength(len) - 1] = len;
- var a = 1732584193;
- var b = -271733879;
- var c = -1732584194;
- var d = 271733878;
-
- for (var i = 0; i < x.length; i += 16) {
- var olda = a;
- var oldb = b;
- var oldc = c;
- var oldd = d;
- a = md5ff(a, b, c, d, x[i], 7, -680876936);
- d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
- c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
- b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
- a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
- d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
- c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
- b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
- a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
- d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
- c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
- b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
- a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
- d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
- c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
- b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
- a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
- d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
- c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
- b = md5gg(b, c, d, a, x[i], 20, -373897302);
- a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
- d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
- c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
- b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
- a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
- d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
- c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
- b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
- a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
- d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
- c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
- b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
- a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
- d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
- c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
- b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
- a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
- d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
- c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
- b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
- a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
- d = md5hh(d, a, b, c, x[i], 11, -358537222);
- c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
- b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
- a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
- d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
- c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
- b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
- a = md5ii(a, b, c, d, x[i], 6, -198630844);
- d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
- c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
- b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
- a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
- d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
- c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
- b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
- a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
- d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
- c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
- b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
- a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
- d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
- c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
- b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
- a = safeAdd(a, olda);
- b = safeAdd(b, oldb);
- c = safeAdd(c, oldc);
- d = safeAdd(d, oldd);
- }
-
- return [a, b, c, d];
- }
- /*
- * Convert an array bytes to an array of little-endian words
- * Characters >255 have their high-byte silently ignored.
- */
-
-
- function bytesToWords(input) {
- if (input.length === 0) {
- return [];
- }
-
- var length8 = input.length * 8;
- var output = new Uint32Array(getOutputLength(length8));
-
- for (var i = 0; i < length8; i += 8) {
- output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
- }
-
- return output;
- }
- /*
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
- * to work around bugs in some JS interpreters.
- */
-
-
- function safeAdd(x, y) {
- var lsw = (x & 0xffff) + (y & 0xffff);
- var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
- return msw << 16 | lsw & 0xffff;
- }
- /*
- * Bitwise rotate a 32-bit number to the left.
- */
-
-
- function bitRotateLeft(num, cnt) {
- return num << cnt | num >>> 32 - cnt;
- }
- /*
- * These functions implement the four basic operations the algorithm uses.
- */
-
-
- function md5cmn(q, a, b, x, s, t) {
- return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
- }
-
- function md5ff(a, b, c, d, x, s, t) {
- return md5cmn(b & c | ~b & d, a, b, x, s, t);
- }
-
- function md5gg(a, b, c, d, x, s, t) {
- return md5cmn(b & d | c & ~d, a, b, x, s, t);
- }
-
- function md5hh(a, b, c, d, x, s, t) {
- return md5cmn(b ^ c ^ d, a, b, x, s, t);
- }
-
- function md5ii(a, b, c, d, x, s, t) {
- return md5cmn(c ^ (b | ~d), a, b, x, s, t);
- }
-
- var v3 = v35('v3', 0x30, md5);
- var v3$1 = v3;
-
- function v4(options, buf, offset) {
- options = options || {};
- var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
-
- rnds[6] = rnds[6] & 0x0f | 0x40;
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
-
- if (buf) {
- offset = offset || 0;
-
- for (var i = 0; i < 16; ++i) {
- buf[offset + i] = rnds[i];
- }
-
- return buf;
- }
-
- return stringify(rnds);
- }
-
- // Adapted from Chris Veness' SHA1 code at
- // http://www.movable-type.co.uk/scripts/sha1.html
- function f(s, x, y, z) {
- switch (s) {
- case 0:
- return x & y ^ ~x & z;
-
- case 1:
- return x ^ y ^ z;
-
- case 2:
- return x & y ^ x & z ^ y & z;
-
- case 3:
- return x ^ y ^ z;
- }
- }
-
- function ROTL(x, n) {
- return x << n | x >>> 32 - n;
- }
-
- function sha1(bytes) {
- var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
- var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
-
- if (typeof bytes === 'string') {
- var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
-
- bytes = [];
-
- for (var i = 0; i < msg.length; ++i) {
- bytes.push(msg.charCodeAt(i));
- }
- } else if (!Array.isArray(bytes)) {
- // Convert Array-like to Array
- bytes = Array.prototype.slice.call(bytes);
- }
-
- bytes.push(0x80);
- var l = bytes.length / 4 + 2;
- var N = Math.ceil(l / 16);
- var M = new Array(N);
-
- for (var _i = 0; _i < N; ++_i) {
- var arr = new Uint32Array(16);
-
- for (var j = 0; j < 16; ++j) {
- arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
- }
-
- M[_i] = arr;
- }
-
- M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
- M[N - 1][14] = Math.floor(M[N - 1][14]);
- M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
-
- for (var _i2 = 0; _i2 < N; ++_i2) {
- var W = new Uint32Array(80);
-
- for (var t = 0; t < 16; ++t) {
- W[t] = M[_i2][t];
- }
-
- for (var _t = 16; _t < 80; ++_t) {
- W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
- }
-
- var a = H[0];
- var b = H[1];
- var c = H[2];
- var d = H[3];
- var e = H[4];
-
- for (var _t2 = 0; _t2 < 80; ++_t2) {
- var s = Math.floor(_t2 / 20);
- var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
- e = d;
- d = c;
- c = ROTL(b, 30) >>> 0;
- b = a;
- a = T;
- }
-
- H[0] = H[0] + a >>> 0;
- H[1] = H[1] + b >>> 0;
- H[2] = H[2] + c >>> 0;
- H[3] = H[3] + d >>> 0;
- H[4] = H[4] + e >>> 0;
- }
-
- return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
- }
-
- var v5 = v35('v5', 0x50, sha1);
- var v5$1 = v5;
-
- var nil = '00000000-0000-0000-0000-000000000000';
-
- function version$1(uuid) {
- if (!validate(uuid)) {
- throw TypeError('Invalid UUID');
- }
-
- return parseInt(uuid.substr(14, 1), 16);
- }
-
- var esmBrowser = /*#__PURE__*/Object.freeze({
- __proto__: null,
- v1: v1,
- v3: v3$1,
- v4: v4,
- v5: v5$1,
- NIL: nil,
- version: version$1,
- validate: validate,
- stringify: stringify,
- parse: parse$1
- });
-
- var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
-
- // var __g = __G.__g;
- globalThis_1.mediator = mediator.apply({});
- // __g.mediator = __g.mediator.apply({})
- console.dir(globalThis_1.mediator);
-
-
- const indexHelper = (function(){
-
- var getPermutations = function(array){
- var permutations = {};
- // l(array.splice(0, 1))
- for(var i in array) {
- // l(array[i]);
- var aclone = array.slice(0);
- aclone.splice(i, 1);
- permutations[array[i]] = getPermutations(aclone );
- }
- return permutations
- };
-
- var getCombinations = function(array){
- // P & C
- // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
- var set = [];
- var alen = array.length;
- var combinations = 1 << alen; // Math.pow(2, array.length);
-
- for (var i = 1; i < combinations ; i++){
- var combination= [];
- for (var j=0;j<alen;j++) {
- if ((i & (1 << j))){
- combination.push(array[j]);
- }
- }
- set.push(combination);
- }
-
- return set;
- };
-
- return function(obj) {
- obj.getPermutations = getPermutations;
- // obj.getPermutations = getPermutations_HeapsMethod;
- obj.getCombinations = getCombinations;
-
- return obj;
- };
- })();
-
- const AnyStore = (function(){
- // A store that can store any type and lookup any type.
- // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
- // This wraps hash and a weakmap into an abstract class that routes to the appropriate
- // store based on the type of the object.
-
- const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
- const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
- const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
-
- const setForPrimitive = function(primitive, content, target) {
- // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
- target.storeForPrmitives[primitive] = content;
- return content;
- };
-
- const setForObject = function(obj, content, target) {
- // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
- target.storeForObjects.set(obj, content);
- return content;
- };
- const setForSymbol = function(symbol, content, target) {
- // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
- target.storeForObjects.set(target.__symbolToObj[symbol], content);
- return content;
- };
-
- const getFor = {
- '[object String]' : getForPrimitive
- , '[object Object]' : getForObject
- , '[object Symbol]' : getForSymbol
- };
- getFor['[object Number]'] = getFor['[object String]'];
- getFor['[object Array]'] = getFor['[object Object]'];
-
- const setFor = {
- '[object String]' : setForPrimitive
- , '[object Object]' : setForObject
- , '[object Symbol]' : setForSymbol
- };
- setFor['[object Number]'] = setFor['[object String]'];
- setFor['[object Array]'] = setFor['[object Object]'];
-
- function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
- // In some cases we are looking for value equivalence and in others referenced object equivalence.
- // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
- // What we really need is dereferencing until real value is reached.
- // And value compare in scope even if the value is an extremely long stream of bits..
- // Both of these are expensive in terms of scanning and finding the info required.
- // p[p.Index(what, true)] !! is not a value compare for find.
- // We also need to deal with sorting and filtering....
- if(valuecompare) throw "Not yet implemented."
- return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
- (()=>{
- if(bDontCreate) return
- var newSymbol = Symbol();
- __symbolFromObj.set(anyThing, newSymbol);
- __symbolToObj[newSymbol] = anyThing;
- return newSymbol })()
- ) }
- }
- function AnyStore(){
-
- // Dispatch based on type of prop.
- var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
- var p = new Proxy( targ
- , {
- // PB : TODO -- Proxy handler gets hit for Index function prop..
- get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
- , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
- });
- p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
- p.get = (what)=>{ return p[p.Index(what, true)] };
- p.set = (what, content)=>{ return p[p.Index(what)] = content};
- return p
- }
- AnyStore.create = AnyStore;
- return AnyStore
- })();
-
-
- function expandUint32Array(arr, data) {
- const newArray = new Uint32Array(arr.length + data.length);
- newArray.set(arr); // copy old data
- newArray.set(data, arr.length); // copy new data after end of old data
- return newArray;
- }
-
- const HEX_FFFFFFFF = 0xFFFFFFFF;
- const HEX_FFFF0000 = 0xFFFF0000;
- const HEX_FF00 = 0xFF00;
- const HEX_F0 = 0xF0;
- const HEX_0C = 0x0C;
-
- const MAX_32BITS = HEX_FFFFFFFF;
- const MAX_53BITS = Number.MAX_SAFE_INTEGER;
-
- const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
- BigInt(HEX_FFFF0000);
- BigInt(HEX_FF00);
- BigInt(HEX_F0);
- BigInt(HEX_0C);
-
- const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
-
- const BIGINT_0 = BigInt(0);
- const BIGINT_1 = BigInt(1);
- BigInt(2);
- BigInt(4);
- BigInt(8);
- BigInt(16);
- const BIGINT_32 = BigInt(32);
-
- // Only Positive numbers;
- function *bigIntBufferGenerator(bn){
- // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
- var signal = {};
- var stop = Symbol();
- var i = 0;
- for(;;){
- var bits32 = new Uint32Array(1);
- if(bn > MAX_32BITS){
- bits32[0]= Number((bn & BIGINT_MAX_32BITS));
- signal = (yield {i, bits32}) || {};
- if(signal === stop || signal.done) return {i, bits32};
- bn >>= BIGINT_32;
- i++;
- }
- else {
- bits32[0] = Number(bn);
- return {i, bits32};
- }
- }
- }
-
- function bigIntToBuffer(bn) {
- // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
- if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
- // PB : Note -- bn must be passed in. Callee should validate.
- var buffer = null;
- var iterator = bigIntBufferGenerator(bn);
- var next = iterator.next();
- if(next && !next.done) buffer = next.value.bits32;
- else return next.value.bits32;
- while(!(next = iterator.next()).done) {
- // PB : TODO -- Ineffficient copy in a loop !!
- // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
- buffer = expandUint32Array(buffer, next.value.bits32);
- }
- buffer = expandUint32Array(buffer, next.value.bits32);
- return buffer;
- }
-
- function bufferToBigInt(buffer) {
- // PB : Note -- buffer must be a Uint32Array. Callee should validate.
- var bn = BIGINT_0;
- for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
- return bn;
- }
- // A bitmask can also be specified by a index number of the bit in a BitArray
- // Implemented as a class to distinguish from a mask value.
- // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
- // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
- const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
- // Should support Numbers, BigInt and Uint32Array.
-
- function __is__(t){ if(t === BitIndex) return true; }
- function __is(type){ return typeof this === type ? true : __is__(type) }
-
- function __create(n){
-
- return BitIndex.apply({
- value : n
- , is : __is
- })
- }
-
- __create.create = __create;
- return __create
- })();
-
- // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
- function leftshift_Number(m){ return m << 1 }
- function leftshift_BigInt(m){ return m << BIGINT_1 }
- // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
-
- function indexOfLSB32(x, gptwo){
- // x needs to be a 32 bit number.
- // Private functions don't do validations to avoid overhead of validation.
- // Only public api's need to validate inputs.
- if(x === 0) return null;
-
- var i = 0;
- x & 0xFFFF0000 && (i += 16, x >>= 16),
- x & 0xFF00 && (i += 8, x >>= 8),
- x & 0xF0 && (i += 4, x >>= 4),
- x & 0x0C && (i += 2, x>>= 2),
- x & 2 && (i += 1);
- // x & 1 && (i = 0);
- return i;
- }
-
- // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
- // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
- // // x needs to be a BigInt.
- // // gptwo needs to be BigInt
- // // Private functions don't do validations to avoid overhead of validation.
- // // Only public api's need to validate inputs.
- // if(x === 0) return null;
- // gptwo = gptwo || x & -x;
-
- // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
- // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
- // var MultiplyDeBruijnBitPosition = [
- // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
- // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
- // ];
- // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
- // }
-
- // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
- // http://graphics.stanford.edu/~seander/bithacks.html
-
- const BitArrayUpto32Bits = (function(){
- function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
-
- function __createA(arr){
- validateBitLength(arr.length);
- var created = __create();
-
- // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
- var iterateUpto = [
- ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
- , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
- , ()=>{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 } ); }}
- ];
- arr.length > 31 ? iterateUpto.forEach(f=>f()) :
- arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
- iterateUpto[0]();
- return created;
- }
-
- function __createO(o){
- var arr = Object.keys(o);
- validateBitLength(arr.length);
-
- var created = __create();
-
- var iterateUpto = [
- ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
- , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
- , ()=>{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 } ); }}
- ];
- arr.length > 31 ? iterateUpto.forEach(f=>f()) :
- arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
- iterateUpto[0]();
-
- return created;
- }
-
- function __create(){
- var labels = {};
- var masks = {};
-
- var currentMaxMask;
- function __nextMask(){ __nextMask = leftshift_Number;
- return currentMaxMask = 1; }
-
- // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
- utils_1.assign(mxn,
- {
- validateMask(m){
- if(__is(m, BitIndex)) {
- if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
- return { BitIndex, labels : [masks[indexToMask(m.value)]]
- // , indices : m.value
- }
- }
- if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
- if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
- return true;
- }
- , labelsToMask : (__labels)=>{
- var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
- return result >>> 0;
- }
- , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
- , maskToLabels(m, transformEach){
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return valid.labels;
-
- var __labels = [];
- for(var gptwo;gptwo=m&-m;m^=gptwo) {
- if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
- else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
- }
- return __labels;
- }
- , labelToMask : (l)=>{ return labels[l] }
- , bit_or : (a, b)=>a | b
- , bit_and : (a, b)=>a & b
- , bit_xor : (a, b)=>a ^ b
- , bit_not : (a)=> ~a
-
- , assignMask : function(label, entity, incrementFn) {
- var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
- labels[label] = entity;
- 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.
- masks[labels[label].mask] = label;
- return labels[label];
- }
- , msbIndex : function(v) { throw "msb Not yet implemented" }
- , indexToMask : function(index) {
- if(index > 31) throw 'Not supported beyond 32 bits.'
- return (1 << index) >>> 0;
- }
- , indicesToMask : function(indices){
- var mask = 0;
- indices.forEach(index=>{
- if(index > 31) throw 'Not supported beyond 32 bits.'
- mask |= (1 << index);
- });
- return mask >>> 0;
- }
- , maskToIndices : function(m) {
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return [m.value];
- var indices = [];
- var gptwo;
- for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
- return indices;
- }
- , bit_shiftl : (a, s)=>{ return a << s }
- , bit_shiftr : (a, s)=>{ return a >> s }
- , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
- // , bit_shiftl_1 : ()=>{}
-
- , toJSON(radix, eachFn){
- var transFormed = {};
- if(!eachFn) return labels;
- Object.keys(labels).forEach(label =>{
- transFormed[label] = eachFn(labels[label]);
- });
- return transFormed;
- }
- , test(){
- Object.keys(masks).forEach((v, i)=> {
- console.log( v );
- console.log( i + ' : ' + v.toString(2) );
- console.log( this.maskToIndices(v));
- });
- console.log( (173).toString(2) );
- this.maskToIndices(173).map( (i)=>{ console.log( i ); });
- console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
- }
- });
- }
-
- var creatorFor = {
- '[object Array]' : __createA
- , '[object Object]' : __createO
- , 'undefined' : function(){ return __create() }
- };
-
- // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
- function BitArrayUpto32Bits(){
- return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
- creatorFor['undefined'](...arguments)}
-
- BitArrayUpto32Bits.create = BitArrayUpto32Bits;
- return BitArrayUpto32Bits
- })();
-
- const Mixin = (function(){
-
- function create(){
-
- var __mixins = new WeakMap();
- __mixins.set(Mixin, true);
-
- function __is__(t, type){
- if(utils_1.js.isPrimitive(t)) return false;
- if(!t || !t.mixins) return false;
- return t.mixins().get(type) ? true : false ; }
- function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
-
- return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
- , is : __is
- }
- }
-
- return {create}
- })();
-
- const BitArrayBigInt = (function(){
-
-
- function __createA(arr){
- var created = __create();
-
- for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
- for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
- return created;
- }
-
- function __createO(o){
- var arr = Object.keys(o);
- var created = __create();
-
- for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
- for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
-
- return created;
- }
-
- function __create(){
- var labels = {};
- var masks = {};
-
- var currentMaxMask;
- function __nextMask(){ __nextMask = leftshift_BigInt;
- return currentMaxMask = BIGINT_1; }
-
- // var store = ??? new Uint32Array(1)
- var mxn = Mixin.create();
- var created = utils_1.assign(mxn,
- {
- validateMask(m){
- if(mxn.is(m, BitIndex)) {
- return { BitIndex, labels : [masks[indexToMask(m.value)]] }
- }
- if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
- return true;
- }
- , labelsToMask : (__labels)=>{
- var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
- return result ;
- }
- , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
- , maskToLabels(m, transformEach){
- m = BigInt(m);
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return valid.labels;
-
- var __labels = [];
- for(var gptwo;gptwo=m&-m;m^=gptwo) {
- if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
- else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
- }
- return __labels;
- }
- , labelToMask : (l)=>{ return labels[l] }
- , bit_or : (a, b)=>a | b
- , bit_and : (a, b)=>a & b
- , bit_xor : (a, b)=>a ^ b
- , bit_not : (a)=> ~a
-
- , assignMask : function(label, entity, incrementFn) {
- var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
- labels[label] = entity;
- 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.
- masks[labels[label].mask] = label;
- return labels[label];
- }
- , msbIndex : function(v) { throw "msb Not yet implemented" }
- , indexToMask : function(index) {
- return BIGINT_1 << index;
- }
- , indicesToMask : function(indices){
- var mask = 0;
- indices.forEach(index=>{
- mask |= (1 << index);
- });
- return mask;
- }
- , maskToIndices : function(m) {
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return [m.value];
- var indices = [];
- var gptwo;
-
- var iterator = bigIntBufferGenerator(BigInt(m));
-
- var next;
- // if(next && !next.done) buffer = next.value.bits32;
- // else return next.value.bits32;
- var i = 0;
- while(!(next = iterator.next()).done) {
- next.value.bits32 > 0 ?
- ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
- : null;
- i++;
- }
- for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
-
- return indices;
- }
- , bit_shiftl : (a, s)=>{ return a << s }
- , bit_shiftr : (a, s)=>{ return a >> s }
- , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
- // , bit_shiftl_1 : ()=>{}
- , toJSON(radix, eachFn){
- var transFormed = {};
- if(!eachFn) return labels;
- Object.keys(labels).forEach(label =>{
- transFormed[label] = eachFn(labels[label]);
- });
- return transFormed;
- }
- , tosqlcte() {
-
- var select = '';
- // debugger
- Object.keys(labels).forEach((label, index, array) =>{
- var labelObject = labels[label];
- var rowselect = 'select ';
- Object.keys(labelObject).forEach((key, index, array) =>{
- rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
- if(array.length !== index+1) rowselect = rowselect + ',';
- });
- select = select + rowselect;
- if(array.length !== index+1) select = select + '\n union all \n';
- });
-
- console.log(select);
- return labels
-
-
- }
- , test(){
- Object.keys(masks).forEach((v, i)=> {
- console.log( v );
- console.log( i + ' : ' + v.toString(2) );
- console.log( this.maskToIndices(v));
- });
- console.log( (173).toString(2) );
- this.maskToIndices(173).map( (i)=>{ console.log( i ); });
- console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
- console.log(BigInt(2535301200456458802993406410752));
- console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
- console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
- }
- }
- );
- created.addMixin(BitArrayBigInt);
- return created;
- }
-
- var creatorFor = {
- '[object Array]' : __createA
- , '[object Object]' : __createO
- , 'undefined' : function(){ return __create() }
- };
-
- // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
- function BitArrayBigInt(){
- return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
- creatorFor['undefined'](...arguments)}
-
- BitArrayBigInt.create = BitArrayBigInt;
- return BitArrayBigInt
- })();
-
- // > 32 bits upto 53 bits.
- const BitArrayUpto53Bits = (function(){
-
- function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
-
- function __createO(o, options){
- var arr = Object.keys(o);
- validateBitLength(arr.length);
-
- var created = __create();
-
- var iterateUpto = [
- ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
- , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
- , ()=>{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 } ); }}
- , ()=>{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) } ); }}
- ];
- arr.length > 32 ? iterateUpto.forEach(f=>f()) :
- arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
- arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
- iterateUpto[0]();
-
- return created;
- }
-
- function __createA(arrInp, options){
- validateBitLength(arrInp.length);
-
- var created = __create();
-
- var arr = [];
- var pregencache = [];
- // PB : Changed to preincrement. Mask need not overflow for 53 bits...
- var iterateUpto = [
- (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]} ); }}
- , (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 ); }}
- , (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 } ); }}
- , (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) } ); }}
- ];
-
- if(options && options.pregenerated) {
- arrInp.forEach((inp=>{
- if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
- // Doesn't have a mask so needs generation.
- arr.push(inp);
- pregencache[inp] = options.pregenerated[inp];
- }
- else if(!options.pregenerated[inp]) arr.push(inp);
- }));
-
- Object.keys(options.pregenerated).forEach(p=>{
- if(pregencache[p]) return;
- created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
- });
- var prelen = Object.keys(created.toJSON()).length;
- prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
- prelen > 30 ?
- (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
- : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
- :
- prelen > 0 ?
- (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
- : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
- iterateUpto.slice(1,2).forEach(f=>f(prelen))
- :
- arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
- arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
- arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
- iterateUpto[0](prelen);
- }
- else {
- arr = arrInp;
- arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
- arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
- arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
- iterateUpto[0](0);
- }
-
- return created;
- }
-
- function __create(){
- var labels = {};
- var masks = {};
-
- var currentMaxMask;
- function __nextMask(){ __nextMask = leftshift_Number;
- return currentMaxMask = 1; }
-
-
-
- // var store = ??? new Uint32Array(1)
- var mxn = Mixin.create();
- var created = utils_1.assign(mxn,
- {
-
- assignMaxAsNextIncrement(possibleMax) {
- if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
- else currentMaxMask = possibleMax;
- }
- , validateMask(m){
- if(mxn.is(m, BitIndex)) {
- return { BitIndex, labels : [masks[indexToMask(m.value)]] }
- }
- if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
- if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
- return true;
- }
- , labelsToMask : (__labels)=>{
- var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
- return result >>> 0;
- }
- , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
- , maskToLabels(m, transformEach){
-
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return valid.labels;
-
- var __labels = [];
- var m = BigInt(m);
- // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
- for(var gptwo;gptwo=m&-m;m^=gptwo) {
- if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
- else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
- }
- return __labels;
- }
- , labelToMask : (l)=>{ return labels[l] }
- , bit_or : (a, b) => {
- return bit_opFn_Upto53(a,b, (a, b)=>a | b)
- }
- , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
- , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
- , bit_not : (a) => Number(~BigInt(a))
- , assignMask : function(label, entity, onassignment) {
-
- if(entity && entity.mask && masks[entity.mask]) {
- throw 'Mask collision. Cannot assign requested mask. ' + entity
- }
- var pregenerated = labels[label] || entity;
- // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
- // Everything is overridable except mask.
- if(pregenerated && pregenerated.mask) {
- onassignment = (onassignment || created.assignMaxAsNextIncrement);
-
- labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
- onassignment(pregenerated.mask);
- }
- else {
- onassignment = (onassignment || __nextMask);
-
- labels[label] = entity;
- 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.
- }
- masks[labels[label].mask] = label;
- return labels[label];
- }
- , msbIndex : function(v) { throw "msb Not yet implemented" }
- , indexToMask : function(index) {
- if(index > 52) throw 'Not supported beyond 53 bits.'
- return Number(BigInt(1) << BigInt(index));
- }
- , indicesToMask : function(indices){
- var mask = BigInt(0);
- indices.forEach(index=>{
- if(index > 52) throw 'Not supported beyond 53 bits.'
- mask |= (BIGINT_1 << BigInt(index));
- });
- return Number(mask);
- }
- , maskToIndices : function(m) {
- var valid = this.validateMask(m);
- if(!valid) throw "Invalid Mask"
- if(valid.BitIndex) return [m.value];
- var indices = [];
- var gptwo;
- if(m > MAX_32BITS) {
- var iterator = bigIntBufferGenerator(BigInt(m));
-
- var next;
- // if(next && !next.done) buffer = next.value.bits32;
- // else return next.value.bits32;
- var i = 0;
- while(!(next = iterator.next()).done) {
- next.value.bits32 > 0 ?
- ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
- : null;
- i++;
- }
- for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
- }
- else {
- m = Number(m);
- for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
- // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
-
- return indices;
- }
- , bit_shiftl : (a, s)=>{ return a << s }
- , bit_shiftr : (a, s)=>{ return a >> s }
- , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
- // , bit_shiftl_1 : ()=>{}
- , toJSON(radix, eachFn){
- var transFormed = {};
- if(!eachFn) return labels;
- Object.keys(labels).forEach(label =>{
- transFormed[label] = eachFn(labels[label]);
- });
- return transFormed;
- }
- , tosqlcte() {
-
- var select = '';
- // debugger
- Object.keys(labels).forEach((label, index, array) =>{
- var labelObject = labels[label];
- var rowselect = 'select ';
- Object.keys(labelObject).forEach((key, index, array) =>{
- rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
- if(array.length !== index+1) rowselect = rowselect + ',';
- });
- select = select + rowselect;
- if(array.length !== index+1) select = select + '\n union all \n';
- });
-
- console.log(select);
- return labels
-
-
- }
- , test(){
- Object.keys(masks).forEach((v, i)=> {
- console.log( v );
- console.log( i + ' : ' + v.toString(2) );
- console.log( this.maskToIndices(v));
- });
- console.log( (173).toString(2) );
- this.maskToIndices(173).map( (i)=>{ console.log( i ); });
- console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
- }
- });
-
- return created;
- }
-
- var creatorFor = {
- '[object Array]' : __createA
- , '[object Object]' : __createO
- , 'undefined' : function(){ return __create() }
-
- };
-
- // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
- function BitArrayUpto53Bits(){
- return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
- creatorFor['undefined'](...arguments)}
-
- BitArrayUpto53Bits.create = BitArrayUpto53Bits;
- return BitArrayUpto53Bits
- })();
- function bit_opFn_Upto53(a, b, opFn){
-
- return Number(opFn(BigInt(a), BigInt(b) ))
- // var result = new Uint32Array(2);
- // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
- // result[1] = opFn(a % POWER32, b % POWER32)
- // return POWER32 * result[0] + result[1];
- }
-
- // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
- const BitArray = (function(){
-
- // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
- // const MAX_SAFE_MASK_LENGTH = 32
-
- // function getMinMax(a, b){
- // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
- // : { min : a.length, minX : a, max : b.length, maxX : b }
- // }
-
- // function getTypes(a, b){
- // var aIsPrimitive = utils.js.isPrimitive(a);
- // var bIsPrimitive = utils.js.isPrimitive(b);
- // return { a : aIsPrimitive, b : bIsPrimitive }
- // }
-
- // // Binary oprations
- // function bit_opFn(a, b, opFn){
- // var tt = getTypes(a, b);
- // var mm = {}
- // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
- // if(tt.a && tt.b) {
- // // both are primitive
- // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
- // getRemaining = function(){ return []}
- // }
- // else if(tt.a){
- // // b is bitarray
- // mm = { min : 1, minX : [a], max : b.length, maxX : b}
- // }
- // else if(tt.b){
- // mm = { min : 1, minX : [b], max : a.length, maxX : a}
- // }
- // else {
- // var mm = getMinMax(a, b)
- // }
-
- // var result = new Uint32Array(mm.max);
- // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
- // // js.utils.isPrimitive(mm.maxX) ?
- // var remaining = getRemaining()
- // remaining.length > 0 ? result.set( remaining, mm.min) : null;
- // return result;
- // }
-
- // // Unary operations
- // function bit_opFnU(mm, opFn){
- // var result = new Uint32Array(mm.length);
- // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
- // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
- // return result;
- // }
- // function __expand(){
-
- // }
-
- function __createA(arr){
- // Create a new BitArray
- // Assign Unique bits to each item in an array of labels.
- arr.length % 32;
- arr.length/32 >>> 0;
- var created = arr.length > 53 ?
- BitArrayBigInt.create(...arguments) : arr.length > 32 ?
- BitArrayUpto53Bits.create(...arguments) :
- BitArrayUpto32Bits.create(...arguments);
- return created;
- }
-
- function __createO(o){
- // Create a new BitArray
- // Assign Unique bits to each item in an array of labels.
- var arr = Object.keys(o);
-
- arr.length % 32;
- arr.length/32 >>> 0;
- var created = arr.length > 53 ?
- BitArrayBigInt.create(...arguments) : arr.length > 32 ?
- BitArrayUpto53Bits.create(...arguments) :
- BitArrayUpto32Bits.create(...arguments);
- return created;
- }
-
- function __create(){
-
-
- // var store = new Uint32Array(1)
- Mixin.create();
- var created = BitArrayBigInt.create();
- created.addMixin(BitArray);
- return created;
- }
-
- var creatorFor = {
- '[object Array]' : __createA
- , '[object Object]' : __createO
- , 'undefined' : function(){ return __create() }
- };
- // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
- // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
- function BitArray(){
- return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
- creatorFor['undefined'](...arguments)}
- BitArray.create = BitArray;
- return BitArray
- })();
-
-
- // var uuidv1 = require('uuid/v1');
- const { v1: uuidv1 } = require$$1$1;
- console.log(uuidv1);
-
- // Mixins.
- const mixs = {
- // __JSTPL : (function() {
- // function __f() {}
- // return function() {
- // this.f = __f;
- // return this;
- // };
- // })()
-
- // Return a set of mixins.
-
- kernelMixin : (function() {
-
- // Wrapper to generate the currently chosen UUID version
- // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
- function __getuuid() {
- return uuidv1();
- }
-
- // uuid property Mainstream getter after lazy init
- function __get() {
- return this.kernel.uuidv1;
- }
-
- // uuid property First Time getter for lazy init.
- function __firstGet() {
- this.kernel.uuidv1 = __getuuid();
-
- __finalize.apply(this);
- return this.uuid;
- }
-
- function __finalize(){
- Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
- Object.defineProperty(this, 'uuid', {
-
- get : __get
- , enumerable : true
- , configurable : false
- });
-
- Object.defineProperty(this, 'kernel', {
-
- enumerable : false
- , configurable : false
- , writable : false
- });
- }
-
- function __defineKernel(){
-
- // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
- //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
- //const uuidv2 = // (date-time and MAC Address, DCE security version)
-
- // (namespace name-based) ...
- //const uuidv3md5 = require('uuid/v3');
- //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
-
- //const uuidv4 = require('uuid/v4'); //(random)
-
-
- // Kernel Properties are promoted onto the object itself without value as getters and setters as
- // configurable = false
- // enumerable = false
- // writable = false
- Object.defineProperty(this, 'kernel', { value :{}, writable : true });
-
-
- // Keep it lazy. Only generate on first use. Which could be first time persistence.
- Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
-
- // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
- // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
- // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
- // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
- // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
- }
-
- function __loadKernel() {
- // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
- this.kernel.uuidv1 = this.uuid;
- __finalize.apply(this);
- }
-
- function __attachKernel() {
-
- // Dont mess with something that already has a kernel.
- if(this.hasOwnProperty('kernel')) {
- l('Already has kernel');
- return this;
- }
-
- __defineKernel.apply(this);
-
- if(this.hasOwnProperty('uuid')) {
- l('Already has uuid');
- __loadKernel.apply(this);
-
- return this;
- }
- Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
- return this;
- }
-
- var __kernelInstanceMixin = function() {
- return __attachKernel.apply(this);
- };
- __kernelInstanceMixin.getuuid = __getuuid;
- return __kernelInstanceMixin;
- })()
-
- // Publishes messages to a message queue broker or mediator.
- , publisherMixin : (function() {
- function __publish() {
-
- }
- return function() {
- this.publish = __publish;
- return this;
- };
- })()
- };
-
- // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
- const helpers = {
- indexHelper : indexHelper
- , meta : (function() {
-
- // Mainly to observe changes to object properties.
- // A kernel uuid is a prerequisite.
- function spy(obj, prop, action) {
- action = action || 'set';
- if(action != 'set') {
- throw 'Currently only set actions can be observed on properties';
- }
-
- // Get the current descriptor
- var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- var value = obj[prop];
-
- if(descriptor && descriptor.get && descriptor.get.$meta){
- var originalset = descriptor.set;
- descriptor.set = function(newValue) {
- globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
- originalset(newValue);
- globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
- };
- return this;
- }
-
- descriptor = {
- get: function() {
- return value;
- },
- set: function(newValue) {
- globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
- value = newValue;
- globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
- }
- };
- descriptor.get.$meta = {};
- Object.defineProperty(obj, prop, descriptor);
- return this;
- }
-
- function getCustomPropertyDescriptor(obj, prop) {
- var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
- if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
- return actualDescriptor;
- }
-
- var value = obj[prop];
- var descriptor = {
- get: function() {
- return value;
- },
- set: function(newValue) {
- value = newValue;
- }
- };
- descriptor.get.$meta = {};
-
- Object.defineProperty(obj, prop, descriptor);
- return Object.getOwnPropertyDescriptor(obj, prop);
- }
-
- function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
- var descriptor = getCustomPropertyDescriptor(obj, propertyName);
-
- descriptor.get.$meta[attributeName] = attributeValue;
- }
-
- function getPropertyAttributes(obj, propertyName) {
- var descriptor = getCustomPropertyDescriptor(obj, propertyName);
-
- return descriptor.get.$meta;
- }
-
- function getPropertyAttribute(obj, propertyName, attributeName) {
- return getPropertyAttributes(obj, propertyName)[attributeName];
- }
-
- return function(obj) {
- obj.getPropertyAttribute = getPropertyAttribute;
- obj.getPropertyAttributes = getPropertyAttributes;
- obj.setPropertyAttribute = setPropertyAttribute;
- obj.spy = spy;
-
- return obj;
- };
- })()
- };
-
- var core = function(object){
- // l('in \tFunction core')
- return {
- mixs
- , helpers
- , AnyStore
- , BitArray
- , BitArrayUpto32Bits
- , BitArrayUpto53Bits
- , BitArrayBigInt
- // core object instances
- , uuidv1
- , Rule
- }
- };
-
- // export default core;
- var core_1 = core;
- // console.dir(__g.mediator)
- // try {
- // console.log( '__g === global : ' + (__g === global) )
- // }
- // catch(e){
- // console.log( '__g === global : ' + false )
- // }
- // try {
- // console.log( '__g === globalThis : ' + (__g === globalThis) )
- // }
- // catch(e){
- // console.log( '__g === globalThis : ' + false )
- // }
-
-
- function *bigIntBitGenerator(){
- var signal = {};
- var stop = Symbol();
- var iId = 0;
- var bit = BIGINT_1;
- for(;;){
- signal = (yield { iId, bit }) || {};
- if(signal === stop || signal.done) return { iId, bit };
- bit = bit << BIGINT_1;
- iId++;
- }
- }
-
- var Rule = (function(){
-
-
- // Immutable private static.
- var __Rule = {};
-
- // Overridable public static shared on the instance as well as convenience functions.
- // When the extend method is used the instance methods also correspond.
- // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
- // These could also be called statically with call or apply Eg: fn.apply(this)
- var _XRule = { assignbit, getParticipating };
- // Extendable public static
- // _Rule should not be referenced anywhere... as its members can be swithed.
-
-
- var _Rule = {
-
- extend : function(extension){
-
- function __create(){ return init.call({}) }
- function __createO(o){ return init.call(o) }
- function __createA(a){ a.forEach(r=> __createO(r)); return a }
- var creatorFor = {
- '[object Array]' : __createA
- , '[object Object]' : __createO
- , 'undefined' : function(){ return __create() }
- };
-
- function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
-
- // All static extensions shall be available on the instance as well.
- var _extension = utils_1.assign({}, _XRule, extension);
- function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
- utils_1.assign(Rule, _Rule, _extension, __Rule);
-
- // Immutable public static methods.
- Rule.create = Rule;
- Rule.build = buildRules;
- Rule.match = match;
- Rule.connect = connectRules;
- Rule.branch = function(as, ...rest){
- // PB : TODO -- All lists will be invalidated when we splice rules in...
- // Rule.create()
- // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
- console.error('Not yet implemented.');
- };
-
- // from loopback-connector/lib/sql.js
- // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
- // Convert from a natural filter to key val expanded filter.
- // Convert In clauses to one rule for each listed values.
- // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
- // Handle mask overflows gracefully
- /**
- * @param where
- * @returns {ChoppedRules}
- */
- function buildRules(where, data, fullResult, parentRule) {
- let columnValue;
- if (!where) return Promise.resolve(fullResult) ;
-
- if (typeof where !== 'object' || Array.isArray(where)) {
- debug('Invalid value for where: %j', where);
- return Promise.resolve(fullResult);
- }
-
- var ruleset = [];
- // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
- var id = data ? data.id : null;
- fullResult = fullResult || [];
- var createIntermediate = createIntermediateParentLess;
- var immediateParentP = null;
- if(parentRule) {
- immediateParentP = parentRule;
- createIntermediate = createIntermediateWithParent;
- }
-
- if(Object.keys(where).length > 1) {
- immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
- ruleset.push(immediateParentP);
- fullResult.push(immediateParentP);
- createIntermediate = createIntermediateWithParent;
- }
-
- for (const key in where) {
- // Handle and/or operators
- if (key === AND || key === OR) {
- const clauses = where[key];
- if (Array.isArray(clauses)) {
- if(clauses.length > 1) {
- var rp = createIntermediate({operator : key}, (rParent)=>{
- var list = [];
- for (let i = 0, n = clauses.length; i < n; i++) {
- list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
- connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
- return ruleForClause;
- }));
- }
- return list;
- }, immediateParentP);
- ruleset.push(rp);
- fullResult.push(rp);
- }
- else {
- // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
- // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
- var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
- // fullResult.push(rP) // Buildrules should should have already pushed this.
- ruleset.push(rP); // buildRules should have already linked parent and child.
- }
- continue;
- }
- else {
- throw 'Invalid filter '
- }
- }
- // eslint-disable one-var
- let expression = where[key];
- let p = key;
- var op ='eq';
- const columnName = columnEscaped(/* modelinstance || */ where, key);
- // eslint-enable one-var
- if (expression === null || expression === undefined) {
- // If null has been passed in we should match null.
- expression = null;
-
- var rpromise = assignbit(Rule.create({ key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
- if(immediateParentP) {
- return immediateParentP.then((immediateParent)=> {
- connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
- return rChild
- })
- }
-
- // PB : TODO -- Unwrapped decendents update on parent!!!
- return rChild
- }).catch(e=>{ console.error('null expression : ' + e); });
-
- fullResult.push(rpromise);
- ruleset.push(rpromise);
- } else if (expression && expression.constructor === Object) {
- const operator = Object.keys(expression)[0];
- expression = expression[operator];
- if (operator === INQ || operator === NIN || operator === BETWEEN) {
- columnValue = [];
- op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
- if (Array.isArray(expression)) {
- // Column value is a list
- for (let j = 0, m = expression.length; j < m; j++) {
- columnValue.push(toColumnValue(p, expression[j]));
- }
- } else {
- columnValue.push(toColumnValue(p, expression[j]));
- }
-
- if (operator === BETWEEN) {
- var rp = createIntermediate({operator : AND}, (rParent)=>{
- // BETWEEN v1 AND v2
- columnValue[0] === undefined ? null : columnValue[0];
- columnValue[1] === undefined ? null : columnValue[1];
- if(expression.length !== 2) console.error('Invalid between operator parameter length');
-
- var list = [];
- list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
- connectRules(operators[rParent.operator].bit, rChild, rParent);
- return rChild
- }));
- list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
- connectRules(operators[rParent.operator].bit, rChild, rParent);
- return rChild
- }));
- fullResult.push.apply(fullResult, list);
- return list;
- }, immediateParentP);
- ruleset.push(rp);
- fullResult.push(rp);
-
- } else {
- var rp = createIntermediate({operator : OR}, (rParent)=>{
- // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
- // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
- if (columnValue.length === 0) {
- if (operator === INQ) {
- columnValue = [null];
- } else {
- // nin () is true
- // nin : [null] is a world query which is an invalid filter. We don't support yet.
- return [];
- }
- }
- var list = [];
- for (let j = 0, m = columnValue.length; j < m; j++) {
- list.push(
- assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
- connectRules(operators[rParent.operator].bit, rChild, rParent);
- return rChild
- })
- );
- }
- fullResult.push.apply(fullResult, list);
- return list
- }, immediateParentP);
- ruleset.push(rp);
- fullResult.push(rp);
- }
- } else if (operator === 'regexp' && expression instanceof RegExp) {
- // do not coerce RegExp based on property definitions
-
- var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
- if(immediateParentP) {
- return immediateParentP.then((immediateParent)=> {
- connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
- return rChild
- })
- }
-
- // PB : TODO -- Unwrapped decendents update on parent!!!
- return rChild
- }).catch(e=>{ console.error('Regexp expression : ' + e); });
-
- fullResult.push(rpromise);
- ruleset.push(rpromise);
- // columnValue = expression;
- } else {
- var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
- if(immediateParentP) {
- return immediateParentP.then((immediateParent)=> {
- connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
- return rChild
- })
- }
-
- // PB : TODO -- Unwrapped decendents update on parent!!!
- return rChild
- }).catch(e=>{ console.error('other expression : ' + e); });
- fullResult.push(rpromise);
- ruleset.push(rpromise);
-
- // columnValue = toColumnValue(p, expression);
- }
-
- } else {
-
- if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
- // ruleProcessor[EQ]();
-
- var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
- if(immediateParentP) {
- return immediateParentP.then((immediateParent)=> {
- connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
- return rChild
- })
- }
-
- // PB : TODO -- Unwrapped decendents update on parent!!!
- return rChild
- }).catch(e=>{ console.error('other expression : ' + e); });
-
- fullResult.push(rpromise);
- ruleset.push(rpromise);
- }
- }
-
- return Promise.all(ruleset).then(()=>{
-
- if(immediateParentP){
- return immediateParentP;
- }
- if(ruleset.length > 1) {
- // If only 1 rule there is no point in having an outer implicit and.
- // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
- // and we need to return the grouped rule.
-
- // var grpromise = Promise.all(ruleset).then( (list)=>{
- // var grouped = Rule.create({ id, operator : AND }).assignbit();
- // return grouped.then(r=>{
- // r.list = list;
- // return r
- // })
- // });
-
- // fullResult.push(grpromise)
- // return grpromise
-
- return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
- }
- else if(ruleset.length > 0) {
- return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
- }
- else {
- return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
- }
- })
-
- }
- return Rule
- }
- };
- var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
- var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
- return rIntermediate
- });
-
- var grpromise = interMediatGroupParentP.then((rParent)=>{
-
- // var rParent = resolved[1]
- // if(immediateParentP) {
- // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
- // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
- // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
- // }
-
- // PB : TODO -- When we unwind descendents on ancestors need to be updated.
- // PB : TODO -- Why is this group not getting pushed into the full list.
- // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
- return Promise.all(createChildren(rParent)).then( (list)=>{
- // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
- // or an outer grouped rule.
- rParent.list = list;
- return rParent
- });
- });
- return grpromise;
- };
-
- var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
-
- var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
- return immediateParentP.then((immediateParent)=>{
- connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
- return rIntermediate
- })
- });
-
- var grpromise = interMediatGroupParentP.then((rParent)=>{
-
- // var rParent = resolved[1]
- // if(immediateParentP) {
- // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
- // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
- // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
- // }
-
- // PB : TODO -- When we unwind descendents on ancestors need to be updated.
- // PB : TODO -- Why is this group not getting pushed into the full list.
- // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
- return Promise.all(createChildren(rParent)).then( (list)=>{
- // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
- // or an outer grouped rule.
- rParent.list = list;
- return rParent
- });
- });
- return grpromise;
- };
-
- // Literals
- const EQ = 'eq';
- const LTE = 'lte';
- const GTE = 'gte';
- const LT = 'lt';
- const GT = 'gt';
- const AND = 'and';
- const OR = 'or';
- const INQ = 'inq';
- const BETWEEN = 'between';
- const NIN = 'nin';
- const NEQ = 'neq';
- __Rule.EQ = 1;
- __Rule.LTE = 2;
- __Rule.GTE = 4;
- __Rule.LT = 8;
- __Rule.GT = 16;
- __Rule.AND = 32;
- __Rule.OR = 64;
-
- var operators = {
- eq : { operator : '=', bit : __Rule.EQ}
- , lte : { operator : '<=', bit : __Rule.LTE}
- , gte : { operator : '>=', bit : __Rule.GTE}
- , lt : { operator : '<', bit : __Rule.LT}
- , gt : { operator : '>', bit : __Rule.GT}
- , and : { operator : AND, bit : __Rule.AND}
- , or : { operator : OR, bit : __Rule.OR}
- };
-
- var operatorsIndex = {};
- Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
-
- function __newInstance(o){
- var d = new Date();
- var id = o.id || uuidv1();
- return { v1ruleId : id, id, datecreated : d, datemodified : d
- , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
- }
-
- var globalBitIterator = bigIntBitGenerator();
- function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
- return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
- }
- // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
- function getParticipating(iRule, rList, cb){
- return Promise.all(iRule.results).then((iRules)=>{
- var SUCCESS = BIGINT_0;
- var FAILURE = BIGINT_0;
- var mask = BIGINT_0;
- var results = rList.filter(rule => {
- var found = iRules.find( iR => {
- if(iR.key && typeof(iR.key)=='string'){iR.key=iR.key.toUpperCase();}
- if(iR === rule || iR.id === rule.id ||
- iR.key === rule.key &&
- ( rule.operator == GT && (
- rule.value <= iR.value && iR.operator == GT
- || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
- )
- || rule.operator == GTE && (
- rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
- || (iR.value - rule.value) >= 0 && iR.operator == GT
- )
- || rule.operator == LT && (
- rule.value >= iR.value && iR.operator == LT
- || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
- )
- || rule.operator == LTE && (
- rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
- || (rule.value - iR.value) >= 0 && iR.operator == LT
- )
- || rule.operator == EQ && (
- rule.value == iR.value && iR.operator == EQ
- )
- )
- ) {
-
- SUCCESS |= bufferToBigInt(rule.bit);
- mask |= bufferToBigInt(rule.mask);
- return true;
- }
- });
-
- if(!found) {
- if(rule.isleaf) { FAILURE |= rule.bit; }
- else {
- // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
- // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
- // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
- // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
- // may help with evaulation of relevant rules earlier....
- // This specific rules full evaluation may be moot if no asserting participants can be found.
- // Or all its ancestral rules are already true without needing this rule to be evaluated....
- if(rule.permissive && rule.restrictive){
- if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
- if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
- if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
- if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
- }
-
- // if((rule.descendents & SUCCESS) === rule.descendents) {
- // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
- // SUCCESS |= rule.bit;
- // mask |= rule.mask;
- // }
- }
- }
-
- return found;
- });
-
- if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
- else return { mask, list : found};
- });
- }
-
- function getParticipatingRoots(participating, rList, cb){
- var qualifiedRoots = [];
- rList.forEach((r)=>{
- if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
- });
- cb(null, qualifiedRoots);
- }
-
- function toColumnValue(p, v) { return v; }
- function columnEscaped(inst, p) { return p; }
-
- function getsql_cond_group(){
- if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
- if(this.list.length < 2) {
- this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
- }
- var slqexprs = [];
- this.list.forEach(r => slqexprs.push(r.sql) );
- return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
- }
-
- function getfilter_cond_group(){
- if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
- if(this.list.length < 2) {
- this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
- }
- var filterexprs = [];
- this.list.forEach(r => filterexprs.push(r.filter) );
- return filterexprs;
- }
-
-
-
-
- // PB : TODO -- This might be easier done in a stored procedure.
- // It will also help if participating is not the whole list but the filtered list relevant for this rule.
- // Relocation so inline functions don't need to be redefined again and again.
- // Implement __Rule.isRoot
- var evaluate = function(rule, participating){
-
- if(rule.bit & participating.SUCCESS ) return true;
- if(rule.bit & participating.FAILURE) return false
- if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
- if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
- if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
- if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
-
- // 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.
-
- if(rule.isleaf) {
- if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
- else { participating.FAILURE |= rule.bit; return false; }
- }
- // else {
- // // If descendents are true we can extract only the ones that are direct connections and
- // // Evaluate...
- // var alldescendentsAreTrue = false;
- // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
- // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
- // alldescendentsAreTrue = true;
- // }
- // }
-
- // getUnevaluated
- var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
- for(var rc in rule.list){
- var r = rule.list[rc];
- if(r.bit & permissive) {
- if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
- else participating.FAILURE |= r.bit;
- }
- }
- if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
-
- // getUnevaluated.
- var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
- for(var rc in rule.list){
- var r = rule.list[rc];
- if(r.bit & restrictive) {
- if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
- participating.SUCCESS |= r.bit;
- }
- }
- if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
-
- throw 'Error : A group rule should either be permissive or restrictive...'
-
- };
-
- var match = function (inputs, rList, cb) {
- var results = [];
- if (typeof(clause)==undefined){var clause=null;}
- Rule.build(inputs, clause, results).then((inputRule)=>{
- inputRule.results = results;
- // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
- // Unless the assertion is of the form
- // Eg : this indiviudal's age is between x and y which is kind of rare.
- // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
- // An or assertion is still more rare and is usually an abstraction to not be specific.
- // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
- // Although the user has specific characteristics the specificity is not disclosed in the inputs.
- // And is adequate to distinguish the inputs from amongst a superset.
- // 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.
- // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
- // 2) exact input values with condition groups in the rules is also supportable.
- // 3) complex input rules as abstract or range assertions matching
- // complex rules that have range or absctract conditions -- How to Implement ??
- // IMPLEMENTATION AS SQL
- // FIND PARTICIPATING rules that evaluate true.
- /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
- OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
- OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
- ) AND
- ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
- OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
- OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
- )
- */
- // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
- /*
- LEFT JOIN rule
- WHERE participating.bit = (participating.bit & rule.mask)
- -- and rule.operator = 'or'
- -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
- */
- /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
- Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
- level rules directly or through other promoted grouped rules or groups.
- Evaluation Sets.
- Permissive rules, Restrictive rules, Indeterminant rules
- 1) Permissive bits turn the whole group to true if any one is true.
- Irrespective of all the other participating leaf rules.
- It is therefore not required to evaluate any other types of leaf rules.
- 2) Restrictive rules turn the whole group to false if any one is false.
- If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
- Other Indeterminant rule evaluation is therefore not relevant.
- 3) Indeterminant rules need to be evaluated at run time.
- -- Are typically unevaluated nested groups
- -- Or can be Individual Evaluated results
- which don't yet determine the overall result and mean anything
- until a complex hierarchy of conditions
- are evaluated and collectively satisifed.
-
- -- Since we do not (yet) support rule negations
- -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
- -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
-
- -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
- Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
-
- When There are no Permissive rules
- AND ( There are no restrictive rules OR all the restrictive rules are true )
- Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
- Subgroups are recursively evaluated using these same 3 steps.
-
- Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
- If the sub group rule participates in parents permissive set.
- All of its permissive rules should be added to the parent groups permissive set.
- -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
- If subgroup has restricitve sets and no descendents sets
- -- and is a subset of the parent groups restrictive set
- -- then subgroup bit can be removed from parents permissive and restrictive groups.
- -- This is good for preventing re-evaluation of the sub group for efficiency.
- -- else subgroup bit should be present in the permissive
- Sub group has descendents sets
- -- the sub group bit must necessarily be added to the parents permissive set.
-
- If the sub group rule participates in the parents restrictive set
- - Sub Group is Pure Permissive = Has no restrictive set or descendents set
- Runtime Evaluate.
-
- - Sub Group is Pure Restrictive = Has no permissive or descendents set
- -- Restrictive set of sub group should be promoted into the restrictive set of the parent
- -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
-
- - All other cases Runtime Evaluate.
-
- Sub Group participates in descendents set.
- -- Run time evaluation.
- */
-
- getParticipating(inputRule, rList, (err, participating)=>{
- getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
- cb(null, participatingRoots);
- });
- });
- });
- };
-
- // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
- // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
- // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
- // So both -ve and +ve dimensions are independent. But can be marked as opposites.
- // Note : Therefore Child and Parent are different independent dimensions.
- // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
- var connectRules = function(as, ...rest){ return branch[as](...rest) };
-
- var branch = {};
- branch[__Rule.AND] = function(rChild, rParent, refresh){
- rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
-
- if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
-
- if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
- rParent.list.push(rChild);
-
- // if(!rParent.permissive && !rParent.restrictive) {
- // if(rParent.operator !== AND && rParent.operator !== OR) {
- // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
- // else throw 'Incomplete parent. Invalid operator or no operator specified.'
- // }
- // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
- // }
-
- // Promotions : All child rules are only a bunch of Ands or ors
- // they can be flattened directly into the containing rule.
- // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
- // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
- rParent.restrictive |= rChild.restrictive | rChild.bit;
-
- // Descendents should be all non immediate descendents.
- // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
- // child may be either permissive or restrictive. Since child.restrictive is already added in.
- rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
-
- // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
- // and vice versa.
- if(refresh){
- // PB : TODO -- Cascading refreshes should avoid circular loops..
- rChild.refreshDescendents(rChild.ancestors);
- rParent.refreshAncestors(rParent.descendents);
- }
- };
-
- branch[__Rule.OR] = function(rChild, rParent, refresh){
- rChild.ancestors |= rParent.ancestors | rParent.bit;
-
- if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
- if(rParent.permissive & rChild.bit) return
- rParent.list.push(rChild);
-
- rParent.permissive |= rChild.permissive | rChild.bit;
-
- rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
- if(refresh){
- rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
- rParent.refreshAncestors(rParent.descendents);
- }
- };
-
- var rProto = { migrationstate : 8, operator : EQ
- , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
- , connect : function(parent){
- connectRules(operators[parent.operator].bit, this, parent);
- }
- // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
- , get sql(){
- var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
- : ()=>this.key + ' ' + operators[this.operator].operator + ` '${this.value}' `;
- return getSql.call(this)
- }
- , get filter(){
- var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getfilter_cond_group
- : ()=>{
- var f = {};
- f[this.key] = {};
- f[this.key][this.operator] = this.value; return f;};
- return getFilter.call(this)
- }
- // PB : TODO -- this.siblings will be a nice addition.
- , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
- , get isIndependent() { return (!this.mask || (this.bit === this.mask)) }
- , get isRoot() { return !this.ancestors }
- , get isChild() { return this.ancestors }
- , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
- , get isleaf() { return !this.bit || !(this.permissive | this.restrictive | this.descendents) }
- , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
- };
-
- return _Rule.extend()
- })();
-
- utils_1.core = core_1;
- var bbhverse = utils_1;
-
- const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
-
-
- function nodeShellExec$1() {
-
- var args = Array.from(arguments);
- var opts = args[2] = args[2] || {};
- opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
-
- // // const spawn = require('child_process').spawn;
- // const s = spawn(
- // 'C:\\Program Files\\Git\\bin\\sh.exe'
- // , ['notepad', 'index'], { cwd: __dirname });
-
-
-
- // var interval = null;
- // var t = setTimeout(function(){
- // interval = setInterval(function(){
-
- // console.log('Awaiting close : ' + child.spawnargs)
-
- // }, 1500)
- // // console.log('Awaiting close : ' + child.spawnargs)
-
- // }, 0)
-
- // child.on('close', (code) => {
- // console.error('Prematurely closed even before promise...')
- // })
- // 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
- // 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
-
- var p = new Promise(function(resolve, reject){
- // console.log(...args)
- const child = spawn$1(...args);
- if(!opts.detached) {
- var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
- var success = true;
-
- if(opts.stdio !== 'ignore') {
- child.stdout.setEncoding('utf8');
- child.stderr.setEncoding('utf8');
- child.stdout.on('data', (chunk) => {
- chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
- process.stdout.write( chunk );
- });
- child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */
- console.log('Error exit not handled.');
- } );
- child.stderr.on('data', (chunk) => {
- if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
- messages.push(chunk);
- process.stdout.write( chunk );
- // console.error('stderr e: ' + chunk)
- });
- }
- child.on('close', (code) => {
- // console.log('Proper close was fired')
- var logEntry = { code, success };
- if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code };} if(opts.stdio !== 'ignore') {
- logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
- logEntry.success = success;
-
- if(opts.runas){
- // success ? logEntry.success = true : null;
- fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
- }
- else {
- // console.log( messages.join('') )
- process.stdout.write( messages.join('') );
- }
- }
- // clearInterval(interval)
- if(code !== 0 || opts.haserrors) return reject(logEntry)
- resolve(logEntry);
- });
- }
- else {
- child.unref();
- // clearInterval(interval)
- resolve(true);
- }
- });
- // p.process = child;
- return p;
- }
-
- var prompt = function(choices, label, defaultchoice){
- var choices = choices || [];
- return this.prompter.ask(
- `${label} \n` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
- ).then(choice => {
- // propName = promptable.interpret(propValue)
- if(!choice) return defaultchoice || choices[0];
- if(choice && isNaN(+choice)) return choice;
- return choices[(+choice) - 1];
- })
- };
-
-
- var cli = {
- nodeShellExec: nodeShellExec$1
- , get prompter() {
- var prompt_interface = {
- ask : function(q){
- // Needs to be serialized. Parallel asks are not possible.
- const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
- return new Promise((resolve, reject)=>{
- clii.question(q, (answer)=>{
- try {
- clii.close();
- console.log("readline.createInterface closed");
- resolve(answer);
- }
- catch(e) {
- reject(e);
- }
- });
- })
- }
- };
- return prompt_interface
- }
- , prompt
- };
-
- var cliverse = cli;
-
- var colorName = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
- };
-
- /* MIT license */
-
- /* eslint-disable no-mixed-operators */
-
-
- // NOTE: conversions should only return primitive values (i.e. arrays, or
- // values that give correct `typeof` results).
- // do not use box values types (i.e. Number(), String(), etc.)
-
- const reverseKeywords = {};
- for (const key of Object.keys(colorName)) {
- reverseKeywords[colorName[key]] = key;
- }
-
- const convert$1 = {
- rgb: {channels: 3, labels: 'rgb'},
- hsl: {channels: 3, labels: 'hsl'},
- hsv: {channels: 3, labels: 'hsv'},
- hwb: {channels: 3, labels: 'hwb'},
- cmyk: {channels: 4, labels: 'cmyk'},
- xyz: {channels: 3, labels: 'xyz'},
- lab: {channels: 3, labels: 'lab'},
- lch: {channels: 3, labels: 'lch'},
- hex: {channels: 1, labels: ['hex']},
- keyword: {channels: 1, labels: ['keyword']},
- ansi16: {channels: 1, labels: ['ansi16']},
- ansi256: {channels: 1, labels: ['ansi256']},
- hcg: {channels: 3, labels: ['h', 'c', 'g']},
- apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
- gray: {channels: 1, labels: ['gray']}
- };
-
- var conversions = convert$1;
-
- // Hide .channels and .labels properties
- for (const model of Object.keys(convert$1)) {
- if (!('channels' in convert$1[model])) {
- throw new Error('missing channels property: ' + model);
- }
-
- if (!('labels' in convert$1[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
-
- if (convert$1[model].labels.length !== convert$1[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
-
- const {channels, labels} = convert$1[model];
- delete convert$1[model].channels;
- delete convert$1[model].labels;
- Object.defineProperty(convert$1[model], 'channels', {value: channels});
- Object.defineProperty(convert$1[model], 'labels', {value: labels});
- }
-
- convert$1.rgb.hsl = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const min = Math.min(r, g, b);
- const max = Math.max(r, g, b);
- const delta = max - min;
- let h;
- let s;
-
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
-
- h = Math.min(h * 60, 360);
-
- if (h < 0) {
- h += 360;
- }
-
- const l = (min + max) / 2;
-
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
-
- return [h, s * 100, l * 100];
- };
-
- convert$1.rgb.hsv = function (rgb) {
- let rdif;
- let gdif;
- let bdif;
- let h;
- let s;
-
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const v = Math.max(r, g, b);
- const diff = v - Math.min(r, g, b);
- const diffc = function (c) {
- return (v - c) / 6 / diff + 1 / 2;
- };
-
- if (diff === 0) {
- h = 0;
- s = 0;
- } else {
- s = diff / v;
- rdif = diffc(r);
- gdif = diffc(g);
- bdif = diffc(b);
-
- if (r === v) {
- h = bdif - gdif;
- } else if (g === v) {
- h = (1 / 3) + rdif - bdif;
- } else if (b === v) {
- h = (2 / 3) + gdif - rdif;
- }
-
- if (h < 0) {
- h += 1;
- } else if (h > 1) {
- h -= 1;
- }
- }
-
- return [
- h * 360,
- s * 100,
- v * 100
- ];
- };
-
- convert$1.rgb.hwb = function (rgb) {
- const r = rgb[0];
- const g = rgb[1];
- let b = rgb[2];
- const h = convert$1.rgb.hsl(rgb)[0];
- const w = 1 / 255 * Math.min(r, Math.min(g, b));
-
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
-
- return [h, w * 100, b * 100];
- };
-
- convert$1.rgb.cmyk = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
-
- const k = Math.min(1 - r, 1 - g, 1 - b);
- const c = (1 - r - k) / (1 - k) || 0;
- const m = (1 - g - k) / (1 - k) || 0;
- const y = (1 - b - k) / (1 - k) || 0;
-
- return [c * 100, m * 100, y * 100, k * 100];
- };
-
- function comparativeDistance(x, y) {
- /*
- See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- */
- return (
- ((x[0] - y[0]) ** 2) +
- ((x[1] - y[1]) ** 2) +
- ((x[2] - y[2]) ** 2)
- );
- }
-
- convert$1.rgb.keyword = function (rgb) {
- const reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
-
- let currentClosestDistance = Infinity;
- let currentClosestKeyword;
-
- for (const keyword of Object.keys(colorName)) {
- const value = colorName[keyword];
-
- // Compute comparative distance
- const distance = comparativeDistance(rgb, value);
-
- // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
-
- return currentClosestKeyword;
- };
-
- convert$1.keyword.rgb = function (keyword) {
- return colorName[keyword];
- };
-
- convert$1.rgb.xyz = function (rgb) {
- let r = rgb[0] / 255;
- let g = rgb[1] / 255;
- let b = rgb[2] / 255;
-
- // Assume sRGB
- r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
- g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
- b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
-
- const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
- const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
- const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
-
- return [x * 100, y * 100, z * 100];
- };
-
- convert$1.rgb.lab = function (rgb) {
- const xyz = convert$1.rgb.xyz(rgb);
- let x = xyz[0];
- let y = xyz[1];
- let z = xyz[2];
-
- x /= 95.047;
- y /= 100;
- z /= 108.883;
-
- x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
- y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
- z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
-
- const l = (116 * y) - 16;
- const a = 500 * (x - y);
- const b = 200 * (y - z);
-
- return [l, a, b];
- };
-
- convert$1.hsl.rgb = function (hsl) {
- const h = hsl[0] / 360;
- const s = hsl[1] / 100;
- const l = hsl[2] / 100;
- let t2;
- let t3;
- let val;
-
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
-
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
-
- const t1 = 2 * l - t2;
-
- const rgb = [0, 0, 0];
- for (let i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
-
- if (t3 > 1) {
- t3--;
- }
-
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
-
- rgb[i] = val * 255;
- }
-
- return rgb;
- };
-
- convert$1.hsl.hsv = function (hsl) {
- const h = hsl[0];
- let s = hsl[1] / 100;
- let l = hsl[2] / 100;
- let smin = s;
- const lmin = Math.max(l, 0.01);
-
- l *= 2;
- s *= (l <= 1) ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- const v = (l + s) / 2;
- const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
-
- return [h, sv * 100, v * 100];
- };
-
- convert$1.hsv.rgb = function (hsv) {
- const h = hsv[0] / 60;
- const s = hsv[1] / 100;
- let v = hsv[2] / 100;
- const hi = Math.floor(h) % 6;
-
- const f = h - Math.floor(h);
- const p = 255 * v * (1 - s);
- const q = 255 * v * (1 - (s * f));
- const t = 255 * v * (1 - (s * (1 - f)));
- v *= 255;
-
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
- };
-
- convert$1.hsv.hsl = function (hsv) {
- const h = hsv[0];
- const s = hsv[1] / 100;
- const v = hsv[2] / 100;
- const vmin = Math.max(v, 0.01);
- let sl;
- let l;
-
- l = (2 - s) * v;
- const lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= (lmin <= 1) ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
-
- return [h, sl * 100, l * 100];
- };
-
- // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
- convert$1.hwb.rgb = function (hwb) {
- const h = hwb[0] / 360;
- let wh = hwb[1] / 100;
- let bl = hwb[2] / 100;
- const ratio = wh + bl;
- let f;
-
- // Wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
-
- const i = Math.floor(6 * h);
- const v = 1 - bl;
- f = 6 * h - i;
-
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
-
- const n = wh + f * (v - wh); // Linear interpolation
-
- let r;
- let g;
- let b;
- /* eslint-disable max-statements-per-line,no-multi-spaces */
- switch (i) {
- default:
- case 6:
- case 0: r = v; g = n; b = wh; break;
- case 1: r = n; g = v; b = wh; break;
- case 2: r = wh; g = v; b = n; break;
- case 3: r = wh; g = n; b = v; break;
- case 4: r = n; g = wh; b = v; break;
- case 5: r = v; g = wh; b = n; break;
- }
- /* eslint-enable max-statements-per-line,no-multi-spaces */
-
- return [r * 255, g * 255, b * 255];
- };
-
- convert$1.cmyk.rgb = function (cmyk) {
- const c = cmyk[0] / 100;
- const m = cmyk[1] / 100;
- const y = cmyk[2] / 100;
- const k = cmyk[3] / 100;
-
- const r = 1 - Math.min(1, c * (1 - k) + k);
- const g = 1 - Math.min(1, m * (1 - k) + k);
- const b = 1 - Math.min(1, y * (1 - k) + k);
-
- return [r * 255, g * 255, b * 255];
- };
-
- convert$1.xyz.rgb = function (xyz) {
- const x = xyz[0] / 100;
- const y = xyz[1] / 100;
- const z = xyz[2] / 100;
- let r;
- let g;
- let b;
-
- r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
- g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
- b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
-
- // Assume sRGB
- r = r > 0.0031308
- ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
- : r * 12.92;
-
- g = g > 0.0031308
- ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
- : g * 12.92;
-
- b = b > 0.0031308
- ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
- : b * 12.92;
-
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
-
- return [r * 255, g * 255, b * 255];
- };
-
- convert$1.xyz.lab = function (xyz) {
- let x = xyz[0];
- let y = xyz[1];
- let z = xyz[2];
-
- x /= 95.047;
- y /= 100;
- z /= 108.883;
-
- x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
- y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
- z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
-
- const l = (116 * y) - 16;
- const a = 500 * (x - y);
- const b = 200 * (y - z);
-
- return [l, a, b];
- };
-
- convert$1.lab.xyz = function (lab) {
- const l = lab[0];
- const a = lab[1];
- const b = lab[2];
- let x;
- let y;
- let z;
-
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
-
- const y2 = y ** 3;
- const x2 = x ** 3;
- const z2 = z ** 3;
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
-
- x *= 95.047;
- y *= 100;
- z *= 108.883;
-
- return [x, y, z];
- };
-
- convert$1.lab.lch = function (lab) {
- const l = lab[0];
- const a = lab[1];
- const b = lab[2];
- let h;
-
- const hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
-
- if (h < 0) {
- h += 360;
- }
-
- const c = Math.sqrt(a * a + b * b);
-
- return [l, c, h];
- };
-
- convert$1.lch.lab = function (lch) {
- const l = lch[0];
- const c = lch[1];
- const h = lch[2];
-
- const hr = h / 360 * 2 * Math.PI;
- const a = c * Math.cos(hr);
- const b = c * Math.sin(hr);
-
- return [l, a, b];
- };
-
- convert$1.rgb.ansi16 = function (args, saturation = null) {
- const [r, g, b] = args;
- let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
-
- value = Math.round(value / 50);
-
- if (value === 0) {
- return 30;
- }
-
- let ansi = 30
- + ((Math.round(b / 255) << 2)
- | (Math.round(g / 255) << 1)
- | Math.round(r / 255));
-
- if (value === 2) {
- ansi += 60;
- }
-
- return ansi;
- };
-
- convert$1.hsv.ansi16 = function (args) {
- // Optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
- };
-
- convert$1.rgb.ansi256 = function (args) {
- const r = args[0];
- const g = args[1];
- const b = args[2];
-
- // We use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
-
- if (r > 248) {
- return 231;
- }
-
- return Math.round(((r - 8) / 247) * 24) + 232;
- }
-
- const ansi = 16
- + (36 * Math.round(r / 255 * 5))
- + (6 * Math.round(g / 255 * 5))
- + Math.round(b / 255 * 5);
-
- return ansi;
- };
-
- convert$1.ansi16.rgb = function (args) {
- let color = args % 10;
-
- // Handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
-
- color = color / 10.5 * 255;
-
- return [color, color, color];
- }
-
- const mult = (~~(args > 50) + 1) * 0.5;
- const r = ((color & 1) * mult) * 255;
- const g = (((color >> 1) & 1) * mult) * 255;
- const b = (((color >> 2) & 1) * mult) * 255;
-
- return [r, g, b];
- };
-
- convert$1.ansi256.rgb = function (args) {
- // Handle greyscale
- if (args >= 232) {
- const c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
-
- args -= 16;
-
- let rem;
- const r = Math.floor(args / 36) / 5 * 255;
- const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- const b = (rem % 6) / 5 * 255;
-
- return [r, g, b];
- };
-
- convert$1.rgb.hex = function (args) {
- const integer = ((Math.round(args[0]) & 0xFF) << 16)
- + ((Math.round(args[1]) & 0xFF) << 8)
- + (Math.round(args[2]) & 0xFF);
-
- const string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
-
- convert$1.hex.rgb = function (args) {
- const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
-
- let colorString = match[0];
-
- if (match[0].length === 3) {
- colorString = colorString.split('').map(char => {
- return char + char;
- }).join('');
- }
-
- const integer = parseInt(colorString, 16);
- const r = (integer >> 16) & 0xFF;
- const g = (integer >> 8) & 0xFF;
- const b = integer & 0xFF;
-
- return [r, g, b];
- };
-
- convert$1.rgb.hcg = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const max = Math.max(Math.max(r, g), b);
- const min = Math.min(Math.min(r, g), b);
- const chroma = (max - min);
- let grayscale;
- let hue;
-
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
-
- if (chroma <= 0) {
- hue = 0;
- } else
- if (max === r) {
- hue = ((g - b) / chroma) % 6;
- } else
- if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma;
- }
-
- hue /= 6;
- hue %= 1;
-
- return [hue * 360, chroma * 100, grayscale * 100];
- };
-
- convert$1.hsl.hcg = function (hsl) {
- const s = hsl[1] / 100;
- const l = hsl[2] / 100;
-
- const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
-
- let f = 0;
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
-
- return [hsl[0], c * 100, f * 100];
- };
-
- convert$1.hsv.hcg = function (hsv) {
- const s = hsv[1] / 100;
- const v = hsv[2] / 100;
-
- const c = s * v;
- let f = 0;
-
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
-
- return [hsv[0], c * 100, f * 100];
- };
-
- convert$1.hcg.rgb = function (hcg) {
- const h = hcg[0] / 360;
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
-
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
-
- const pure = [0, 0, 0];
- const hi = (h % 1) * 6;
- const v = hi % 1;
- const w = 1 - v;
- let mg = 0;
-
- /* eslint-disable max-statements-per-line */
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1; pure[1] = v; pure[2] = 0; break;
- case 1:
- pure[0] = w; pure[1] = 1; pure[2] = 0; break;
- case 2:
- pure[0] = 0; pure[1] = 1; pure[2] = v; break;
- case 3:
- pure[0] = 0; pure[1] = w; pure[2] = 1; break;
- case 4:
- pure[0] = v; pure[1] = 0; pure[2] = 1; break;
- default:
- pure[0] = 1; pure[1] = 0; pure[2] = w;
- }
- /* eslint-enable max-statements-per-line */
-
- mg = (1.0 - c) * g;
-
- return [
- (c * pure[0] + mg) * 255,
- (c * pure[1] + mg) * 255,
- (c * pure[2] + mg) * 255
- ];
- };
-
- convert$1.hcg.hsv = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
-
- const v = c + g * (1.0 - c);
- let f = 0;
-
- if (v > 0.0) {
- f = c / v;
- }
-
- return [hcg[0], f * 100, v * 100];
- };
-
- convert$1.hcg.hsl = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
-
- const l = g * (1.0 - c) + 0.5 * c;
- let s = 0;
-
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else
- if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
-
- return [hcg[0], s * 100, l * 100];
- };
-
- convert$1.hcg.hwb = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
- const v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
- };
-
- convert$1.hwb.hcg = function (hwb) {
- const w = hwb[1] / 100;
- const b = hwb[2] / 100;
- const v = 1 - b;
- const c = v - w;
- let g = 0;
-
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
-
- return [hwb[0], c * 100, g * 100];
- };
-
- convert$1.apple.rgb = function (apple) {
- return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
- };
-
- convert$1.rgb.apple = function (rgb) {
- return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
- };
-
- convert$1.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
-
- convert$1.gray.hsl = function (args) {
- return [0, 0, args[0]];
- };
-
- convert$1.gray.hsv = convert$1.gray.hsl;
-
- convert$1.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
- };
-
- convert$1.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
- };
-
- convert$1.gray.lab = function (gray) {
- return [gray[0], 0, 0];
- };
-
- convert$1.gray.hex = function (gray) {
- const val = Math.round(gray[0] / 100 * 255) & 0xFF;
- const integer = (val << 16) + (val << 8) + val;
-
- const string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
-
- convert$1.rgb.gray = function (rgb) {
- const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
- };
-
- /*
- This function routes a model to all other models.
-
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
-
- conversions that are not possible simply are not included.
- */
-
- function buildGraph() {
- const graph = {};
- // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- const models = Object.keys(conversions);
-
- for (let len = models.length, i = 0; i < len; i++) {
- graph[models[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
-
- return graph;
- }
-
- // https://en.wikipedia.org/wiki/Breadth-first_search
- function deriveBFS(fromModel) {
- const graph = buildGraph();
- const queue = [fromModel]; // Unshift -> queue -> pop
-
- graph[fromModel].distance = 0;
-
- while (queue.length) {
- const current = queue.pop();
- const adjacents = Object.keys(conversions[current]);
-
- for (let len = adjacents.length, i = 0; i < len; i++) {
- const adjacent = adjacents[i];
- const node = graph[adjacent];
-
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
-
- return graph;
- }
-
- function link(from, to) {
- return function (args) {
- return to(from(args));
- };
- }
-
- function wrapConversion(toModel, graph) {
- const path = [graph[toModel].parent, toModel];
- let fn = conversions[graph[toModel].parent][toModel];
-
- let cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path.unshift(graph[cur].parent);
- fn = link(conversions[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
-
- fn.conversion = path;
- return fn;
- }
-
- var route = function (fromModel) {
- const graph = deriveBFS(fromModel);
- const conversion = {};
-
- const models = Object.keys(graph);
- for (let len = models.length, i = 0; i < len; i++) {
- const toModel = models[i];
- const node = graph[toModel];
-
- if (node.parent === null) {
- // No possible conversion, or this node is the source model.
- continue;
- }
-
- conversion[toModel] = wrapConversion(toModel, graph);
- }
-
- return conversion;
- };
-
- const convert = {};
-
- const models = Object.keys(conversions);
-
- function wrapRaw(fn) {
- const wrappedFn = function (...args) {
- const arg0 = args[0];
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
-
- if (arg0.length > 1) {
- args = arg0;
- }
-
- return fn(args);
- };
-
- // Preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
-
- return wrappedFn;
- }
-
- function wrapRounded(fn) {
- const wrappedFn = function (...args) {
- const arg0 = args[0];
-
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
-
- if (arg0.length > 1) {
- args = arg0;
- }
-
- const result = fn(args);
-
- // We're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (let len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
-
- return result;
- };
-
- // Preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
-
- return wrappedFn;
- }
-
- models.forEach(fromModel => {
- convert[fromModel] = {};
-
- Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
- Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
-
- const routes = route(fromModel);
- const routeModels = Object.keys(routes);
-
- routeModels.forEach(toModel => {
- const fn = routes[toModel];
-
- convert[fromModel][toModel] = wrapRounded(fn);
- convert[fromModel][toModel].raw = wrapRaw(fn);
- });
- });
-
- var colorConvert = convert;
-
- var ansiStyles = createCommonjsModule(function (module) {
-
- const wrapAnsi16 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\u001B[${code + offset}m`;
- };
-
- const wrapAnsi256 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\u001B[${38 + offset};5;${code}m`;
- };
-
- const wrapAnsi16m = (fn, offset) => (...args) => {
- const rgb = fn(...args);
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
- };
-
- const ansi2ansi = n => n;
- const rgb2rgb = (r, g, b) => [r, g, b];
-
- const setLazyProperty = (object, property, get) => {
- Object.defineProperty(object, property, {
- get: () => {
- const value = get();
-
- Object.defineProperty(object, property, {
- value,
- enumerable: true,
- configurable: true
- });
-
- return value;
- },
- enumerable: true,
- configurable: true
- });
- };
-
- /** @type {typeof import('color-convert')} */
- let colorConvert$1;
- const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
- if (colorConvert$1 === undefined) {
- colorConvert$1 = colorConvert;
- }
-
- const offset = isBackground ? 10 : 0;
- const styles = {};
-
- for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
- const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
- if (sourceSpace === targetSpace) {
- styles[name] = wrap(identity, offset);
- } else if (typeof suite === 'object') {
- styles[name] = wrap(suite[targetSpace], offset);
- }
- }
-
- return styles;
- };
-
- function assembleStyles() {
- const codes = new Map();
- const styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
-
- // Bright color
- blackBright: [90, 39],
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
-
- // Bright color
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- };
-
- // Alias bright black as gray (and grey)
- styles.color.gray = styles.color.blackBright;
- styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
- styles.color.grey = styles.color.blackBright;
- styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
-
- for (const [groupName, group] of Object.entries(styles)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles[styleName] = {
- open: `\u001B[${style[0]}m`,
- close: `\u001B[${style[1]}m`
- };
-
- group[styleName] = styles[styleName];
-
- codes.set(style[0], style[1]);
- }
-
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- }
-
- Object.defineProperty(styles, 'codes', {
- value: codes,
- enumerable: false
- });
-
- styles.color.close = '\u001B[39m';
- styles.bgColor.close = '\u001B[49m';
-
- setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
- setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
- setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
- setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
- setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
- setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
-
- return styles;
- }
-
- // Make the export immutable
- Object.defineProperty(module, 'exports', {
- enumerable: true,
- get: assembleStyles
- });
- }, "/$$rollup_base$$/node_modules/ansi-styles");
-
- var hasFlag = (flag, argv = process.argv) => {
- const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
- const position = argv.indexOf(prefix + flag);
- const terminatorPosition = argv.indexOf('--');
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
- };
-
- const {env: env$1} = process;
-
- let forceColor;
- if (hasFlag('no-color') ||
- hasFlag('no-colors') ||
- hasFlag('color=false') ||
- hasFlag('color=never')) {
- forceColor = 0;
- } else if (hasFlag('color') ||
- hasFlag('colors') ||
- hasFlag('color=true') ||
- hasFlag('color=always')) {
- forceColor = 1;
- }
-
- if ('FORCE_COLOR' in env$1) {
- if (env$1.FORCE_COLOR === 'true') {
- forceColor = 1;
- } else if (env$1.FORCE_COLOR === 'false') {
- forceColor = 0;
- } else {
- forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
- }
- }
-
- function translateLevel(level) {
- if (level === 0) {
- return false;
- }
-
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
-
- function supportsColor(haveStream, streamIsTTY) {
- if (forceColor === 0) {
- return 0;
- }
-
- if (hasFlag('color=16m') ||
- hasFlag('color=full') ||
- hasFlag('color=truecolor')) {
- return 3;
- }
-
- if (hasFlag('color=256')) {
- return 2;
- }
-
- if (haveStream && !streamIsTTY && forceColor === undefined) {
- return 0;
- }
-
- const min = forceColor || 0;
-
- if (env$1.TERM === 'dumb') {
- return min;
- }
-
- if (process.platform === 'win32') {
- // Windows 10 build 10586 is the first Windows release that supports 256 colors.
- // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
- const osRelease = os__default['default'].release().split('.');
- if (
- Number(osRelease[0]) >= 10 &&
- Number(osRelease[2]) >= 10586
- ) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
-
- return 1;
- }
-
- if ('CI' in env$1) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
- return 1;
- }
-
- return min;
- }
-
- if ('TEAMCITY_VERSION' in env$1) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
- }
-
- if (env$1.COLORTERM === 'truecolor') {
- return 3;
- }
-
- if ('TERM_PROGRAM' in env$1) {
- const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
-
- switch (env$1.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
-
- if (/-256(color)?$/i.test(env$1.TERM)) {
- return 2;
- }
-
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
- return 1;
- }
-
- if ('COLORTERM' in env$1) {
- return 1;
- }
-
- return min;
- }
-
- function getSupportLevel(stream) {
- const level = supportsColor(stream, stream && stream.isTTY);
- return translateLevel(level);
- }
-
- var supportsColor_1 = {
- supportsColor: getSupportLevel,
- stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
- stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
- };
-
- const stringReplaceAll$1 = (string, substring, replacer) => {
- let index = string.indexOf(substring);
- if (index === -1) {
- return string;
- }
-
- const substringLength = substring.length;
- let endIndex = 0;
- let returnValue = '';
- do {
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
- endIndex = index + substringLength;
- index = string.indexOf(substring, endIndex);
- } while (index !== -1);
-
- returnValue += string.substr(endIndex);
- return returnValue;
- };
-
- const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
- let endIndex = 0;
- let returnValue = '';
- do {
- const gotCR = string[index - 1] === '\r';
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
- endIndex = index + 1;
- index = string.indexOf('\n', endIndex);
- } while (index !== -1);
-
- returnValue += string.substr(endIndex);
- return returnValue;
- };
-
- var util = {
- stringReplaceAll: stringReplaceAll$1,
- stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
- };
-
- 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;
- const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
-
- const ESCAPES = new Map([
- ['n', '\n'],
- ['r', '\r'],
- ['t', '\t'],
- ['b', '\b'],
- ['f', '\f'],
- ['v', '\v'],
- ['0', '\0'],
- ['\\', '\\'],
- ['e', '\u001B'],
- ['a', '\u0007']
- ]);
-
- function unescape$1(c) {
- const u = c[0] === 'u';
- const bracket = c[1] === '{';
-
- if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
-
- if (u && bracket) {
- return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
- }
-
- return ESCAPES.get(c) || c;
- }
-
- function parseArguments(name, arguments_) {
- const results = [];
- const chunks = arguments_.trim().split(/\s*,\s*/g);
- let matches;
-
- for (const chunk of chunks) {
- const number = Number(chunk);
- if (!Number.isNaN(number)) {
- results.push(number);
- } else if ((matches = chunk.match(STRING_REGEX))) {
- results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape$1(escape) : character));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
-
- return results;
- }
-
- function parseStyle(style) {
- STYLE_REGEX.lastIndex = 0;
-
- const results = [];
- let matches;
-
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
- const name = matches[1];
-
- if (matches[2]) {
- const args = parseArguments(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
-
- return results;
- }
-
- function buildStyle(chalk, styles) {
- const enabled = {};
-
- for (const layer of styles) {
- for (const style of layer.styles) {
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- }
-
- let current = chalk;
- for (const [styleName, styles] of Object.entries(enabled)) {
- if (!Array.isArray(styles)) {
- continue;
- }
-
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
-
- current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
- }
-
- return current;
- }
-
- var templates = (chalk, temporary) => {
- const styles = [];
- const chunks = [];
- let chunk = [];
-
- // eslint-disable-next-line max-params
- temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
- if (escapeCharacter) {
- chunk.push(unescape$1(escapeCharacter));
- } else if (style) {
- const string = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
- styles.push({inverse, styles: parseStyle(style)});
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
-
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(character);
- }
- });
-
- chunks.push(chunk.join(''));
-
- if (styles.length > 0) {
- const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMessage);
- }
-
- return chunks.join('');
- };
-
- const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
- const {
- stringReplaceAll,
- stringEncaseCRLFWithFirstIndex
- } = util;
-
- const {isArray: isArray$2} = Array;
-
- // `supportsColor.level` → `ansiStyles.color[name]` mapping
- const levelMapping = [
- 'ansi',
- 'ansi',
- 'ansi256',
- 'ansi16m'
- ];
-
- const styles = Object.create(null);
-
- const applyOptions = (object, options = {}) => {
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
- throw new Error('The `level` option should be an integer from 0 to 3');
- }
-
- // Detect level if not set manually
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
- object.level = options.level === undefined ? colorLevel : options.level;
- };
-
- class ChalkClass {
- constructor(options) {
- // eslint-disable-next-line no-constructor-return
- return chalkFactory(options);
- }
- }
-
- const chalkFactory = options => {
- const chalk = {};
- applyOptions(chalk, options);
-
- chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
-
- Object.setPrototypeOf(chalk, Chalk.prototype);
- Object.setPrototypeOf(chalk.template, chalk);
-
- chalk.template.constructor = () => {
- throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
- };
-
- chalk.template.Instance = ChalkClass;
-
- return chalk.template;
- };
-
- function Chalk(options) {
- return chalkFactory(options);
- }
-
- for (const [styleName, style] of Object.entries(ansiStyles)) {
- styles[styleName] = {
- get() {
- const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
- Object.defineProperty(this, styleName, {value: builder});
- return builder;
- }
- };
- }
-
- styles.visible = {
- get() {
- const builder = createBuilder(this, this._styler, true);
- Object.defineProperty(this, 'visible', {value: builder});
- return builder;
- }
- };
-
- const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
-
- for (const model of usedModels) {
- styles[model] = {
- get() {
- const {level} = this;
- return function (...arguments_) {
- const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
- return createBuilder(this, styler, this._isEmpty);
- };
- }
- };
- }
-
- for (const model of usedModels) {
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- const {level} = this;
- return function (...arguments_) {
- const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
- return createBuilder(this, styler, this._isEmpty);
- };
- }
- };
- }
-
- const proto = Object.defineProperties(() => {}, {
- ...styles,
- level: {
- enumerable: true,
- get() {
- return this._generator.level;
- },
- set(level) {
- this._generator.level = level;
- }
- }
- });
-
- const createStyler = (open, close, parent) => {
- let openAll;
- let closeAll;
- if (parent === undefined) {
- openAll = open;
- closeAll = close;
- } else {
- openAll = parent.openAll + open;
- closeAll = close + parent.closeAll;
- }
-
- return {
- open,
- close,
- openAll,
- closeAll,
- parent
- };
- };
-
- const createBuilder = (self, _styler, _isEmpty) => {
- const builder = (...arguments_) => {
- if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
- // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
- return applyStyle(builder, chalkTag(builder, ...arguments_));
- }
-
- // Single argument is hot path, implicit coercion is faster than anything
- // eslint-disable-next-line no-implicit-coercion
- return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
- };
-
- // We alter the prototype because we must return a function, but there is
- // no way to create a function with a different prototype
- Object.setPrototypeOf(builder, proto);
-
- builder._generator = self;
- builder._styler = _styler;
- builder._isEmpty = _isEmpty;
-
- return builder;
- };
-
- const applyStyle = (self, string) => {
- if (self.level <= 0 || !string) {
- return self._isEmpty ? '' : string;
- }
-
- let styler = self._styler;
-
- if (styler === undefined) {
- return string;
- }
-
- const {openAll, closeAll} = styler;
- if (string.indexOf('\u001B') !== -1) {
- while (styler !== undefined) {
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- string = stringReplaceAll(string, styler.close, styler.open);
-
- styler = styler.parent;
- }
- }
-
- // We can move both next actions out of loop, because remaining actions in loop won't have
- // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
- const lfIndex = string.indexOf('\n');
- if (lfIndex !== -1) {
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
- }
-
- return openAll + string + closeAll;
- };
-
- let template;
- const chalkTag = (chalk, ...strings) => {
- const [firstString] = strings;
-
- if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return strings.join(' ');
- }
-
- const arguments_ = strings.slice(1);
- const parts = [firstString.raw[0]];
-
- for (let i = 1; i < firstString.length; i++) {
- parts.push(
- String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
- String(firstString.raw[i])
- );
- }
-
- if (template === undefined) {
- template = templates;
- }
-
- return template(chalk, parts.join(''));
- };
-
- Object.defineProperties(Chalk.prototype, styles);
-
- const chalk = Chalk(); // eslint-disable-line new-cap
- chalk.supportsColor = stdoutColor;
- chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
- chalk.stderr.supportsColor = stderrColor;
-
- var source = chalk;
-
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
- var isWindows = process.platform === 'win32';
-
-
- // JavaScript implementation of realpath, ported from node pre-v6
-
- var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
-
- function rethrow() {
- // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
- // is fairly slow to generate.
- var callback;
- if (DEBUG) {
- var backtrace = new Error;
- callback = debugCallback;
- } else
- callback = missingCallback;
-
- return callback;
-
- function debugCallback(err) {
- if (err) {
- backtrace.message = err.message;
- err = backtrace;
- missingCallback(err);
- }
- }
-
- function missingCallback(err) {
- if (err) {
- if (process.throwDeprecation)
- throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
- else if (!process.noDeprecation) {
- var msg = 'fs: missing callback ' + (err.stack || err.message);
- if (process.traceDeprecation)
- console.trace(msg);
- else
- console.error(msg);
- }
- }
- }
- }
-
- function maybeCallback(cb) {
- return typeof cb === 'function' ? cb : rethrow();
- }
-
- path__default['default'].normalize;
-
- // Regexp that finds the next partion of a (partial) path
- // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
- if (isWindows) {
- var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
- } else {
- var nextPartRe = /(.*?)(?:[\/]+|$)/g;
- }
-
- // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
- if (isWindows) {
- var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
- } else {
- var splitRootRe = /^[\/]*/;
- }
-
- var realpathSync$1 = function realpathSync(p, cache) {
- // make p is absolute
- p = path__default['default'].resolve(p);
-
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return cache[p];
- }
-
- var original = p,
- seenLinks = {},
- knownHard = {};
-
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
-
- start();
-
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
-
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs__default['default'].lstatSync(base);
- knownHard[base] = true;
- }
- }
-
- // walk down the path, swapping out linked pathparts for their real
- // values
- // NB: p.length changes.
- while (pos < p.length) {
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
-
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- continue;
- }
-
- var resolvedLink;
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // some known symbolic link. no need to stat again.
- resolvedLink = cache[base];
- } else {
- var stat = fs__default['default'].lstatSync(base);
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- continue;
- }
-
- // read the link if it wasn't read before
- // dev/ino always return 0 on windows, so skip the check.
- var linkTarget = null;
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- linkTarget = seenLinks[id];
- }
- }
- if (linkTarget === null) {
- fs__default['default'].statSync(base);
- linkTarget = fs__default['default'].readlinkSync(base);
- }
- resolvedLink = path__default['default'].resolve(previous, linkTarget);
- // track this, if given a cache.
- if (cache) cache[base] = resolvedLink;
- if (!isWindows) seenLinks[id] = linkTarget;
- }
-
- // resolve the link, then start over
- p = path__default['default'].resolve(resolvedLink, p.slice(pos));
- start();
- }
-
- if (cache) cache[original] = p;
-
- return p;
- };
-
-
- var realpath$1 = function realpath(p, cache, cb) {
- if (typeof cb !== 'function') {
- cb = maybeCallback(cache);
- cache = null;
- }
-
- // make p is absolute
- p = path__default['default'].resolve(p);
-
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return process.nextTick(cb.bind(null, null, cache[p]));
- }
-
- var original = p,
- seenLinks = {},
- knownHard = {};
-
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
-
- start();
-
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
-
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs__default['default'].lstat(base, function(err) {
- if (err) return cb(err);
- knownHard[base] = true;
- LOOP();
- });
- } else {
- process.nextTick(LOOP);
- }
- }
-
- // walk down the path, swapping out linked pathparts for their real
- // values
- function LOOP() {
- // stop if scanned past end of path
- if (pos >= p.length) {
- if (cache) cache[original] = p;
- return cb(null, p);
- }
-
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
-
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- return process.nextTick(LOOP);
- }
-
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // known symbolic link. no need to stat again.
- return gotResolvedLink(cache[base]);
- }
-
- return fs__default['default'].lstat(base, gotStat);
- }
-
- function gotStat(err, stat) {
- if (err) return cb(err);
-
- // if not a symlink, skip to the next path part
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- return process.nextTick(LOOP);
- }
-
- // stat & read the link if not read before
- // call gotTarget as soon as the link target is known
- // dev/ino always return 0 on windows, so skip the check.
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- return gotTarget(null, seenLinks[id], base);
- }
- }
- fs__default['default'].stat(base, function(err) {
- if (err) return cb(err);
-
- fs__default['default'].readlink(base, function(err, target) {
- if (!isWindows) seenLinks[id] = target;
- gotTarget(err, target);
- });
- });
- }
-
- function gotTarget(err, target, base) {
- if (err) return cb(err);
-
- var resolvedLink = path__default['default'].resolve(previous, target);
- if (cache) cache[base] = resolvedLink;
- gotResolvedLink(resolvedLink);
- }
-
- function gotResolvedLink(resolvedLink) {
- // resolve the link, then start over
- p = path__default['default'].resolve(resolvedLink, p.slice(pos));
- start();
- }
- };
-
- var old = {
- realpathSync: realpathSync$1,
- realpath: realpath$1
- };
-
- var fs_realpath = realpath;
- realpath.realpath = realpath;
- realpath.sync = realpathSync;
- realpath.realpathSync = realpathSync;
- realpath.monkeypatch = monkeypatch;
- realpath.unmonkeypatch = unmonkeypatch;
-
-
- var origRealpath = fs__default['default'].realpath;
- var origRealpathSync = fs__default['default'].realpathSync;
-
- var version = process.version;
- var ok = /^v[0-5]\./.test(version);
-
-
- function newError (er) {
- return er && er.syscall === 'realpath' && (
- er.code === 'ELOOP' ||
- er.code === 'ENOMEM' ||
- er.code === 'ENAMETOOLONG'
- )
- }
-
- function realpath (p, cache, cb) {
- if (ok) {
- return origRealpath(p, cache, cb)
- }
-
- if (typeof cache === 'function') {
- cb = cache;
- cache = null;
- }
- origRealpath(p, cache, function (er, result) {
- if (newError(er)) {
- old.realpath(p, cache, cb);
- } else {
- cb(er, result);
- }
- });
- }
-
- function realpathSync (p, cache) {
- if (ok) {
- return origRealpathSync(p, cache)
- }
-
- try {
- return origRealpathSync(p, cache)
- } catch (er) {
- if (newError(er)) {
- return old.realpathSync(p, cache)
- } else {
- throw er
- }
- }
- }
-
- function monkeypatch () {
- fs__default['default'].realpath = realpath;
- fs__default['default'].realpathSync = realpathSync;
- }
-
- function unmonkeypatch () {
- fs__default['default'].realpath = origRealpath;
- fs__default['default'].realpathSync = origRealpathSync;
- }
-
- var concatMap = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray$1(x)) res.push.apply(res, x);
- else res.push(x);
- }
- return res;
- };
-
- var isArray$1 = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
-
- var balancedMatch = balanced;
- function balanced(a, b, str) {
- if (a instanceof RegExp) a = maybeMatch(a, str);
- if (b instanceof RegExp) b = maybeMatch(b, str);
-
- var r = range(a, b, str);
-
- return r && {
- start: r[0],
- end: r[1],
- pre: str.slice(0, r[0]),
- body: str.slice(r[0] + a.length, r[1]),
- post: str.slice(r[1] + b.length)
- };
- }
-
- function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
- }
-
- balanced.range = range;
- function range(a, b, str) {
- var begs, beg, left, right, result;
- var ai = str.indexOf(a);
- var bi = str.indexOf(b, ai + 1);
- var i = ai;
-
- if (ai >= 0 && bi > 0) {
- if(a===b) {
- return [ai, bi];
- }
- begs = [];
- left = str.length;
-
- while (i >= 0 && !result) {
- if (i == ai) {
- begs.push(i);
- ai = str.indexOf(a, i + 1);
- } else if (begs.length == 1) {
- result = [ begs.pop(), bi ];
- } else {
- beg = begs.pop();
- if (beg < left) {
- left = beg;
- right = bi;
- }
-
- bi = str.indexOf(b, i + 1);
- }
-
- i = ai < bi && ai >= 0 ? ai : bi;
- }
-
- if (begs.length) {
- result = [ left, right ];
- }
- }
-
- return result;
- }
-
- var braceExpansion = expandTop;
-
- var escSlash = '\0SLASH'+Math.random()+'\0';
- var escOpen = '\0OPEN'+Math.random()+'\0';
- var escClose = '\0CLOSE'+Math.random()+'\0';
- var escComma = '\0COMMA'+Math.random()+'\0';
- var escPeriod = '\0PERIOD'+Math.random()+'\0';
-
- function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
- }
-
- function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
- }
-
- function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
- }
-
-
- // Basically just str.split(","), but handling cases
- // where we have nested braced sections, which should be
- // treated as individual members, like {a,{b,c},d}
- function parseCommaParts(str) {
- if (!str)
- return [''];
-
- var parts = [];
- var m = balancedMatch('{', '}', str);
-
- if (!m)
- return str.split(',');
-
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
-
- p[p.length-1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length-1] += postParts.shift();
- p.push.apply(p, postParts);
- }
-
- parts.push.apply(parts, p);
-
- return parts;
- }
-
- function expandTop(str) {
- if (!str)
- return [];
-
- // I don't know why Bash 4.3 does this, but it does.
- // Anything starting with {} will have the first two bytes preserved
- // but *only* at the top level, so {},a}b will not expand to anything,
- // but a{},b}c will be expanded to [a}c,abc].
- // One could argue that this is a bug in Bash, but since the goal of
- // this module is to match Bash's rules, we escape a leading {}
- if (str.substr(0, 2) === '{}') {
- str = '\\{\\}' + str.substr(2);
- }
-
- return expand(escapeBraces(str), true).map(unescapeBraces);
- }
-
- function embrace(str) {
- return '{' + str + '}';
- }
- function isPadded(el) {
- return /^-?0\d/.test(el);
- }
-
- function lte(i, y) {
- return i <= y;
- }
- function gte(i, y) {
- return i >= y;
- }
-
- function expand(str, isTop) {
- var expansions = [];
-
- var m = balancedMatch('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
-
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = m.body.indexOf(',') >= 0;
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*\}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
- }
-
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
- return post.map(function(p) {
- return m.pre + n[0] + p;
- });
- }
- }
- }
-
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
-
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
-
- var N;
-
- if (isSequence) {
- var x = numeric(n[0]);
- var y = numeric(n[1]);
- var width = Math.max(n[0].length, n[1].length);
- var incr = n.length == 3
- ? Math.abs(numeric(n[2]))
- : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte;
- }
- var pad = n.some(isPadded);
-
- N = [];
-
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\')
- c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0)
- c = '-' + z + c.slice(1);
- else
- c = z + c;
- }
- }
- }
- N.push(c);
- }
- } else {
- N = concatMap(n, function(el) { return expand(el, false) });
- }
-
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion)
- expansions.push(expansion);
- }
- }
-
- return expansions;
- }
-
- var minimatch_1 = minimatch;
- minimatch.Minimatch = Minimatch$1;
-
- var path = { sep: '/' };
- try {
- path = path__default['default'];
- } catch (er) {}
-
- var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
-
-
- var plTypes = {
- '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
- '?': { open: '(?:', close: ')?' },
- '+': { open: '(?:', close: ')+' },
- '*': { open: '(?:', close: ')*' },
- '@': { open: '(?:', close: ')' }
- };
-
- // any single thing other than /
- // don't need to escape / when using new RegExp()
- var qmark = '[^/]';
-
- // * => any number of characters
- var star = qmark + '*?';
-
- // ** when dots are allowed. Anything goes, except .. and .
- // not (^ or / followed by one or two dots followed by $ or /),
- // followed by anything, any number of times.
- var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
-
- // not a ^ or / followed by a dot,
- // followed by anything, any number of times.
- var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
-
- // characters that need to be escaped in RegExp.
- var reSpecials = charSet('().*{}+?[]^$\\!');
-
- // "abc" -> { a:true, b:true, c:true }
- function charSet (s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true;
- return set
- }, {})
- }
-
- // normalizes slashes.
- var slashSplit = /\/+/;
-
- minimatch.filter = filter;
- function filter (pattern, options) {
- options = options || {};
- return function (p, i, list) {
- return minimatch(p, pattern, options)
- }
- }
-
- function ext (a, b) {
- a = a || {};
- b = b || {};
- var t = {};
- Object.keys(b).forEach(function (k) {
- t[k] = b[k];
- });
- Object.keys(a).forEach(function (k) {
- t[k] = a[k];
- });
- return t
- }
-
- minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch
-
- var orig = minimatch;
-
- var m = function minimatch (p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options))
- };
-
- m.Minimatch = function Minimatch (pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options))
- };
-
- return m
- };
-
- Minimatch$1.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch$1
- return minimatch.defaults(def).Minimatch
- };
-
- function minimatch (p, pattern, options) {
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required')
- }
-
- if (!options) options = {};
-
- // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false
- }
-
- // "" only matches ""
- if (pattern.trim() === '') return p === ''
-
- return new Minimatch$1(pattern, options).match(p)
- }
-
- function Minimatch$1 (pattern, options) {
- if (!(this instanceof Minimatch$1)) {
- return new Minimatch$1(pattern, options)
- }
-
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required')
- }
-
- if (!options) options = {};
- pattern = pattern.trim();
-
- // windows support: need to use /, not \
- if (path.sep !== '/') {
- pattern = pattern.split(path.sep).join('/');
- }
-
- this.options = options;
- this.set = [];
- this.pattern = pattern;
- this.regexp = null;
- this.negate = false;
- this.comment = false;
- this.empty = false;
-
- // make the set of regexps etc.
- this.make();
- }
-
- Minimatch$1.prototype.debug = function () {};
-
- Minimatch$1.prototype.make = make;
- function make () {
- // don't do it more than once.
- if (this._made) return
-
- var pattern = this.pattern;
- var options = this.options;
-
- // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true;
- return
- }
- if (!pattern) {
- this.empty = true;
- return
- }
-
- // step 1: figure out negation, etc.
- this.parseNegate();
-
- // step 2: expand braces
- var set = this.globSet = this.braceExpand();
-
- if (options.debug) this.debug = console.error;
-
- this.debug(this.pattern, set);
-
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit)
- });
-
- this.debug(this.pattern, set);
-
- // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this);
-
- this.debug(this.pattern, set);
-
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- });
-
- this.debug(this.pattern, set);
-
- this.set = set;
- }
-
- Minimatch$1.prototype.parseNegate = parseNegate;
- function parseNegate () {
- var pattern = this.pattern;
- var negate = false;
- var options = this.options;
- var negateOffset = 0;
-
- if (options.nonegate) return
-
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate;
- negateOffset++;
- }
-
- if (negateOffset) this.pattern = pattern.substr(negateOffset);
- this.negate = negate;
- }
-
- // Brace expansion:
- // a{b,c}d -> abd acd
- // a{b,}c -> abc ac
- // a{0..3}d -> a0d a1d a2d a3d
- // a{b,c{d,e}f}g -> abg acdfg acefg
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
- //
- // Invalid sets are not expanded.
- // a{2..}b -> a{2..}b
- // a{b}c -> a{b}c
- minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
- };
-
- Minimatch$1.prototype.braceExpand = braceExpand;
-
- function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch$1) {
- options = this.options;
- } else {
- options = {};
- }
- }
-
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern;
-
- if (typeof pattern === 'undefined') {
- throw new TypeError('undefined pattern')
- }
-
- if (options.nobrace ||
- !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern]
- }
-
- return braceExpansion(pattern)
- }
-
- // parse a component of the expanded set.
- // At this point, no pattern may contain "/" in it
- // so we're going to return a 2d array, where each entry is the full
- // pattern, split on '/', and then turned into a regular expression.
- // A regexp is made at the end which joins each array with an
- // escaped /, and another full one which joins each regexp with |.
- //
- // Following the lead of Bash 4.1, note that "**" only has special meaning
- // when it is the *only* thing in a path portion. Otherwise, any series
- // of * is equivalent to a single *. Globstar behavior is enabled by
- // default, and can be disabled by setting options.noglobstar.
- Minimatch$1.prototype.parse = parse;
- var SUBPARSE = {};
- function parse (pattern, isSub) {
- if (pattern.length > 1024 * 64) {
- throw new TypeError('pattern is too long')
- }
-
- var options = this.options;
-
- // shortcuts
- if (!options.noglobstar && pattern === '**') return GLOBSTAR
- if (pattern === '') return ''
-
- var re = '';
- var hasMagic = !!options.nocase;
- var escaping = false;
- // ? => one single character
- var patternListStack = [];
- var negativeLists = [];
- var stateChar;
- var inClass = false;
- var reClassStart = -1;
- var classStart = -1;
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)';
- var self = this;
-
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star;
- hasMagic = true;
- break
- case '?':
- re += qmark;
- hasMagic = true;
- break
- default:
- re += '\\' + stateChar;
- break
- }
- self.debug('clearStateChar %j %j', stateChar, re);
- stateChar = false;
- }
- }
-
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c);
-
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c;
- escaping = false;
- continue
- }
-
- switch (c) {
- case '/':
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
-
- case '\\':
- clearStateChar();
- escaping = true;
- continue
-
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
-
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class');
- if (c === '!' && i === classStart + 1) c = '^';
- re += c;
- continue
- }
-
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar);
- clearStateChar();
- stateChar = c;
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar();
- continue
-
- case '(':
- if (inClass) {
- re += '(';
- continue
- }
-
- if (!stateChar) {
- re += '\\(';
- continue
- }
-
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- });
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
- this.debug('plType %j %j', stateChar, re);
- stateChar = false;
- continue
-
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)';
- continue
- }
-
- clearStateChar();
- hasMagic = true;
- var pl = patternListStack.pop();
- // negation is (?:(?!js)[^/]*)
- // The others are (?:<pattern>)<type>
- re += pl.close;
- if (pl.type === '!') {
- negativeLists.push(pl);
- }
- pl.reEnd = re.length;
- continue
-
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|';
- escaping = false;
- continue
- }
-
- clearStateChar();
- re += '|';
- continue
-
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar();
-
- if (inClass) {
- re += '\\' + c;
- continue
- }
-
- inClass = true;
- classStart = i;
- reClassStart = re.length;
- re += c;
- continue
-
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c;
- escaping = false;
- continue
- }
-
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- if (inClass) {
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i);
- try {
- RegExp('[' + cs + ']');
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
- hasMagic = hasMagic || sp[1];
- inClass = false;
- continue
- }
- }
-
- // finish up the class.
- hasMagic = true;
- inClass = false;
- re += c;
- continue
-
- default:
- // swallow any state char that wasn't consumed
- clearStateChar();
-
- if (escaping) {
- // no need
- escaping = false;
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\';
- }
-
- re += c;
-
- } // switch
- } // for
-
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1);
- sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0];
- hasMagic = hasMagic || sp[1];
- }
-
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length);
- this.debug('setting tail', re, pl);
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\';
- }
-
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- });
-
- this.debug('tail=%j\n %s', tail, tail, pl, re);
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type;
-
- hasMagic = true;
- re = re.slice(0, pl.reStart) + t + '\\(' + tail;
- }
-
- // handle trailing things that only matter at the very end.
- clearStateChar();
- if (escaping) {
- // trailing \\
- re += '\\\\';
- }
-
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false;
- switch (re.charAt(0)) {
- case '.':
- case '[':
- case '(': addPatternStart = true;
- }
-
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n];
-
- var nlBefore = re.slice(0, nl.reStart);
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
- var nlAfter = re.slice(nl.reEnd);
-
- nlLast += nlAfter;
-
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1;
- var cleanAfter = nlAfter;
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
- }
- nlAfter = cleanAfter;
-
- var dollar = '';
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$';
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
- re = newRe;
- }
-
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re;
- }
-
- if (addPatternStart) {
- re = patternStart + re;
- }
-
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
-
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
-
- var flags = options.nocase ? 'i' : '';
- try {
- var regExp = new RegExp('^' + re + '$', flags);
- } catch (er) {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
- }
-
- regExp._glob = pattern;
- regExp._src = re;
-
- return regExp
- }
-
- minimatch.makeRe = function (pattern, options) {
- return new Minimatch$1(pattern, options || {}).makeRe()
- };
-
- Minimatch$1.prototype.makeRe = makeRe;
- function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
-
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set;
-
- if (!set.length) {
- this.regexp = false;
- return this.regexp
- }
- var options = this.options;
-
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot;
- var flags = options.nocase ? 'i' : '';
-
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|');
-
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$';
-
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$';
-
- try {
- this.regexp = new RegExp(re, flags);
- } catch (ex) {
- this.regexp = false;
- }
- return this.regexp
- }
-
- minimatch.match = function (list, pattern, options) {
- options = options || {};
- var mm = new Minimatch$1(pattern, options);
- list = list.filter(function (f) {
- return mm.match(f)
- });
- if (mm.options.nonull && !list.length) {
- list.push(pattern);
- }
- return list
- };
-
- Minimatch$1.prototype.match = match;
- function match (f, partial) {
- this.debug('match', f, this.pattern);
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
-
- if (f === '/' && partial) return true
-
- var options = this.options;
-
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/');
- }
-
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit);
- this.debug(this.pattern, 'split', f);
-
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
-
- var set = this.set;
- this.debug(this.pattern, 'set', set);
-
- // Find the basename of the path by looking for the last non-empty segment
- var filename;
- var i;
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i];
- if (filename) break
- }
-
- for (i = 0; i < set.length; i++) {
- var pattern = set[i];
- var file = f;
- if (options.matchBase && pattern.length === 1) {
- file = [filename];
- }
- var hit = this.matchOne(file, pattern, partial);
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
- }
- }
-
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
- }
-
- // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options;
-
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern });
-
- this.debug('matchOne', file.length, pattern.length);
-
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop');
- var p = pattern[pi];
- var f = file[fi];
-
- this.debug(pattern, p, f);
-
- // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false
-
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f]);
-
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi;
- var pr = pi + 1;
- if (pr === pl) {
- this.debug('** at the end');
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
- }
-
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr];
-
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
-
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee);
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr);
- break
- }
-
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue');
- fr++;
- }
- }
-
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
- if (fr === fl) return true
- }
- return false
- }
-
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit;
- if (typeof p === 'string') {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase();
- } else {
- hit = f === p;
- }
- this.debug('string match', p, f, hit);
- } else {
- hit = f.match(p);
- this.debug('pattern match', p, f, hit);
- }
-
- if (!hit) return false
- }
-
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
-
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
- return emptyFileEnd
- }
-
- // should be unreachable.
- throw new Error('wtf?')
- };
-
- // replace stuff like \* with *
- function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
- }
-
- function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
- }
-
- var inherits_browser = createCommonjsModule(function (module) {
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- }
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function () {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- }
- };
- }
- }, "/$$rollup_base$$/node_modules/inherits");
-
- var inherits = createCommonjsModule(function (module) {
- try {
- var util = require$$0__default['default'];
- /* istanbul ignore next */
- if (typeof util.inherits !== 'function') throw '';
- module.exports = util.inherits;
- } catch (e) {
- /* istanbul ignore next */
- module.exports = inherits_browser;
- }
- }, "/$$rollup_base$$/node_modules/inherits");
-
- function posix(path) {
- return path.charAt(0) === '/';
- }
-
- function win32(path) {
- // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
- var result = splitDeviceRe.exec(path);
- var device = result[1] || '';
- var isUnc = Boolean(device && device.charAt(1) !== ':');
-
- // UNC paths are always absolute
- return Boolean(result[2] || isUnc);
- }
-
- var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
- var posix_1 = posix;
- var win32_1 = win32;
- pathIsAbsolute.posix = posix_1;
- pathIsAbsolute.win32 = win32_1;
-
- var setopts_1 = setopts$2;
- var ownProp_1 = ownProp$2;
- var makeAbs_1 = makeAbs;
- var finish_1 = finish;
- var mark_1 = mark;
- var isIgnored_1 = isIgnored$2;
- var childrenIgnored_1 = childrenIgnored$2;
-
- function ownProp$2 (obj, field) {
- return Object.prototype.hasOwnProperty.call(obj, field)
- }
-
-
-
-
-
- var Minimatch = minimatch_1.Minimatch;
-
- function alphasort (a, b) {
- return a.localeCompare(b, 'en')
- }
-
- function setupIgnores (self, options) {
- self.ignore = options.ignore || [];
-
- if (!Array.isArray(self.ignore))
- self.ignore = [self.ignore];
-
- if (self.ignore.length) {
- self.ignore = self.ignore.map(ignoreMap);
- }
- }
-
- // ignore patterns are always in dot:true mode.
- function ignoreMap (pattern) {
- var gmatcher = null;
- if (pattern.slice(-3) === '/**') {
- var gpattern = pattern.replace(/(\/\*\*)+$/, '');
- gmatcher = new Minimatch(gpattern, { dot: true });
- }
-
- return {
- matcher: new Minimatch(pattern, { dot: true }),
- gmatcher: gmatcher
- }
- }
-
- function setopts$2 (self, pattern, options) {
- if (!options)
- options = {};
-
- // base-matching: just use globstar for that.
- if (options.matchBase && -1 === pattern.indexOf("/")) {
- if (options.noglobstar) {
- throw new Error("base matching requires globstar")
- }
- pattern = "**/" + pattern;
- }
-
- self.silent = !!options.silent;
- self.pattern = pattern;
- self.strict = options.strict !== false;
- self.realpath = !!options.realpath;
- self.realpathCache = options.realpathCache || Object.create(null);
- self.follow = !!options.follow;
- self.dot = !!options.dot;
- self.mark = !!options.mark;
- self.nodir = !!options.nodir;
- if (self.nodir)
- self.mark = true;
- self.sync = !!options.sync;
- self.nounique = !!options.nounique;
- self.nonull = !!options.nonull;
- self.nosort = !!options.nosort;
- self.nocase = !!options.nocase;
- self.stat = !!options.stat;
- self.noprocess = !!options.noprocess;
- self.absolute = !!options.absolute;
- self.fs = options.fs || fs__default['default'];
-
- self.maxLength = options.maxLength || Infinity;
- self.cache = options.cache || Object.create(null);
- self.statCache = options.statCache || Object.create(null);
- self.symlinks = options.symlinks || Object.create(null);
-
- setupIgnores(self, options);
-
- self.changedCwd = false;
- var cwd = process.cwd();
- if (!ownProp$2(options, "cwd"))
- self.cwd = cwd;
- else {
- self.cwd = path__default['default'].resolve(options.cwd);
- self.changedCwd = self.cwd !== cwd;
- }
-
- self.root = options.root || path__default['default'].resolve(self.cwd, "/");
- self.root = path__default['default'].resolve(self.root);
- if (process.platform === "win32")
- self.root = self.root.replace(/\\/g, "/");
-
- // TODO: is an absolute `cwd` supposed to be resolved against `root`?
- // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
- self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
- if (process.platform === "win32")
- self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
- self.nomount = !!options.nomount;
-
- // disable comments and negation in Minimatch.
- // Note that they are not supported in Glob itself anyway.
- options.nonegate = true;
- options.nocomment = true;
-
- self.minimatch = new Minimatch(pattern, options);
- self.options = self.minimatch.options;
- }
-
- function finish (self) {
- var nou = self.nounique;
- var all = nou ? [] : Object.create(null);
-
- for (var i = 0, l = self.matches.length; i < l; i ++) {
- var matches = self.matches[i];
- if (!matches || Object.keys(matches).length === 0) {
- if (self.nonull) {
- // do like the shell, and spit out the literal glob
- var literal = self.minimatch.globSet[i];
- if (nou)
- all.push(literal);
- else
- all[literal] = true;
- }
- } else {
- // had matches
- var m = Object.keys(matches);
- if (nou)
- all.push.apply(all, m);
- else
- m.forEach(function (m) {
- all[m] = true;
- });
- }
- }
-
- if (!nou)
- all = Object.keys(all);
-
- if (!self.nosort)
- all = all.sort(alphasort);
-
- // at *some* point we statted all of these
- if (self.mark) {
- for (var i = 0; i < all.length; i++) {
- all[i] = self._mark(all[i]);
- }
- if (self.nodir) {
- all = all.filter(function (e) {
- var notDir = !(/\/$/.test(e));
- var c = self.cache[e] || self.cache[makeAbs(self, e)];
- if (notDir && c)
- notDir = c !== 'DIR' && !Array.isArray(c);
- return notDir
- });
- }
- }
-
- if (self.ignore.length)
- all = all.filter(function(m) {
- return !isIgnored$2(self, m)
- });
-
- self.found = all;
- }
-
- function mark (self, p) {
- var abs = makeAbs(self, p);
- var c = self.cache[abs];
- var m = p;
- if (c) {
- var isDir = c === 'DIR' || Array.isArray(c);
- var slash = p.slice(-1) === '/';
-
- if (isDir && !slash)
- m += '/';
- else if (!isDir && slash)
- m = m.slice(0, -1);
-
- if (m !== p) {
- var mabs = makeAbs(self, m);
- self.statCache[mabs] = self.statCache[abs];
- self.cache[mabs] = self.cache[abs];
- }
- }
-
- return m
- }
-
- // lotta situps...
- function makeAbs (self, f) {
- var abs = f;
- if (f.charAt(0) === '/') {
- abs = path__default['default'].join(self.root, f);
- } else if (pathIsAbsolute(f) || f === '') {
- abs = f;
- } else if (self.changedCwd) {
- abs = path__default['default'].resolve(self.cwd, f);
- } else {
- abs = path__default['default'].resolve(f);
- }
-
- if (process.platform === 'win32')
- abs = abs.replace(/\\/g, '/');
-
- return abs
- }
-
-
- // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
- // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
- function isIgnored$2 (self, path) {
- if (!self.ignore.length)
- return false
-
- return self.ignore.some(function(item) {
- return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
- })
- }
-
- function childrenIgnored$2 (self, path) {
- if (!self.ignore.length)
- return false
-
- return self.ignore.some(function(item) {
- return !!(item.gmatcher && item.gmatcher.match(path))
- })
- }
-
- var common = {
- setopts: setopts_1,
- ownProp: ownProp_1,
- makeAbs: makeAbs_1,
- finish: finish_1,
- mark: mark_1,
- isIgnored: isIgnored_1,
- childrenIgnored: childrenIgnored_1
- };
-
- var require$$1 = glob_1;
-
- var sync = globSync;
- globSync.GlobSync = GlobSync$1;
- require$$1.Glob;
-
-
-
-
-
- var setopts$1 = common.setopts;
- var ownProp$1 = common.ownProp;
- var childrenIgnored$1 = common.childrenIgnored;
- var isIgnored$1 = common.isIgnored;
-
- function globSync (pattern, options) {
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
-
- return new GlobSync$1(pattern, options).found
- }
-
- function GlobSync$1 (pattern, options) {
- if (!pattern)
- throw new Error('must provide pattern')
-
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
-
- if (!(this instanceof GlobSync$1))
- return new GlobSync$1(pattern, options)
-
- setopts$1(this, pattern, options);
-
- if (this.noprocess)
- return this
-
- var n = this.minimatch.set.length;
- this.matches = new Array(n);
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false);
- }
- this._finish();
- }
-
- GlobSync$1.prototype._finish = function () {
- assert__default['default'](this instanceof GlobSync$1);
- if (this.realpath) {
- var self = this;
- this.matches.forEach(function (matchset, index) {
- var set = self.matches[index] = Object.create(null);
- for (var p in matchset) {
- try {
- p = self._makeAbs(p);
- var real = fs_realpath.realpathSync(p, self.realpathCache);
- set[real] = true;
- } catch (er) {
- if (er.syscall === 'stat')
- set[self._makeAbs(p)] = true;
- else
- throw er
- }
- }
- });
- }
- common.finish(this);
- };
-
-
- GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
- assert__default['default'](this instanceof GlobSync$1);
-
- // Get the first [n] parts of pattern that are all strings.
- var n = 0;
- while (typeof pattern[n] === 'string') {
- n ++;
- }
- // now n is the index of the first one that is *not* a string.
-
- // See if there's anything else
- var prefix;
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index);
- return
-
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null;
- break
-
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/');
- break
- }
-
- var remain = pattern.slice(n);
-
- // get the list of entries.
- var read;
- if (prefix === null)
- read = '.';
- else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
- if (!prefix || !pathIsAbsolute(prefix))
- prefix = '/' + prefix;
- read = prefix;
- } else
- read = prefix;
-
- var abs = this._makeAbs(read);
-
- //if ignored, skip processing
- if (childrenIgnored$1(this, read))
- return
-
- var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
- };
-
-
- GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar);
-
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return
-
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0];
- var negate = !!this.minimatch.negate;
- var rawGlob = pn._glob;
- var dotOk = this.dot || rawGlob.charAt(0) === '.';
-
- var matchedEntries = [];
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (e.charAt(0) !== '.' || dotOk) {
- var m;
- if (negate && !prefix) {
- m = !e.match(pn);
- } else {
- m = e.match(pn);
- }
- if (m)
- matchedEntries.push(e);
- }
- }
-
- var len = matchedEntries.length;
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return
-
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
-
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null);
-
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i];
- if (prefix) {
- if (prefix.slice(-1) !== '/')
- e = prefix + '/' + e;
- else
- e = prefix + e;
- }
-
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path__default['default'].join(this.root, e);
- }
- this._emitMatch(index, e);
- }
- // This was the last one, and no stats were needed
- return
- }
-
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift();
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i];
- var newPattern;
- if (prefix)
- newPattern = [prefix, e];
- else
- newPattern = [e];
- this._process(newPattern.concat(remain), index, inGlobStar);
- }
- };
-
-
- GlobSync$1.prototype._emitMatch = function (index, e) {
- if (isIgnored$1(this, e))
- return
-
- var abs = this._makeAbs(e);
-
- if (this.mark)
- e = this._mark(e);
-
- if (this.absolute) {
- e = abs;
- }
-
- if (this.matches[index][e])
- return
-
- if (this.nodir) {
- var c = this.cache[abs];
- if (c === 'DIR' || Array.isArray(c))
- return
- }
-
- this.matches[index][e] = true;
-
- if (this.stat)
- this._stat(e);
- };
-
-
- GlobSync$1.prototype._readdirInGlobStar = function (abs) {
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false)
-
- var entries;
- var lstat;
- try {
- lstat = this.fs.lstatSync(abs);
- } catch (er) {
- if (er.code === 'ENOENT') {
- // lstat failed, doesn't exist
- return null
- }
- }
-
- var isSym = lstat && lstat.isSymbolicLink();
- this.symlinks[abs] = isSym;
-
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory())
- this.cache[abs] = 'FILE';
- else
- entries = this._readdir(abs, false);
-
- return entries
- };
-
- GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
-
- if (inGlobStar && !ownProp$1(this.symlinks, abs))
- return this._readdirInGlobStar(abs)
-
- if (ownProp$1(this.cache, abs)) {
- var c = this.cache[abs];
- if (!c || c === 'FILE')
- return null
-
- if (Array.isArray(c))
- return c
- }
-
- try {
- return this._readdirEntries(abs, this.fs.readdirSync(abs))
- } catch (er) {
- this._readdirError(abs, er);
- return null
- }
- };
-
- GlobSync$1.prototype._readdirEntries = function (abs, entries) {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i];
- if (abs === '/')
- e = abs + e;
- else
- e = abs + '/' + e;
- this.cache[e] = true;
- }
- }
-
- this.cache[abs] = entries;
-
- // mark and cache dir-ness
- return entries
- };
-
- GlobSync$1.prototype._readdirError = function (f, er) {
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f);
- this.cache[abs] = 'FILE';
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd);
- error.path = this.cwd;
- error.code = er.code;
- throw error
- }
- break
-
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false;
- break
-
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false;
- if (this.strict)
- throw er
- if (!this.silent)
- console.error('glob error', er);
- break
- }
- };
-
- GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
-
- var entries = this._readdir(abs, inGlobStar);
-
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return
-
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1);
- var gspref = prefix ? [ prefix ] : [];
- var noGlobStar = gspref.concat(remainWithoutGlobStar);
-
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false);
-
- var len = entries.length;
- var isSym = this.symlinks[abs];
-
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return
-
- for (var i = 0; i < len; i++) {
- var e = entries[i];
- if (e.charAt(0) === '.' && !this.dot)
- continue
-
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar);
- this._process(instead, index, true);
-
- var below = gspref.concat(entries[i], remain);
- this._process(below, index, true);
- }
- };
-
- GlobSync$1.prototype._processSimple = function (prefix, index) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var exists = this._stat(prefix);
-
- if (!this.matches[index])
- this.matches[index] = Object.create(null);
-
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return
-
- if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix);
- if (prefix.charAt(0) === '/') {
- prefix = path__default['default'].join(this.root, prefix);
- } else {
- prefix = path__default['default'].resolve(this.root, prefix);
- if (trail)
- prefix += '/';
- }
- }
-
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/');
-
- // Mark this as a match
- this._emitMatch(index, prefix);
- };
-
- // Returns either 'DIR', 'FILE', or false
- GlobSync$1.prototype._stat = function (f) {
- var abs = this._makeAbs(f);
- var needDir = f.slice(-1) === '/';
-
- if (f.length > this.maxLength)
- return false
-
- if (!this.stat && ownProp$1(this.cache, abs)) {
- var c = this.cache[abs];
-
- if (Array.isArray(c))
- c = 'DIR';
-
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return c
-
- if (needDir && c === 'FILE')
- return false
-
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
- var stat = this.statCache[abs];
- if (!stat) {
- var lstat;
- try {
- lstat = this.fs.lstatSync(abs);
- } catch (er) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false;
- return false
- }
- }
-
- if (lstat && lstat.isSymbolicLink()) {
- try {
- stat = this.fs.statSync(abs);
- } catch (er) {
- stat = lstat;
- }
- } else {
- stat = lstat;
- }
- }
-
- this.statCache[abs] = stat;
-
- var c = true;
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE';
-
- this.cache[abs] = this.cache[abs] || c;
-
- if (needDir && c === 'FILE')
- return false
-
- return c
- };
-
- GlobSync$1.prototype._mark = function (p) {
- return common.mark(this, p)
- };
-
- GlobSync$1.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
- };
-
- // Returns a wrapper function that returns a wrapped callback
- // The wrapper function should do some stuff, and return a
- // presumably different callback function.
- // This makes sure that own properties are retained, so that
- // decorations and such are not lost along the way.
- var wrappy_1 = wrappy;
- function wrappy (fn, cb) {
- if (fn && cb) return wrappy(fn)(cb)
-
- if (typeof fn !== 'function')
- throw new TypeError('need wrapper function')
-
- Object.keys(fn).forEach(function (k) {
- wrapper[k] = fn[k];
- });
-
- return wrapper
-
- function wrapper() {
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i];
- }
- var ret = fn.apply(this, args);
- var cb = args[args.length-1];
- if (typeof ret === 'function' && ret !== cb) {
- Object.keys(cb).forEach(function (k) {
- ret[k] = cb[k];
- });
- }
- return ret
- }
- }
-
- var once_1 = wrappy_1(once);
- var strict = wrappy_1(onceStrict);
-
- once.proto = once(function () {
- Object.defineProperty(Function.prototype, 'once', {
- value: function () {
- return once(this)
- },
- configurable: true
- });
-
- Object.defineProperty(Function.prototype, 'onceStrict', {
- value: function () {
- return onceStrict(this)
- },
- configurable: true
- });
- });
-
- function once (fn) {
- var f = function () {
- if (f.called) return f.value
- f.called = true;
- return f.value = fn.apply(this, arguments)
- };
- f.called = false;
- return f
- }
-
- function onceStrict (fn) {
- var f = function () {
- if (f.called)
- throw new Error(f.onceError)
- f.called = true;
- return f.value = fn.apply(this, arguments)
- };
- var name = fn.name || 'Function wrapped with `once`';
- f.onceError = name + " shouldn't be called more than once";
- f.called = false;
- return f
- }
- once_1.strict = strict;
-
- var reqs = Object.create(null);
-
-
- var inflight_1 = wrappy_1(inflight);
-
- function inflight (key, cb) {
- if (reqs[key]) {
- reqs[key].push(cb);
- return null
- } else {
- reqs[key] = [cb];
- return makeres(key)
- }
- }
-
- function makeres (key) {
- return once_1(function RES () {
- var cbs = reqs[key];
- var len = cbs.length;
- var args = slice(arguments);
-
- // XXX It's somewhat ambiguous whether a new callback added in this
- // pass should be queued for later execution if something in the
- // list of callbacks throws, or if it should just be discarded.
- // However, it's such an edge case that it hardly matters, and either
- // choice is likely as surprising as the other.
- // As it happens, we do go ahead and schedule it for later execution.
- try {
- for (var i = 0; i < len; i++) {
- cbs[i].apply(null, args);
- }
- } finally {
- if (cbs.length > len) {
- // added more in the interim.
- // de-zalgo, just in case, but don't call again.
- cbs.splice(0, len);
- process.nextTick(function () {
- RES.apply(null, args);
- });
- } else {
- delete reqs[key];
- }
- }
- })
- }
-
- function slice (args) {
- var length = args.length;
- var array = [];
-
- for (var i = 0; i < length; i++) array[i] = args[i];
- return array
- }
-
- // Approach:
- //
- // 1. Get the minimatch set
- // 2. For each pattern in the set, PROCESS(pattern, false)
- // 3. Store matches per-set, then uniq them
- //
- // PROCESS(pattern, inGlobStar)
- // Get the first [n] items from pattern that are all strings
- // Join these together. This is PREFIX.
- // If there is no more remaining, then stat(PREFIX) and
- // add to matches if it succeeds. END.
- //
- // If inGlobStar and PREFIX is symlink and points to dir
- // set ENTRIES = []
- // else readdir(PREFIX) as ENTRIES
- // If fail, END
- //
- // with ENTRIES
- // If pattern[n] is GLOBSTAR
- // // handle the case where the globstar match is empty
- // // by pruning it out, and testing the resulting pattern
- // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
- // // handle other cases.
- // for ENTRY in ENTRIES (not dotfiles)
- // // attach globstar + tail onto the entry
- // // Mark that this entry is a globstar match
- // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
- //
- // else // not globstar
- // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
- // Test ENTRY against pattern[n]
- // If fails, continue
- // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
- //
- // Caveat:
- // Cache all stats and readdirs results to minimize syscall. Since all
- // we ever care about is existence and directory-ness, we can just keep
- // `true` for files, and [children,...] for directories, or `false` for
- // things that don't exist.
-
- var glob_1 = glob;
-
- var EE = require$$0__default$1['default'].EventEmitter;
-
-
-
-
-
- var setopts = common.setopts;
- var ownProp = common.ownProp;
-
-
- var childrenIgnored = common.childrenIgnored;
- var isIgnored = common.isIgnored;
-
-
-
- function glob (pattern, options, cb) {
- if (typeof options === 'function') cb = options, options = {};
- if (!options) options = {};
-
- if (options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return sync(pattern, options)
- }
-
- return new Glob(pattern, options, cb)
- }
-
- glob.sync = sync;
- var GlobSync = glob.GlobSync = sync.GlobSync;
-
- // old api surface
- glob.glob = glob;
-
- function extend (origin, add) {
- if (add === null || typeof add !== 'object') {
- return origin
- }
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin
- }
-
- glob.hasMagic = function (pattern, options_) {
- var options = extend({}, options_);
- options.noprocess = true;
-
- var g = new Glob(pattern, options);
- var set = g.minimatch.set;
-
- if (!pattern)
- return false
-
- if (set.length > 1)
- return true
-
- for (var j = 0; j < set[0].length; j++) {
- if (typeof set[0][j] !== 'string')
- return true
- }
-
- return false
- };
-
- glob.Glob = Glob;
- inherits(Glob, EE);
- function Glob (pattern, options, cb) {
- if (typeof options === 'function') {
- cb = options;
- options = null;
- }
-
- if (options && options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return new GlobSync(pattern, options)
- }
-
- if (!(this instanceof Glob))
- return new Glob(pattern, options, cb)
-
- setopts(this, pattern, options);
- this._didRealPath = false;
-
- // process each pattern in the minimatch set
- var n = this.minimatch.set.length;
-
- // The matches are stored as {<filename>: true,...} so that
- // duplicates are automagically pruned.
- // Later, we do an Object.keys() on these.
- // Keep them as a list so we can fill in when nonull is set.
- this.matches = new Array(n);
-
- if (typeof cb === 'function') {
- cb = once_1(cb);
- this.on('error', cb);
- this.on('end', function (matches) {
- cb(null, matches);
- });
- }
-
- var self = this;
- this._processing = 0;
-
- this._emitQueue = [];
- this._processQueue = [];
- this.paused = false;
-
- if (this.noprocess)
- return this
-
- if (n === 0)
- return done()
-
- var sync = true;
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false, done);
- }
- sync = false;
-
- function done () {
- --self._processing;
- if (self._processing <= 0) {
- if (sync) {
- process.nextTick(function () {
- self._finish();
- });
- } else {
- self._finish();
- }
- }
- }
- }
-
- Glob.prototype._finish = function () {
- assert__default['default'](this instanceof Glob);
- if (this.aborted)
- return
-
- if (this.realpath && !this._didRealpath)
- return this._realpath()
-
- common.finish(this);
- this.emit('end', this.found);
- };
-
- Glob.prototype._realpath = function () {
- if (this._didRealpath)
- return
-
- this._didRealpath = true;
-
- var n = this.matches.length;
- if (n === 0)
- return this._finish()
-
- var self = this;
- for (var i = 0; i < this.matches.length; i++)
- this._realpathSet(i, next);
-
- function next () {
- if (--n === 0)
- self._finish();
- }
- };
-
- Glob.prototype._realpathSet = function (index, cb) {
- var matchset = this.matches[index];
- if (!matchset)
- return cb()
-
- var found = Object.keys(matchset);
- var self = this;
- var n = found.length;
-
- if (n === 0)
- return cb()
-
- var set = this.matches[index] = Object.create(null);
- found.forEach(function (p, i) {
- // If there's a problem with the stat, then it means that
- // one or more of the links in the realpath couldn't be
- // resolved. just return the abs value in that case.
- p = self._makeAbs(p);
- fs_realpath.realpath(p, self.realpathCache, function (er, real) {
- if (!er)
- set[real] = true;
- else if (er.syscall === 'stat')
- set[p] = true;
- else
- self.emit('error', er); // srsly wtf right here
-
- if (--n === 0) {
- self.matches[index] = set;
- cb();
- }
- });
- });
- };
-
- Glob.prototype._mark = function (p) {
- return common.mark(this, p)
- };
-
- Glob.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
- };
-
- Glob.prototype.abort = function () {
- this.aborted = true;
- this.emit('abort');
- };
-
- Glob.prototype.pause = function () {
- if (!this.paused) {
- this.paused = true;
- this.emit('pause');
- }
- };
-
- Glob.prototype.resume = function () {
- if (this.paused) {
- this.emit('resume');
- this.paused = false;
- if (this._emitQueue.length) {
- var eq = this._emitQueue.slice(0);
- this._emitQueue.length = 0;
- for (var i = 0; i < eq.length; i ++) {
- var e = eq[i];
- this._emitMatch(e[0], e[1]);
- }
- }
- if (this._processQueue.length) {
- var pq = this._processQueue.slice(0);
- this._processQueue.length = 0;
- for (var i = 0; i < pq.length; i ++) {
- var p = pq[i];
- this._processing--;
- this._process(p[0], p[1], p[2], p[3]);
- }
- }
- }
- };
-
- Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
- assert__default['default'](this instanceof Glob);
- assert__default['default'](typeof cb === 'function');
-
- if (this.aborted)
- return
-
- this._processing++;
- if (this.paused) {
- this._processQueue.push([pattern, index, inGlobStar, cb]);
- return
- }
-
- //console.error('PROCESS %d', this._processing, pattern)
-
- // Get the first [n] parts of pattern that are all strings.
- var n = 0;
- while (typeof pattern[n] === 'string') {
- n ++;
- }
- // now n is the index of the first one that is *not* a string.
-
- // see if there's anything else
- var prefix;
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index, cb);
- return
-
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null;
- break
-
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/');
- break
- }
-
- var remain = pattern.slice(n);
-
- // get the list of entries.
- var read;
- if (prefix === null)
- read = '.';
- else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
- if (!prefix || !pathIsAbsolute(prefix))
- prefix = '/' + prefix;
- read = prefix;
- } else
- read = prefix;
-
- var abs = this._makeAbs(read);
-
- //if ignored, skip _processing
- if (childrenIgnored(this, read))
- return cb()
-
- var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
- };
-
- Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this;
- this._readdir(abs, inGlobStar, function (er, entries) {
- return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- });
- };
-
- Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
-
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return cb()
-
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0];
- var negate = !!this.minimatch.negate;
- var rawGlob = pn._glob;
- var dotOk = this.dot || rawGlob.charAt(0) === '.';
-
- var matchedEntries = [];
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (e.charAt(0) !== '.' || dotOk) {
- var m;
- if (negate && !prefix) {
- m = !e.match(pn);
- } else {
- m = e.match(pn);
- }
- if (m)
- matchedEntries.push(e);
- }
- }
-
- //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
-
- var len = matchedEntries.length;
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return cb()
-
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
-
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null);
-
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i];
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e;
- else
- e = prefix + e;
- }
-
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path__default['default'].join(this.root, e);
- }
- this._emitMatch(index, e);
- }
- // This was the last one, and no stats were needed
- return cb()
- }
-
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift();
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i];
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e;
- else
- e = prefix + e;
- }
- this._process([e].concat(remain), index, inGlobStar, cb);
- }
- cb();
- };
-
- Glob.prototype._emitMatch = function (index, e) {
- if (this.aborted)
- return
-
- if (isIgnored(this, e))
- return
-
- if (this.paused) {
- this._emitQueue.push([index, e]);
- return
- }
-
- var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
-
- if (this.mark)
- e = this._mark(e);
-
- if (this.absolute)
- e = abs;
-
- if (this.matches[index][e])
- return
-
- if (this.nodir) {
- var c = this.cache[abs];
- if (c === 'DIR' || Array.isArray(c))
- return
- }
-
- this.matches[index][e] = true;
-
- var st = this.statCache[abs];
- if (st)
- this.emit('stat', e, st);
-
- this.emit('match', e);
- };
-
- Glob.prototype._readdirInGlobStar = function (abs, cb) {
- if (this.aborted)
- return
-
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false, cb)
-
- var lstatkey = 'lstat\0' + abs;
- var self = this;
- var lstatcb = inflight_1(lstatkey, lstatcb_);
-
- if (lstatcb)
- self.fs.lstat(abs, lstatcb);
-
- function lstatcb_ (er, lstat) {
- if (er && er.code === 'ENOENT')
- return cb()
-
- var isSym = lstat && lstat.isSymbolicLink();
- self.symlinks[abs] = isSym;
-
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory()) {
- self.cache[abs] = 'FILE';
- cb();
- } else
- self._readdir(abs, false, cb);
- }
- };
-
- Glob.prototype._readdir = function (abs, inGlobStar, cb) {
- if (this.aborted)
- return
-
- cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
- if (!cb)
- return
-
- //console.error('RD %j %j', +inGlobStar, abs)
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs, cb)
-
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs];
- if (!c || c === 'FILE')
- return cb()
-
- if (Array.isArray(c))
- return cb(null, c)
- }
-
- var self = this;
- self.fs.readdir(abs, readdirCb(this, abs, cb));
- };
-
- function readdirCb (self, abs, cb) {
- return function (er, entries) {
- if (er)
- self._readdirError(abs, er, cb);
- else
- self._readdirEntries(abs, entries, cb);
- }
- }
-
- Glob.prototype._readdirEntries = function (abs, entries, cb) {
- if (this.aborted)
- return
-
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i];
- if (abs === '/')
- e = abs + e;
- else
- e = abs + '/' + e;
- this.cache[e] = true;
- }
- }
-
- this.cache[abs] = entries;
- return cb(null, entries)
- };
-
- Glob.prototype._readdirError = function (f, er, cb) {
- if (this.aborted)
- return
-
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f);
- this.cache[abs] = 'FILE';
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd);
- error.path = this.cwd;
- error.code = er.code;
- this.emit('error', error);
- this.abort();
- }
- break
-
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false;
- break
-
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false;
- if (this.strict) {
- this.emit('error', er);
- // If the error is handled, then we abort
- // if not, we threw out of here
- this.abort();
- }
- if (!this.silent)
- console.error('glob error', er);
- break
- }
-
- return cb()
- };
-
- Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this;
- this._readdir(abs, inGlobStar, function (er, entries) {
- self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
- });
- };
-
-
- Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- //console.error('pgs2', prefix, remain[0], entries)
-
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return cb()
-
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1);
- var gspref = prefix ? [ prefix ] : [];
- var noGlobStar = gspref.concat(remainWithoutGlobStar);
-
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false, cb);
-
- var isSym = this.symlinks[abs];
- var len = entries.length;
-
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return cb()
-
- for (var i = 0; i < len; i++) {
- var e = entries[i];
- if (e.charAt(0) === '.' && !this.dot)
- continue
-
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar);
- this._process(instead, index, true, cb);
-
- var below = gspref.concat(entries[i], remain);
- this._process(below, index, true, cb);
- }
-
- cb();
- };
-
- Glob.prototype._processSimple = function (prefix, index, cb) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var self = this;
- this._stat(prefix, function (er, exists) {
- self._processSimple2(prefix, index, er, exists, cb);
- });
- };
- Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
-
- //console.error('ps2', prefix, exists)
-
- if (!this.matches[index])
- this.matches[index] = Object.create(null);
-
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return cb()
-
- if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix);
- if (prefix.charAt(0) === '/') {
- prefix = path__default['default'].join(this.root, prefix);
- } else {
- prefix = path__default['default'].resolve(this.root, prefix);
- if (trail)
- prefix += '/';
- }
- }
-
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/');
-
- // Mark this as a match
- this._emitMatch(index, prefix);
- cb();
- };
-
- // Returns either 'DIR', 'FILE', or false
- Glob.prototype._stat = function (f, cb) {
- var abs = this._makeAbs(f);
- var needDir = f.slice(-1) === '/';
-
- if (f.length > this.maxLength)
- return cb()
-
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs];
-
- if (Array.isArray(c))
- c = 'DIR';
-
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return cb(null, c)
-
- if (needDir && c === 'FILE')
- return cb()
-
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
- var stat = this.statCache[abs];
- if (stat !== undefined) {
- if (stat === false)
- return cb(null, stat)
- else {
- var type = stat.isDirectory() ? 'DIR' : 'FILE';
- if (needDir && type === 'FILE')
- return cb()
- else
- return cb(null, type, stat)
- }
- }
-
- var self = this;
- var statcb = inflight_1('stat\0' + abs, lstatcb_);
- if (statcb)
- self.fs.lstat(abs, statcb);
-
- function lstatcb_ (er, lstat) {
- if (lstat && lstat.isSymbolicLink()) {
- // If it's a symlink, then treat it as the target, unless
- // the target does not exist, then treat it as a file.
- return self.fs.stat(abs, function (er, stat) {
- if (er)
- self._stat2(f, abs, null, lstat, cb);
- else
- self._stat2(f, abs, er, stat, cb);
- })
- } else {
- self._stat2(f, abs, er, lstat, cb);
- }
- }
- };
-
- Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false;
- return cb()
- }
-
- var needDir = f.slice(-1) === '/';
- this.statCache[abs] = stat;
-
- if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
- return cb(null, false, stat)
-
- var c = true;
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE';
- this.cache[abs] = this.cache[abs] || c;
-
- if (needDir && c === 'FILE')
- return cb()
-
- return cb(null, c, stat)
- };
-
- var spawn = childProcess__default['default'].spawn;
- var exec = childProcess__default['default'].exec;
-
- var treeKill = function (pid, signal, callback) {
- if (typeof signal === 'function' && callback === undefined) {
- callback = signal;
- signal = undefined;
- }
-
- pid = parseInt(pid);
- if (Number.isNaN(pid)) {
- if (callback) {
- return callback(new Error("pid must be a number"));
- } else {
- throw new Error("pid must be a number");
- }
- }
-
- var tree = {};
- var pidsToProcess = {};
- tree[pid] = [];
- pidsToProcess[pid] = 1;
-
- switch (process.platform) {
- case 'win32':
- exec('taskkill /pid ' + pid + ' /T /F', callback);
- break;
- case 'darwin':
- buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
- return spawn('pgrep', ['-P', parentPid]);
- }, function () {
- killAll(tree, signal, callback);
- });
- break;
- // case 'sunos':
- // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
- // killAll(tree, signal, callback);
- // });
- // break;
- default: // Linux
- buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
- return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
- }, function () {
- killAll(tree, signal, callback);
- });
- break;
- }
- };
-
- function killAll (tree, signal, callback) {
- var killed = {};
- try {
- Object.keys(tree).forEach(function (pid) {
- tree[pid].forEach(function (pidpid) {
- if (!killed[pidpid]) {
- killPid(pidpid, signal);
- killed[pidpid] = 1;
- }
- });
- if (!killed[pid]) {
- killPid(pid, signal);
- killed[pid] = 1;
- }
- });
- } catch (err) {
- if (callback) {
- return callback(err);
- } else {
- throw err;
- }
- }
- if (callback) {
- return callback();
- }
- }
-
- function killPid(pid, signal) {
- try {
- process.kill(parseInt(pid, 10), signal);
- }
- catch (err) {
- if (err.code !== 'ESRCH') throw err;
- }
- }
-
- function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
- var ps = spawnChildProcessesList(parentPid);
- var allData = '';
- ps.stdout.on('data', function (data) {
- var data = data.toString('ascii');
- allData += data;
- });
-
- var onClose = function (code) {
- delete pidsToProcess[parentPid];
-
- if (code != 0) {
- // no more parent processes
- if (Object.keys(pidsToProcess).length == 0) {
- cb();
- }
- return;
- }
-
- allData.match(/\d+/g).forEach(function (pid) {
- pid = parseInt(pid, 10);
- tree[parentPid].push(pid);
- tree[pid] = [];
- pidsToProcess[pid] = 1;
- buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
- });
- };
-
- ps.on('close', onClose);
- }
-
- var any = bbhverse.any;
- var Tasq = bbhverse.Tasq;
- var statuslog = bbhverse.Traq;
- var Traq = bbhverse.Traq;
- Tasq.addlistener(statuslog.statuslog);
-
- var nodeShellExec = cliverse.nodeShellExec;
-
-
-
- const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
- const BUILD_VERSION = 'Version: 1.0.0 - built on September 29, 2021 19:31:21';
- const runtimestamp = (new Date()).getTime();
- function getVersion() { return BUILD_VERSION; }
- console.log(getVersion());
-
-
-
- // 'use strict';
-
- // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
-
- // PB : TODO --
- // runas bypass non elevated tasks when we request privelege
- // runas message is always error needs to be fixed.
- // runas wait needs to be parallelized.
- // suppress elevation check error messages
- // support runas lauched directly from shell.
- // pass in environment in hta to shellexecute.
-
- // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
- (function () {
- if (!Array.prototype.earlyreduce) {
- Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
- var iterable = this;
- var donecallback = donecallback || (a=>a);
- var result = { value : initialValue === undefined ? iterable[0] : initialValue };
- initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
- // function *earlyReduceGenerator(acc, v, i, a) {
- for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
- var element = iterable[i];
- result = eachcallback(result, element, i, iterable);
- if(result.done) return donecallback(result)
- }
- // }
- return donecallback(result)
- };
- }
- }());
-
- const { existsSync } = fs__default['default'];
- const existsFolderSync = existsSync;
- const fs = fs__default['default'];
-
- const cliargs = bbhverse.cliargs;
- const processedArgs = cliargs(process.argv.slice(2));
- console.dir(processedArgs);
- // PB : TODO -- defaults for valuless arguments if passed.
- // Object.keys(processedArgs).forEach(a=>{
- // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
-
- // }
- // })
-
- var clioverrides = { };
- processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
- processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
- : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
- ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
-
- Object.keys(clioverrides).forEach( prop => { });
-
- require$$1.sync;
-
- var ENV = Object.assign({}, process.env); // Shallow clone it.
-
- const { readdir } = fs__default['default'].promises;
-
- // Directory shallow walk and do perform on each dir.
- const dirs = async (perform, path) => {
- for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
- if (dir.isDirectory()) perform(dir);
- }
- };
-
- var getShellTask = (command, args, options) => {
- options = options || {};
- var callshell = command === 'rm' ? callgitbashtask : callsheltask;
- return () => {
- var p = callshell( [command, args, Object.assign({
- inherit: true, shell: true, env: ENV, title: `${command} ${args}`
- }, options)
- ]);
- if (options.ignorefailures) {
- return p.catch(e => {
- // Ignore. Not a major error.
- })
- }
- else return p;
- }
- };
-
- var callsheltask = (args) => {
- return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } };
- var callgitbashtask = (args) => { return () => {
- return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
- };
-
- var getTaskCheckExists = (command, options) => {
- options = options || {};
- return () => {
- var p = nodeShellExec.apply(null, ['where', [command]]);
- if (options.ignorefailures) {
- return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
- return false;
- })
- }
- else return p.then(() => { return true });
- }
- };
-
- var getTaskWithElevation = function(tasdef){
- return ()=>{
- if (__isElevated) {
- return tasdef.elevatedpulltasks().then(()=>{
- // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
- fs.writeFileSync('run.done', 'success');
- }).catch(e=>{
- fs.writeFileSync('run.done', 'failure');
- });
- }
- else {
- // PB : TODO -- Rename op['runas'] to 'elevate'
-
- var __runasresult = null;
-
- return op['runas']().then((r) => { return __runasresult = r; })
- .catch((e) => {
- console.error(e);
- })
- .finally(() => {
- if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
- if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
- })
- }
- }
- };
-
- var getTaskWithoutElevation = function(tasdef){
- return ()=>{
- if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
- else Promise.resolve(true);
- }
- };
-
- var gitops = {
-
- getdiscoverbranchcmd : function(repo){
-
- var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
- var cmd = [gitbash
- , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
- return cmd
- }
- };
-
- var getPullCmd = (repo, branch) => {
- // console.log(useGitPull)var getPullCmd = (repo, branch) => {
- // console.log(useGitPull)
-
- // var pullCmd = [gitInstallDir
- // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
- if(branch) {
- var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
- var pullCmd = [ gitbash
- , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
- }
- else {
- // console.warn('No branch was specified detecting from working client.')
- // First check if working client exits.
- // if (existsSync(instanceroot + '/' + repo)) {
- var pullCmd = gitops.getdiscoverbranchcmd(repo);
- // }
- // else performpull
- }
- // var pullCmd = ['pullall', [], { cwd : repo }]
- if (useGitPull) pullCmd = ['git', ['pull'], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + repo
- // , env: process.env
- , runas: processedArgs.runas
- , title: `git pull ${repo}`
- }];
- return pullCmd
- };
-
- var performPull = (repo, branch) => {
- // PB : TODO -- Handle no branch passed in case.
- // if(!branch) { throw 'No branch specified' }
-
- if (existsSync(instanceroot + '/' + repo)) {
- var branchprint = branch ? ' branch :' + branch : '';
- console.log('pulling ' + instanceroot + '/' + repo + branchprint );
- return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
- }
- else statuslog.statuslog(null, repo);
- return true;
- })
- .catch((e) => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
- }
- else statuslog.statuslog(e); console.error(e);
- })
- }
- else {
- console.log('cloning ' + repo);
- // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
- return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd : instanceroot
- , runas: processedArgs.runas
- }).catch((e) => {
- throw e;
- }).then(() => {
-
- return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
- {
- inherit: true, shell: true,
- env: process.env
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
- })
- .then(() => {
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
- }
- else statuslog.statuslog(null, repo);
- })
- .catch((e) => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
- }
- else statuslog.statuslog(e);
- })
- })
- .catch(e => {
- e.repo = repo;
- if (__isElevated) {
- fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
- }
- else statuslog.statuslog(e);
- })
- }
- };
-
- // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
- // -- Currently workaround is to always run from a non-elevated shell.
- var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
- var acquireElevationState = () => {
- if (__isElevated === null) {
- return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
- inherit: true
- // , shell: true
- , stdio: 'ignore'
- , env: process.env
- , title: `check privileged execution mode using "fsutil dirty query C:"`
- }).then((exitcode) => {
- console.log('Elevated');
- __isElevated = true;
- return true;
- }).catch(() => {
- __isElevated = false;
- console.log('Not Elevated');
- return false;
- });
- }
- else return Promise.resolve(__isElevated);
- };
- var defaultRepoOwner = 'chess';
- var elevatedRunasRepos = null;
- var gitRepos = null;
-
- // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
-
-
- // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
-
- var dbForLabel = function (label) {
- var dbsForLabel = {
- devmysql: 'mysql'
- , development: 'mssql'
- , production: 'mssql'
- };
- return dbsForLabel[label] || 'mysql'
- };
-
- // SAM : TODO Use nodeshellexec where to detect git installation dir
- var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
- // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
- // Relevant git repos
- var exludeMergeRepos = [];
- var useGitPull = processedArgs.useGitPull || false;
-
- // elxr cli operations
- var op = {
- 'h': () => { console.log(elxr.help()); return '-h' }
- , 'clean' : () => {
- // delete all node_module folders and links.
- var tasklist = [];
- dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
- return Promise.all(tasklist)
- }
- , 'undefined': () => { return op.h(); }
- , 'reset': () => {
-
- // Reset NPM packages semver so major versions can be updated.
-
- const fs = fs__default['default'];
- const wipeDependencies = (__package) => {
- const file = fs.readFileSync(__package + '/package.json');
- const content = JSON.parse(file);
- for (var devDep in content.devDependencies) {
- if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.devDependencies[devDep] = '*';
- }
- }
- for (var dep in content.dependencies) {
- if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.dependencies[dep] = '*';
- }
- }
- fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
- };
-
- var repos = ['client'];
- // repos = gitRepos;
- repos.forEach(wipeDependencies);
- // if (require.main === module) {
- // } else {
- // module.exports = wipeDependencies
- // }
-
- }
- , 'upgrade': () => {
- console.log('upgrade.......');
- var tasks = [
- () => {
- var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 1;
- console.log('One');
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
-
- p.position = 2;
- console.log('Two');
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['install', '-g', 'n'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 3;
- console.log('Three');
- return p;
- }
- , () => {
- var p = nodeShellExec('n', ['latest'], {
- inherit: true, shell: true
- , env: process.env
- }).catch((e) => { console.error(e); });
- p.position = 4;
- console.log('Four');
- return p;
- }
- ];
- any(tasks);
- console.log('.......done');
- console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
- console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
- console.info('Uninstalling existing ember globally');
- var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path__default['default'].dirname(__dirname),
- env: env
- });
- step1.on('close', () => {
- console.info('Installing ember globally');
- var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path__default['default'].dirname(__dirname),
- env: env
- });
-
- step2.on('close', () => {
- nodeShellExec('cmd', ['/c', 'ember', '--version'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path__default['default'].dirname(__dirname),
- env: env
- });
- });
- });
- }
- , 'runas': () => {
-
- if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
-
- console.log('Testing Elevation');
-
- if (__isElevated) {
- try {
- op[processedArgs.label || processedArgs._[0] || 'h']();
- }
- catch (e) {
- console.error('Error Invalid command : ' + e);
- fs.writeFileSync('run.done', 'error');
- }
- finally {
- }
- }
- else {
- console.log('Requesting Elevated Privileges');
- // Wait for the runas to complete before we read it.
- try {
- fs.unlinkSync('run.done');
- fs.unlinkSync('run.log');
- }
- catch (e) { } //Ignore
-
- // Find node path to send to hta.
- return nodeShellExec('where', ['node']).then(r => {
- var namedArgs = [];
- console.log('result : ' + JSON.stringify(r));
- Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
- // PB : TODO -- Convert all the cli args back to string.
- var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
- // args.push('--nodepath=' + r.messages[r.messages.length - 1])
- // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
- // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
- console.dir(processedArgs);
-
- return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
- , {
- inherit: true
- , shell: true
- , env: ENV
- , runas: 'self'
- , title: `runas`
- }
- ).then(() => {
- // runas returned.
- try {
- // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
- var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
- runaslog.forEach((logEntry) => {
- statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
- logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
- });
- }
- catch (e) {
- // We must have a runas log
- statuslog.statuslog(e);
- console.error('Run log error probably was not created by runas : ' + e);
- }
- })
- .catch(err => console.error('Elevation failed : ' + err));
- })
-
- }
- }
- , 'push': () => {
- if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
- // init remote bare from local
- // pushandinitremotebare
- // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
- // connect to repo server -- net use 172.16.0.27
- // cd 172.16.0.27/repos/
- // mkdir repo.git
- // cd repo.git
- // git init --bare
- // cd localrepo
- // git remote rename origin githubclone
- // git remote add origin //172.16.0.27/repos/repo.git
- // git push origin master
-
- var repo = processedArgs._[1];
-
- var sequentialTaskShellCommands = [];
- if (!existsSync(`Z:/${repo}.git`)) {
- sequentialTaskShellCommands = [
- // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
- // inherit : true, shell: true
- // , env: process.env
- // }]
- ['pwd', { cwd: 'Z:', inherit: true }]
- , ['mkdir', [`${repo}.git`], {
- cwd: `Z:`
- , inherit: true, shell: true
- , env: process.env
- }]
- , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
- , ['git', ['init', '--bare'], {
- cwd: `Z:/${repo}.git`
- , inherit: true, shell: true
- , env: process.env
- }]
- // PB : TODO -- Do this conditionally only...
- , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
- console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
- }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
- , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
- // PB : TODO -- If threre is a gitbubclone origin
- // Set the master to pull from the local repo.
- ];
- if (!existsSync(`Z:`)) {
- sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
- inherit: true, shell: true
- , env: process.env
- }]);
- console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
- // throw 'done'
- }
- }
-
- sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
- // console.dir(sequentialTaskShellCommands);
-
- var tasks = [];
- sequentialTaskShellCommands.forEach(shellcmd => {
- // console.log(shellcmd)
- tasks.push(() => {
-
- var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
- return p;
- });
- });
- any(tasks);
-
- }
- , 'is-git-repo': (dir) => {
- return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
- }
- // git remote equivalents...
- // git branch --set-upstream-to=elixir-unc/master master
- // git push --set-upstream elixir-unc branch..
- , 'remote': (args) => {
-
- // Subcommands!
- if(!processedArgs.v) return false; // Only -v is supported presently..
-
- var serial_perform = (repo) => {
- var options = { cwd: instanceroot + '/' + repo };
-
- return [
- ['git', ['remote', '-v'], options]
- ]
- };
-
- var x = (args) => {
- var tasq = () => {
- // console.log(args)
- return nodeShellExec.apply(null, args).catch(e => {
- // We continue on failure.
- console.error(tasq.toString());
- })
- };
- tasq.toString = function(){
- return JSON.stringify(args)
- };
- return tasq;
- };
-
- var perform = (dir) => {
- return any(serial_perform(dir.name).map(x))
- };
-
- dirs(perform);
- }
-
- , 'remote set-url': (args) => {
- // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
- var __args = {
- remotename : args.remotename || processedArgs._[2]
- , url : args.url || processedArgs._[3]
- };
-
- // pushable doesn't mean the remote doesn't support being pushed to.
- // 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.
- // PB : TODO -- change this to enablepushing.
- // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
- var pushable = processedArgs.pushable || false;
- remotename = __args.remotename;
- url = __args.url;
- var serial_perform_git_seturl = (repo) => {
- // console.log(repo)
- if (pushable) {
- return [
- ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- ]
- }
- else {
- return [
- ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- };
-
- var x = (args) => {
- var tasq = () => {
- // console.log(args)
- return nodeShellExec.apply(null, args).catch(e => {
- // We continue on failure.
- console.error(tasq.toString());
- })
- };
- tasq.toString = function(){
- return JSON.stringify(args)
- };
- return tasq;
- };
- var perform_git_seturl = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- return any(serial_perform_git_seturl(dir.name).map(x))
- }).catch((e) => {
- // console.log('Failed : ' + dir.name)
- });
- };
-
- dirs(perform_git_seturl);
- }
- , 'reset' : ()=>{
- // Reset the whole installation pertaining to this elxr folder.
-
- }
- , 'remote add': (args) => {
- // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
- // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
- // That explicitly has a remote name prefix.
- // git branch branch_name --set-upstream-to your_new_remote/branch_name
- // git branch branch_name -u your_new_remote/branch_name -- older versions
- // git branch -vv -- Detect which branch are we tracking.
- // default upstream should be users own fork.
- // Also need alias branches to
- // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
- // probably git merge from all remotes... and relevant branches...
- // alias pushall='for i in `git remote`; do git push $i; done;'
- // alias pullall='for i in `git remote`; do git pull $i; done;'
- // args === processedArgs ? args = {} : null;
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- };
-
- var remotename = __args.remotename;
- var url = __args.url;
- var branch = __args.branch;
-
- var pushable = processedArgs.pushable || false;
-
-
- var serial_perform_git_add = (repo) => {
- // console.log(repo)
- if (pushable) {
- return [
- ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
- , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
- ]
- }
- else {
-
- return [
- ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
- , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- };
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- };
- var perform_git_add = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
- })
- .catch((e) => {
- any(serial_perform_git_add(dir.name).map(x));
- });
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- console.log('Failed : ' + dir.name);
- });
- };
-
- fs__default['default'].promises;
-
- dirs(perform_git_add);
- }
- , 'remote remove': (args) => {
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- };
- var remotename = __args.remotename;
- var serial_perform_git_remove = (repo) => {
- // console.log(repo)
- return [
- ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
- ]
- };
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- };
- var perform_git_remove = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- any(serial_perform_git_remove(dir.name).map(x));
- })
- .catch((e) => {
- console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
- });
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- // console.log('Failed : ' + dir.name)
- });
- };
-
- fs__default['default'].promises;
-
- dirs(perform_git_remove);
- }
- , 'init-gitea': (user) => {
- user = user || processedArgs._[1];
- if (!user) throw 'User name required'
- var serial_perform_init_gitea = (repo) => {
- // console.log(repo)
- return [
- ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- ]
- };
- var x = (args) => {
- return () => {
- // console.log(args)
- return nodeShellExec.apply(null, args)
- }
- // return Promise.resolve(true)
- };
- var perform_init_gitea = (dir) => {
- op['is-git-repo'](dir).then((logEntry) => {
- // console.log(code)
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
- })
- .catch((e) => {
- any(serial_perform_init_gitea(dir.name).map(x));
- });
- }
- // else console.log('Skipped : Not a Git Repo : ' + dir.name)
- }).catch((e) => {
- // console.log('Failed : ' + dir.name)
- });
- };
-
- fs__default['default'].promises;
-
- dirs(perform_init_gitea);
- }
- , 'syncmaster': (label) => {
- // Usage :
- // elxr pull -- Defaults to run config
-
- Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
-
- if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
- if (__isElevated) {
- return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- }
- else return op['runas']()
- }
-
- , 'repo-relocate' : function(args){
- // relocate a subfolder in source repo to same subfolder in target repo with history.
-
- var args = args || {
- remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
- , folder : processedArgs._[3] || 'server'
- , sourcerepo : processedArgs._[2] || 'client'
- , targetrepo : processedArgs._[1] || 'elixir-server'
- };
- var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- return op['repo-split'](args).then(()=>{
- return op['repo-merge'](args).then(()=>{
-
- // cleanup folder from source.
- var cmdseq = [
- ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
- // commits have to intentional...
- // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
- ];
-
- return any(cmdseq.map(callsheltask))
- })
- }).catch(e=>{console.error(e);})
- }
-
- , 'repo-split' : function(args) {
-
- // https://gist.github.com/smdabdoub/17065c348289158277b5
-
- /**
- * Eg : folder, remotebase, sourcerepo, targetrepo
- * args.folder = 'server'
- * args.remotebase = 'https://git.bbh/chess/'
- * args.sourcerepo = 'client'
- * args.targetrepo = 'elixir-server'
- */
-
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- };
-
- var options = { cwd: `${instanceroot}/relocate`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
- // create a temporary working dir in current folder where we started execution.
- ['mkdir', [ '-p', 'relocate']]
- , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
- , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
- , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
- ];
-
- return any(cmdseq.map(callsheltask)).then(() => {
- // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
- // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
- // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
- // , ['mkdir', [`${args.folder}`], sourcerepooptions]
- // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
- // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
-
-
- // subtree split and filter-branch are options. We currently use repo-filter.
- return op['filter-repo'](args)
- }).catch(e=>{console.error(e); throw 'failed'})
- }
-
- , 'repo-merge' : function(args) {
- // Merge source repo into target repo
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , sourcerepo : 'client'
- , targetrepo : 'elixir-server'
- };
-
- ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- });
- var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
- // , stdio: ['pipe', process.stdout, process.stderr]
- , inherit: true,
- shell: true,
- env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
- ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
- , targetrepooptions ]
- // , ['git', ['push', targetrepooptions ] // manual push for now..
- ];
- return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
- }
-
- , 'filter-repo' : function(args){
- // Merge source repo into target repo
- var args = args || {
- folder : 'server'
- , remotebase : 'http://git.bbh/chess/'
- , targetrepo : 'elixir-server'
- };
-
- var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
- , inherit: true, shell: true
- , env: process.env
- , runas: processedArgs.runas
- };
-
- var cmdseq = [
- // git checkout -b feature/merge-old-project
- // git remote add src-project ../src-project
- ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
- ];
- return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
- }
-
- , 'filter-branch' : function(preservefolder, repo){
- // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
- // git subtree split -P <name-of-folder> -b <name-of-new-branch>
- // Preserve a specific folder.
- // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
- /*
- git clone repo reposplit
- git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
- git remote rm origin
- */
-
- throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
- }
-
- // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
- // // Merge repo2 into a subfolder in repo1
- // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
- // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
- // /*
- // cd repo1
- // git remote add -f tempmergesource ../{{mergesource}}/.git
- // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
- // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
- // git commit
-
- // // Repair History
- // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
-
- // #!/usr/bin/env bash
-
- // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
- // last=038e26e21bd60fa265d6637261f3bc918780d2e8
- // subdir=server
-
- // git filter-branch --tree-filter '
- // first='"$first"'
- // last='"$last"'
-
- // subdir='"$subdir"'
- // log_file=/tmp/filter.log
-
- // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
-
- // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
- // echo "=== $GIT_COMMIT: making changes"
- // files=$(git ls-tree --name-only $GIT_COMMIT)
- // mkdir -p $subdir
- // for i in $files; do
- // mv $i $subdir || echo "ERR: mv $i $subdir failed"
- // done
- // else
- // echo "=== $GIT_COMMIT: ignoring"
- // fi \
- // >> $log_file
-
- // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
-
- // status=0 # tell tree-filter never to fail
- // '
-
- // git remote rm tempmergesource
- // */
- // // better alternative for history
- // /**
- // *
- // git clone git@server.com:old-project.git
- // git clone git@server.com:new-project.git
-
- // cd old-project
- // mkdir old-project
- // git mv !(old-project) old-project
- // ls -la and gt mv hidden files ....
- // git commit -a -S -m “Moving old project into its own subdirectory”
-
- // cd ../new-project
- // git remote add old-project ../old-project
- // git fetch old-project
- // git checkout -b feature/merge-old-project
- // git merge -S --allow-unrelated-histories old-project/master
- // git push origin feature/merge-old-project
- // git remote rm old-project
- // */
-
- // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
- // }
-
- , 'pull' : (label) => {
- // Usage :
- // elxr pull -- Defaults to run config
-
- return elxr.getpulltask(selectedinstance)()
- }
- , 'isInstalled': () => {
- return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
- console.log(processedArgs._[1] + ' exists.');
- return true;
- });
- }
- , 'i' : () => {
-
- var tasks = [];
- // tasks.push(op['pull']);
- tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
- tasks.push(op['use']);
- if (!__isElevated) {
- tasks.push(op['npmi']);
- }
-
- // var tasksdefs = [
- // ['elxr', ['pull']]
- // , ['elxr', ['use', 'elixir']]
- // , ['elxr', ['npmi']]
- // ]
-
-
- // tasksdefs.forEach(tasksdef=>{
- // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
- // })
-
- return any(tasks);
-
- }
- , 'npmi': () => {
- var tasks = [];
-
- // Build fails without babel...
- tasks.push(getShellTask(
- 'npm',[ 'i', '-g', 'babel-cli' ]
- ) );
-
- var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
- npmbuildrepos = [];
- npmbuildrepos.forEach(repo => {
- tasks.push(() => {
- return nodeShellExec('npm', ['i --force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: process.env
- , title: `npm i for ${repo}`
- }).catch((e) => {
- console.error('Ignoring Benign Error'); console.error(e);
- }).then(() => {
- console.log(`--npm run build for ${repo}--------------------`);
- return nodeShellExec('npm', ['run build'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: process.env
- , title: `npm run build for ${repo}`
- }).then(Tasq.then).catch(Tasq.catch)
- })
- });
- });
-
- any(tasks).then(() => {
-
- gitRepos.push('client/server');
- gitRepos = gitRepos.concat(elevatedRunasRepos);
-
- // gitRepos = [
- // // 'bbhverse', 'serververse', 'elixir-server',
- // // 'clientverse',
- // 'client'
- // ];
- var rmtasks = [];
- var repotasks = [];
- var env = Object.assign({}, process.env);
- delete env.NODE_ENV;
- gitRepos.forEach(repodef => {
-
- rmtasks.push(
- // () => {
- // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
- // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
- (callShellTask(['rm', ['package-lock.json'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: process.env
- , title: `rm 'package-lock.json' for ${repodef.repo}`
- }]))()
- .then(()=>{
- console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
- }).catch((e) => { console.error(e); })
- // }
- );
-
- if (npmbuildrepos.indexOf(repodef.repo) < 0) {
- repotasks.push(
- () => {
- console.log(`--npm i for ${repodef.repo}--------------------`);
- var p = nodeShellExec('npm', ['i', '--force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env
- , title: `npm i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch);
- return p;
- });
- }
- });
-
-
- // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
- // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
- // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
- // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
- // Second time try also doesnt work.
- // repotasks.push(
- // () => {
- // var env = Object.assign({}, process.env)
- // delete env.NODE_ENV
- // console.log(`--------------------second time npm i for client--------------------`)
- // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
- // // return nodeShellExec('npm', ['i --force'], {
- // inherit: true, shell: true
- // , cwd: instanceroot + '/' + 'client'
- // , env
- // , title: `npm i for client`
- // }).then(Tasq.then).catch(Tasq.catch)
- // })
-
- var bowerRepos = [{ repo : 'client'}];
- bowerRepos.forEach(repodef => {
- repotasks.push(() => {
- console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
- // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
- var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
-
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: process.env
- , title: `bower i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch);
- return p;
- });
- });
- // console.log('rmtasks.length : ' + rmtasks.length)
- return Promise.all(rmtasks).then(() => any(repotasks));
- }).catch(e => {
-
- }).finally(statuslog.finally);
-
- }
- , 'start': (label) => {
- console.log('Starting Elixir Server.');
- var env = Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- env.NODE_ENV = process.env.NODE_ENV || 'development';
- env.DEBUG = 'loopback:connector:' + dbForLabel(label);
- var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
- // cmd = 'node'
- cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
- var childPromise = nodeShellExec(...cmd, {
- // inherit : true,
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + '/' + 'elixir-server'
- , env: env
- });
-
- var child = childPromise.process;
- if (typeof child.pid !== 'undefined') {
- console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
- fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
- encoding: 'utf8'
- });
- }
-
- // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
- // inherit : true,
- // shell: true, detached: true,
- // cwd : 'qms/server',
- // env: env,
- // shell : true
- // })
-
- // nodeShellExec('ember', ['s'], {
- // // inherit : true,
- // shell: true, detached: true,
- // cwd : 'client/',
- // env: env
- // })
- console.log('Starting Elixir Client Host.');
- var cmd = ['ember', ['s']];
- var childPromise = nodeShellExec(...cmd, {
- // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
- // PB : TODO -- ember debugging.
- // inherit : true,
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + '/' + 'client'
- , env: env
- });
- // .catch(e=>console.error(e))
-
- child = childPromise.process;
- if (typeof child.pid !== 'undefined') {
- console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
- fs.writeFileSync('.client.server.pid', child.pid, {
- encoding: 'utf8'
- });
- }
-
- }
- , 'stop': (label) => {
- const kill = treeKill;
-
- var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
- encoding: 'utf8'
- });
- fs.unlinkSync('.elixir-server.elixir.server.pid');
- console.log(serverPid);
- kill(serverPid);
-
- serverPid = fs.readFileSync('.client.server.pid', {
- encoding: 'utf8'
- });
- fs.unlinkSync('.client.server.pid');
- console.log(serverPid);
- kill(serverPid);
- }
- , 'model' : () => {
- if (__isElevated) {
- var tasks = [
- () => {
- var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
- , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
- inherit: true, shell: true
- , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
- , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
- , env: process.env
- }).catch((e) => { console.error(e); });
- return p;
- }
- ];
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- }
- else return op['runas']()
- }
- , 'use' : () => {
- // use a certain named instance.
- // Eg :
- // 1) elxr use elixir
- // 2) elxr use cihsr
- // If environment is not specified defaults to development.
- // 1) NODE=test elxr use elixir
-
- /*// Steps
- 1) Delete Config and Data symlinks
- 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
- 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
- 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
- 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
- */
- var runconfig = { NODE_ENV: selectedinstance.node_env };
- try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
- // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
- if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
- runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
- selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
-
- console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
- if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
- return
- }
-
- var tasks = [
- () => {
- if (existsSync('config')) {
- var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
- ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
- return p;
- }
- else return Promise.resolve(true);
- },
- () => {
- if (existsSync('data')) {
- var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
- ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
- return p;
- }
- else return Promise.resolve(true);
- },
- ];
- runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
- if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
- if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
- // console.log(process.env.cwd)
- fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
-
- // Maps an environment to a branch. Not required if the branch is appropriately named.
- var checkoutMap = { 'development': 'master' };
-
- var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
-
- var performPullOrCloneForBranch = (def)=>{
- var promise = Promise.resolve(true);
- if (!branch) {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
-
- promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
- .catch((e) => { console.error(e); return { error: true, message: repo } });
-
- }
-
- return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
- };
-
- var performCloneAndCheckout = null;
- // cant use git checkout -b it fails when branch already exists.
- var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
-
- return performPullOrCloneForBranch(def).then(()=>{
- nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
- // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
- // inherit : true, shell: true,
- cwd: instanceroot + '/' + def.repo
- // , stdio : ignore // Use when we want to silence output completely.
- , runas: processedArgs.runas
- , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
- }).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 } });
- })
- };
-
- var mergeSources = {
- 'development': null,
- 'test': 'master',
- 'production': 'master'
- };
- var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
-
- // Checkout is reduced to pull provided the current branch is the targetbranch
- if(branch === mergesource) performCheckout = (def) => {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
- return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
-
- if(branch === __branch) return performCloneAndCheckout(def)
- return performPullOrCloneForBranch(def)
- })
- .catch((e) => { console.error(e); return { error: true, message: repo } })
- };
- // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
-
- var performPullAll = (def) => {
- if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['pull', '--all'], {
- // inherit : true, shell: true,
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
- }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
- };
-
- var excludeCheckouts = Object.assign(exludeMergeRepos);
- delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
- delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
-
- var performMerge = (def) => {
- if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['merge', mergesource], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- }).catch((e) => { console.error(e); })
- };
- if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
-
- // var performRepoOperation = function(def) {
- // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
- // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
- // }
-
- return any(tasks).then(() => {
- var pr = Promise.resolve(true);
- if (!__isElevated) {
- pr = op['runas']();
- return pr.then(()=>{
-
- //target is the env is we specify in elxr use command. Default is dev
- //Switch to target branch
- return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
- // pull or clone target branch
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
- // switch to source branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
- })
- //Pull on merge source branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullAll(repo)))
- })
- //Switch to target branch
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
- })
- .then( //Merge source branch to target branch
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
- })
- })
- }
- else {
- tasks = [
- () => {
- // Use junctions to avoid npm package issues
- var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: process.env
- }).catch((e) => { console.error(e); });
- return p;
- }
- ];
- if (processedArgs._[1]) {
- tasks = tasks.concat(
- [
- () => {
- var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: process.env
- }).catch((e) => { console.error(e); });
- return p;
- }
- ]
- );
- }
-
- return any(tasks).then(()=>{
- // checkout target branch
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- // pull or clone target branch
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
- })
- // switch to source branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
- })
- //Pull on merge source branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
- })
- //Switch to target branch
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- })
- .then( //Merge source branch to target branch
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
- })
- .then(() => {
- fs.writeFileSync('run.done', 'success');
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
- })
- }
-
- }).catch(() => {
- fs.writeFileSync('run.done', 'error');
- })
-
- // Antibiotic stewardship program.
- // 1st use is fine.
- // Max vials dispense
- // 2nd use Pharmacy needs justification Form.
- // Approval after a certain period of time.
- }
- , 'g': () => {
- if (processedArgs.h) {
-
- console.log('elxr g [modelname] => generate a model named [modelname]');
- console.log('elxr g => regenerate all known models');
- return
- }
- // nodeShellExec('npm', ['init', '-y'], options);
- // nodeShellExec('npm', ['init', '-y'], options);
- // })
-
- var g = {
- 'client': () => {
- // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
-
- console.info('Creating new ember client named : ' + processedArgs._[2]);
- nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path__default['default'].dirname(__dirname),
- env: env
- });
- },
-
- 'modelr': () => {
- var tasks = [
- () => {
- var p = nodeShellExec('"ember"', [
- 'g'
- , 'modelr'
- , processedArgs._[2]], {
- inherit: true, shell: true, env: process.env
- }).then(() => {
- console.log('Blueprint generation complete for : ' + processedArgs._[2]);
- return true;
- }).catch((e) => { console.error(e); });
- return p;
- },
- () => {
- var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
- var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
- chromeprefs = JSON.parse(chromeprefs);
- var previous = chromeprefs.download.default_directory;
- var parentDir = path__default['default'].dirname(__dirname);
- chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
- // PB : TODO -- detect where chrome is installed.
- // PB : TODO -- set the download dir to the place where files are needed.
- var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
- '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
- , '--profile-directory="chess"'
- , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
- inherit: true, shell: true
- , env: process.env
- }).then(() => {
- chromeprefs.download.default_directory = previous;
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
- return true;
- }).catch((e) => { console.error(e); });
- return p;
- }
- ,
- () => {
- console.log('Browser process should have closed here....');
- return true;
- }
- ];
- any(tasks);
-
- }
-
- };
-
- g[processedArgs._[1]]();
- }
- };
-
-
- var cliname = 'elxr';
- var ver = '1.1';
- var readme = `
- Command syntax examples
-
- elxr
- Displays help. Same as elxr h
-
- elxr i
- Runs interactive propmts to help choose installation options.
-
- NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
- General command syntax.
- Eg: NODE_ENV=development elxr pull elixir
-
- Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
- The specific cmd defines what the value is interpreted as.
- There are several cmds that do not require an {{instancename}} parameter.
- Eg: elxr remote remove origin
- Git operations or passthrough external commands on all repository folders in you working directory.
-
- Main objectives.
- elxr cli is a wrapper around other shell commands and api based operations.
- One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
- Eg: A git operation like pull can be repeated consistently on a set of git repositories.
-
- `;
- var help = `
- ${readme}
-
-
- # list of commands... please refer dveloper documentation for ${cliname}
- ${
- // util.inspect(
- [Object.keys(op)]
- // )
- }
- `;
-
- var elxr = {
- help() {
- return source.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- ${help}
- -------------------------------------------------------------------------------
- `)
- }
- , info() {
- return source.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- -------------------------------------------------------------------------------
- `)
- }
- , getpulltask(def){
-
- // def can be an instance config
- // Or an object with many repos and elevated repos
- // Or a single repo ( Either Elevated or normal. )
-
-
- def = def || {
- repos : selectedinstance.repos,
- elevated : selectedinstance.elevated
- };
-
- var elevatedpulltasks = null;
- if(def.repo) {
- // Single repo case.
- if(def.repo.requiresElevation) {
- elevatedpulltasks = function() {
- return performPull(def.repo).then(() => {
- return true;
- }).catch((e) => {
- console.error(e);
- })
- };
- return
- }
- else {
- var regularpulltasks = function(){
- var pendingpulls = [];
- pendingpulls.push(performPull(def.repo));
- return Promise.all(pendingpulls).finally(Traq.finally)
- };
- }
- if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
- else return getTaskWithoutElevation({ regularpulltasks})
- }
-
- // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
- console.dir(def);
-
- Object.assign({}, process.env); // Shallow clone it.
- console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
-
- processedArgs.useGitPull || false;
-
- if(def.elevated || def.repos) {
- if(def.elevated) def.requiresElevation = true;
- else delete def.requiresElevation;
- }
- else {
- if(def.requiresElevation) def.elevated = [def];
- else def.repos = [def];
- }
-
-
- var regularpulltasks = function(){ return Promise.resolve(true) };
- if(def.elevated){
- elevatedpulltasks = function() {
- return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
- return true;
- }).catch((e) => {
- console.error(e);
- })
- };
- }
- if(def.repos) {
- var regularpulltasks = function(){
- var pendingpulls = [];
- def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
- return Promise.all(pendingpulls).finally(Traq.finally)
- };
- }
- if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
- else return getTaskWithoutElevation({ regularpulltasks})
- }
- };
-
- function preworkerconfig(){
- // Everything runs after this check is completed. Elevation occurs out of process when needed.
- gitRepos = selectedinstance.repos;
- // gitRepos = ['chess-server-lib'];
-
- // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
- elevatedRunasRepos = selectedinstance.elevated;
- // Repos that should excluded from merge for releases...
- exludeMergeRepos = selectedinstance.exludeMergeRepos;
- }
-
-
- // The main elxr cli process
- function elxrworker() {
- var subcommandlabels = {
- remote : (`remote ${processedArgs._[1] || ''}`).trim()
- };
-
- var __runcmd = function (label) {
- var distinquishedlabel = subcommandlabels[label] || label;
- return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
- };
-
-
- // --runas
- if (processedArgs.runas) {
- // Weve been asked to run in priviledged mode. Check if we already are privileged.
- return __runcmd('runas')
- }
- else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
- }
-
- var mergeObjByKey = function(arrOfObjs, keyName) {
-
- var keyedDistinct = {};
- var distinctArrOfObjs = [];
-
- arrOfObjs.forEach( o => {
- if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
- });
- Object.keys(keyedDistinct).forEach(key => {
- distinctArrOfObjs.push( bbhverse.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
- });
-
- return distinctArrOfObjs;
- };
-
- var cacheWriteInstanceConfig = function(chessinstances){
- var instanceName = chessinstances['current_run'].instanceName;
- var node_env = chessinstances['current_run'].node_env;
- chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
- chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
- fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
- };
-
- var acquireConfig = function (selected) {
-
- var configrepo = selected.instanceName + '-config-' + selected.node_env;
-
- return performPull(configrepo).then(() => {
- var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- selectedinstance = commonjsRequire(manifestpath,"/$$rollup_base$$")();
- // Config from server always override merges into selection ecept for the current selection.
- // PB : TODO -- utils.assign Array merges are non-distinct...
- if(!selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
- }
- if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
- }
- chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign(selected, selectedinstance);
- chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
- cacheWriteInstanceConfig(chessinstances);
- ENV.NODE_ENV = selectedinstance.node_env;
- })
- .catch((e) => {
- console.error(e);
- console.error('Config acquisition failed.');
- })
- };
-
- var launchpath = path__default['default'].normalize(process.cwd());
- 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.
- // The easisest would be to ask for a target directory and default to current dir....
- var instanceroot = path__default['default'].normalize(thisscriptdir) === path__default['default'].normalize(launchpath) ? path__default['default'].normalize(thisscriptdir + '/..') : launchpath ;
-
- var __default = {
-
- // Default is public server only.
- // All public repos are by default available.
- reposervers: ['https://git.bbh.org.in']
- , repos: [
- { repo : 'setup' }
- , { repo : 'elxr' }
- , { repo : 'loopback-connector-mysql' }
- , { repo : 'loopback-jsonapi-model-serializer' }
- , { repo : 'loopback-component-jsonapi' }
- , { repo : 'ember-service-worker' }
- , { repo : 'ember-service-worker-asset-cache' }
- , { repo : 'ember-service-worker-cache-fallback' }
- , { repo : 'ember-service-worker-index' }
- , { repo : 'ember-sw-client-route' }
- ]
-
- , elevated: []
- , exludeMergeRepos: {}
- , instanceName: 'chess'
- // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
- , node_env: 'development'
- };
-
- var hasElxr = function(path, options, cb) {
- // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
- options = options || {};
-
-
- var tasks = [
- '/elxr' // Is there a subfolder named elxr
- , '/elxr/.git' // which is self git repository
- , '/elxr/.elxr' // and has .elxr subfolder
- , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
- ];
-
- if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value }
-
- if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value );
-
- return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value);
- };
-
- var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
-
- var detectfromroot = function(root){
- return { root, node_env : path__default['default'].basename(root), instanceName : path__default['default'].basename( path__default['default'].dirname(root) ) }
- };
-
- var detectinstances = function () {
- console.log(`launchpath = ${launchpath}`);
- console.log(`thisscriptdir = ${thisscriptdir}`);
-
- // PB : TODO -- !Postpone this.
- console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
-
- // Note : Paths should already be normalized fefore this.
-
- var root = instanceroot;
- var detected = { root };
- var instanceoptions = [clioverrides];
-
- return hasElxr(launchpath).then( (elxrCliExists) => {
-
- // We need a reference to the root director for elxr cli to be properly oriented.
- if (( elxrCliExists && path__default['default'].normalize(launchpath + '/elxr')) === thisscriptdir) {
- // We were run from the proper root with elxr cli in the subfolder.
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
- if(path__default['default'].normalize(launchpath + '/elxr') === thisscriptdir) {
- // elxrCliExists is false -- and yet thiscriptdir is still proper.
- // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
- console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else if (launchpath === thisscriptdir) {
-
- var parentHasElxr = hasElxrSync(launchpath + '/..');
- // PB : TODO -- verify if we have .elxr folder in the parent...
- if(!parentHasElxr) {
- // ! thisscriptdir is not elxr.
- console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
- }
-
- // Same directory doesn't mean we are being run from elxr sub directory.
- // In standalone build script we may or not be in the same location.
- if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
- // Unbuilt therefore we are in the elxr sub directory.
-
- instanceroot = root = path__default['default'].normalize(launchpath + '/..');
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
- // Built version.
- // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
- if(parentHasElxr) {
- // Built version was run from the full elxr subfolder. Should work
- // PB : TODO -- but we should switch to the full version...
- instanceroot = root = path__default['default'].normalize(launchpath + '/..');
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- else {
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- // Assume current launchpath is a new instance and create.
- // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
-
- // if(clioverrides.instanceName) {
- // if(clioverrides.node_env) {
- // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
- // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
- // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
- // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
- // // eg : floder name can be elixir01 but instance name is elixr
- // }
- // else {
- // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
- // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
- // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
- // }
- // }
- // else {
- // instanceroot = root = launchpath;
- // if(clioverrides.node_env) {
- // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
- // instanceoptions.splice( 0, 0, detectfromroot(root))
- // }
- // else {
- // // Nothing was specified... We only have one option from root.
- // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
- // }
- // }
- }
- }
- }
- else {
- if(elxrCliExists) {
- instanceroot = root = launchpath;
- instanceoptions.splice( 0, 0, detected = { root });
- instanceoptions.splice( 0, 0, detectfromroot(root));
- }
- }
- }
-
- instanceroot = detected.root;
- __default.root = root;
- clioverrides.root = clioverrides.root || root;
-
- // Resolves empty array when No known instances detected.
- return Promise.resolve(instanceoptions)
- })
-
- };
-
- if(clioverrides.reconfirm) {
- var reconfirm = { 'instanceName' : clioverrides['instanceName'] === 'chess' };
- }
- else { var reconfirm = {}; }
-
- var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
- return function(prompts, k, i, a){
-
- // No local instances config found. We use a default initialized instance available in selectedinstance
- // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
- // PB : TODO -- selectedinstance === __default check to prompt everything...
- if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
- || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
- || reconfirm[k]) {
- prompts.push(async ()=>{
- // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
- // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
- // If latest altered state is required we can reerence this directly.
- // var asyncthis = Object.assign(this);
- promptables[k].choices = choices[k];
- Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
- return await target[k]
- });
- }
- delete mustPrompt[k];
- return prompts
- }
- };
-
- var __interactive_prompts = function( target, choices ){
-
- Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
-
- var interactionpoints = {
- runchoice : {
- label :
- `Choose an option :
- d) Install the default chess instance.
- => elxr i chess node_env=development --default
- n) Create your custom new instance interactively
- => elxr i {{instanceName}} node_env={{environment}}
- i) Choose an instance and environment to install
- => elxr i {{instanceName}} node_env={{environment}}
- c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
- => elxr {{cmd}} {{instanceName}} node_env={{environment}}
- h) Help
- q) Quit
- : `
- , choices : []
- , defaultchoice : 'c'
- , interpret : function(choice){
- var interpret_map = {
- d : function(){
- processedArgs._[0] = 'i';
- target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
- target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
- target.reposerver = 'https://git.bbh.org.in';
- }
- , n : function() { processedArgs._[0] = 'i'; }
- , i : function() { processedArgs._[0] = 'i'; }
- , c : async function() {
- Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
- label : `Enter cmd :
- p) pull
- Default <= p
- : `
- , defaultchoice : 'pull'
- }
- ));
-
- var cmd = await target['cmd'];
- if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
- else target['cmd'] = processedArgs._[0] = cmd;
- return cmd;
- }
- , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
- , q : function() { process.exit(); }
- };
- var __interpreter = interpret_map['c'];
- // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
- if(interpret_map[choice]) __interpreter = interpret_map[choice];
-
- return __interpreter.call(target)
- }
- }
- , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
- , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
- , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
- };
-
- var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices);
- return Object.keys(interactionpoints).reduce(eachPrompt, [])
- };
-
-
- var downloadsdir = '../Downloads';
- var prerequisites = [
- {
- shellcmd: 'git',
- url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
- , installer: 'Git-2.31.0-64-bit.exe'
- , installcmd: ['cmd', ['/c', 'start',
- '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
- , '/VERYSILENT'
- // , '/MERGETASKS=!runcode' // This is required only for vscode...
- ]]
- , preinstallsteps: function() {
- var prompt = cliverse.prompter;
- var steps = [
- () => {
- if (!existsSync(downloadsdir + '/' + this.installer)) {
- return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
- }
- else return Promise.resolve(true)
- }
- ];
- var prompts = [
- () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
- , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
- ];
- return any([any(steps), any(prompts)])
- }
- , installsteps: function () {
- return any([this.installcmd].map(callsheltask))
- }
- , postinstallsteps: function(){
-
- var gitUser = 'guest';
- var gitEmail = 'guest@bbh.org.in';
- var prompts = [];
- prompts.push(
- ()=>{
- var choices = { 0 : 'guest', 1 : 'chessdemo' };
- return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
- }
- );
-
- prompts.push(
- ()=>{
- var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
- return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
- }
- );
-
- return any(prompts).then(()=>{
- var steps = [
- ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
- , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
- ];
- return any(steps.map(callsheltask)).then(() => {
-
- })
- });
- }
- , install: function () {
- return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
- }
- , verifyAndInstall : function(){
- return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
- if(exists) {
- // return any(['git', ['config', '--global', '-l']].map(callsheltask))
- return this.getUser(null, this.postinstallsteps.bind(this))
- }
- return this.install();
- });
- }
- , getUser : function(repo, onNoResult){
-
-
- onNoResult = onNoResult || function(){return false};
- var globalOrLocal = '--global';
- if(!repo) globalOrLocal = '--global';
- else globalOrLocal = '--local';
-
- return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
- // not yet configured.
- if(!result.success) return onNoResult()
- else {
- var users = result.messages[0].trim().split('\n');
- if(users.length === 0 ||
- users.length === 1 && users[0] === 'guest') {
-
- return onNoResult()
- }
- else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
- }
- })
- .catch((e)=>{
- console.log(e);
- return onNoResult()
- })
- }
- }
- ,
- {
- shellcmd: 'node',
- url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
- , installer: 'node-v14.16.0-x64.msi'
- , installcmd: ['MSIEXEC.exe', ['/i'
- , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
- , 'ACCEPT=YES', '/passive']]
- , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
- }
- ];
-
- prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
-
- function ensureDirectoryExistence(filePath) {
- var dirname = path__default['default'].dirname(filePath);
- if (fs.existsSync(dirname)) {
- return filePath;
- }
- ensureDirectoryExistence(dirname);
- fs.mkdirSync(dirname);
- return filePath;
- }
-
- var mainTasks = [];
- function verifyAndInstallPrerequisites() {
- fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
-
- // PB : TODO include and build from files... using rollup..
- var downloadbatch =
- `::**************************************************************************
- :Download_ <url> <File>
- Powershell.exe ^
- $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
- [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
- (New-Object System.Net.WebClient).DownloadFile('%1','%2')
- exit /b
- ::**************************************************************************`;
- fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
-
-
- var windowselevate =
- `
- <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
- <script language="vbscript">
- document.title = "elxr control panel"
- self.ResizeTo 200,600
-
- Sub Window_Onload
- self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
- End Sub
-
- Set objShell = CreateObject("WScript.Shell")
- Set objENV = objShell.Environment("Process")
- dim NODE_ENV
- NODE_ENV = objENV("NODE_ENV")
- </script>
-
- <script language="javascript">
- //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
- // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
- // alert(windowselevate.commandLine)
- var args = windowselevate.commandLine.split('"').slice(3);
- // alert(args)
- var processedArgs = { _ : [] }
- var namedArgs = [];
- for(var item in args){
- if(args[item].charAt(0) === '-'){
- namedArgs.push(args[item])
- var split = args[item].split('=');
- processedArgs[split[0].slice(2)] = split[1] || true;
- }
- else processedArgs._.push(args[item]);
- }
- // args = args.forEach(function(item){ })
- // alert('processedArgs._ : ' + processedArgs._);
- // alert(processedArgs.runas);
-
- // PB : TODO -- Convert all the cli args back to string.
- var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
- // alert(cargs)
- var shell = new ActiveXObject('shell.application');
- // alert('launching node privilged. ' + processedArgs['nodepath'])
- // shell.ShellExecute('where', 'node', '', '', 10);
- shell.ShellExecute('node', cargs, '', 'runas', 1);
- // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
- var fso = new ActiveXObject('Scripting.FileSystemObject');
-
- window.onload = function() {
- document.body.style.backgroundColor = 'black';
- document.body.style.fontFamily = 'arial';
- var log = document.createElement('div');
- log.innerHTML='Please Wait';
- function l(msg){ log.innerHTML+= msg; };
- log.style.color = 'blue';
- log.style.width = '95%';
- log.id = 'log';
- document.body.appendChild(log);
-
- l('<Br/>Current config : ')
- l('<Br/>NODE_ENV = ' + NODE_ENV)
- l('<Br/>cmd = ' + processedArgs._[0])
- processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
- l('<Br/><Br/>')
-
- var timer = function(){
- l('.');
- if(fso.FileExists("run.done")) close();
- else window.setTimeout(timer, 1000);
- };
- window.setTimeout(timer, 3000);
- };
-
- </script>
- </html>
-
- `;
- fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
-
- var downloadtasks = [];
- var installtasks = [];
- prerequisites.forEach(preq => {
- downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
- if (exists) console.log(`${preq.shellcmd} exists`);
- else {
- console.log(`${preq.shellcmd} is not installed`);
- return preq.preinstallsteps.call(preq).then(() => {
- installtasks.push(preq.install.bind(preq));
- })
- }
- }));
- });
- return Promise.all(downloadtasks).then(() => { return any(installtasks) })
- }
-
- var getPromptableAsyncPropDescriptor = function(propName, promptable){
- return {
- get (){
- return cliverse.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
-
- var asyncprop = Promise.resolve(propValue);
- if(promptable.interpret){
- asyncprop = promptable.interpret(propValue);
- }
-
- return asyncprop.then(
- ()=>{
- Object.defineProperty(this, propName, {
- value: propValue,
- writable: true,
- configurable : true,
- enumerable : true
- });
- return propValue
- }
- )
- })
- }
- // , set (propValue){
- // Object.defineProperty(this, propName, {
- // value: propValue,
- // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
- // configurable : true,
- // enumerable : true
- // })
- // return propValue;
- // }
- , configurable : true
- , enumerable : true
- }
- };
-
-
-
-
- function acquirelocalinstances(selected){
- // utils.assign is used to cleanup duplicates...
- var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
- return chessinstances
- }
-
- function findlocalinstances(chessinstances, instanceoptions){
- // We can expect a .elxr at each level.
- ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
- earlyreduce( ( value, p, i, a )=>{
- var localinstancesPath = `${instanceroot}/${p}.elxr`;
- if(existsSync( localinstancesPath )) {
- try {
- var chessinstances = acquirelocalinstances( { localinstancesPath } );
- return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
- return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
- if( path__default['default'].normalize(chessinstances[instanceName][instanceType].root) === path__default['default'].normalize( instanceroot) ) {
- instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
- return {
- value : chessinstances[instanceName][instanceType]
- , done : true
- };
- }
- })
- })
- }
- catch(e){
- return { }
- }
- }
- else return { }
- }
- );
- }
-
-
- // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
- var selectedinstance = null;
- var chessinstances = { current_run : {} };
- var promptkeys = {
- // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
- // 'instanceName' : true
- // , 'node_env' : true
- };
-
- function createChessInsance( cfg ){
- var inst = {};
- var __new = Object.assign({}, __default, cfg);
- inst[cfg.node_env] = __new; return inst;
- }
-
- acquireElevationState().then(() => {
- function initinstances(selected_overrides) {
- var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectinstances.
-
- var instanceName = selected_overrides.instanceName
- || clioverrides.instanceName
- // || processedArgs._[1]
- || chessinstances.current_run.instanceName;
-
- var node_env = selected_overrides.node_env
- || clioverrides.node_env
- // || processedArgs.node_env
- || chessinstances.current_run.node_env;
-
- var reposerver = selected_overrides.reposerver
- || clioverrides.reposerver
- // || processedArgs.node_env
- || chessinstances.current_run.reposerver;
-
- if(!instanceName) {
- promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
- promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- if(!node_env) {
- promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- if(!reposerver) {
- promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
- }
-
- chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
- instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
- chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
-
- if(path__default['default'].normalize(selected_overrides.root) !== path__default['default'].normalize(chessinstances[instanceName][node_env].root)) {
- 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
- }
- // Override sequence.
- // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
- selectedinstance = bbhverse.assign(
- chessinstances[instanceName][node_env]
- , clioverrides
- , selected_overrides
- // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
- );
-
- // chessinstances[instanceName] = chessinstances[instanceName] || {}
- // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
-
- // if(!selectedinstance.repos || selectedinstance.instanceName) {
- // // Brand New.
- // selectedinstance = Object.assign( __default, selectedinstance )
- // }
-
- if(!selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
- }
- if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
- }
-
- // Config from server always override merges into selection except for the current selection.
- // PB : TODO -- utils.assign Array merges are non-distinct...
- chessinstances[instanceName][node_env] = selectedinstance;
- // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
- cacheWriteInstanceConfig(chessinstances);
- // PB : TODO -- We should probably write the new server config also...
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
-
- return chessinstances
- }
-
- var noprerequisites = {
- add : true, 'set-url' : true, 'repo-relocate' : true
- , remote : true
- };
- var skipprereqs = {};
- var maintask = () => {
-
- // Default cmd to run !
- processedArgs._[0] === processedArgs._[0] || 'pull';
- // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
-
- if(!noprerequisites[processedArgs._[0]]
- && !skipprereqs[processedArgs._[0]]
- ) {
- return prerequisites.git.verifyAndInstall().then(()=>{
- return acquireConfig(selectedinstance).catch((err) => {
- console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
- console.error(err);
- }).then(() => { preworkerconfig(); return elxrworker() })
- // .finally(()=>{
- // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
- // if(!e.success) fs.writeFileSync('run.done', 'error');
- // // return process.exit()
- // })
- })
- }
- else {
- console.log('cmd has no preqs or has been configured to skip preqs');
- preworkerconfig();
- return elxrworker()
- }
-
- };
-
- const retaincount = 2;
- var min = runtimestamp;
- var collect = [];
-
- if(noprerequisites[processedArgs._[0]]
- || skipprereqs[processedArgs._[0]]
- ) {
- return elxrworker()
- }
-
- var getchoices = function(detectedinstanceoptions, promptkeys){
-
- var instances = [];
- var reposervers = [];
- var instnaceNames = [];
- var instanceTypes = ['development', 'production'];
- Object.keys( chessinstances).forEach(instanceName => {
- if(instanceName === 'current_run') return;
- Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
- var instance = chessinstances[instanceName][node_env];
- reposervers = reposervers.concat(instance.reposervers);
- if(instance.reposerver) reposervers.push(instance.reposerver);
- instances.push(instance);
- instanceTypes.push(instance.node_env);
- instnaceNames.push(instance.instanceName);
- });
- });
- instances = instances.concat(detectedinstanceoptions);
-
- if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName']);
- if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName']);
- if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
-
- var choices = {
- 'instanceName' : Array.from( new Set(instnaceNames) )
- , 'reposerver' : Array.from( new Set(reposervers) )
- , 'instanceType' : Array.from( new Set(instanceTypes) )
- };
-
- return choices;
- };
-
- return detectinstances().then((detectedinstanceoptions)=>{
- detectedinstanceoptions.splice(0,0, __default);
-
-
- // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
- selectedinstance = bbhverse.assign( ...detectedinstanceoptions.slice(-2) );
- // promptkeys = utils.assign(promptkeys, clioverrides)
-
- try {
-
- chessinstances = acquirelocalinstances(selectedinstance);
- findlocalinstances(chessinstances, detectedinstanceoptions);
- initinstances(selectedinstance); // use the local instances for defaults if at all possible.
- var choices = getchoices(detectedinstanceoptions, promptkeys);
- var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
- return initinstances(selectedinstance)
- });
- }
- catch (e) {
- // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
- var choices = getchoices(detectedinstanceoptions, promptkeys);
- var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
- return initinstances(selectedinstance)
- });
-
- // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
- // // Weve not been told what to do.
- // todo = todo.then(() => { return acquireChoices(selectedinstance) })
- // }
-
- todo = todo.then(() => {
- try {
- chessinstances = acquirelocalinstances(selectedinstance);
- findlocalinstances(chessinstances, detectedinstanceoptions);
- detectedinstanceoptions.splice(0,0, __default);
- initinstances(selectedinstance);
- }
- catch (e) {
- console.error(e);
- console.log('No local instances config found in current root = ' + selectedinstance.root);
- console.log('A config will be createed with the instance and environment chosen...');
- // return (async ()=>{return await __default.reposerver})().then(()=>{
- // // selectedinstance = Object.assign(detectedInstance, clioverrides);
- // return selectedinstance = Object.assign(__default, selectedinstance);
- // })
- return selectedinstance
- }
- });
- }
-
- return todo
- })
- .then(()=>{
-
- if(!__isElevated) {
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
- // collect garbage
- return dirs( (dir)=>{
- var matches = /run-(.*)/gm.exec(dir.name);
- if(matches) {
- if(+(matches[1]) < min) {
- min = matches[1];
- collect.splice( 0, 0, matches[1] );
- }
- else collect.push(matches[1]);
- }
-
- }, `${selectedinstance.root}/.elxr` ).then(()=>{
- // delete garbage
- if(collect.length > retaincount) {
-
- var asyncs = [];
- while((collect.length - asyncs.length) > retaincount) {
- asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
- }
- return Promise.all(asyncs)
- }
- else return true
- })
- }
- else return true;
- })
- .then(()=>{
- // PB : TODO -- Keep only the last n runs...
- // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
-
- if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
- mainTasks.push(maintask);
- return any(mainTasks);
- })
- });
-
-
-
-
- // Sample instances config.
- // var instances = {
- // "elixir": {
- // "production": {
- // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
- // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
- // , "exludeMergeRepos": {
- // "elixir-config-development": true, "elixir-config-test": true
- // , "elixir-config-production": true, "elixir-data": true
- // }
- // , "instanceName": "elixir", "node_env": "production"
- // }
- // },
- // "current_run": { "instanceName": "elixir", "node_env": "production" }
- // }
-
- // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
-
- var elxr_1 = {
-
- };
-
- module.exports = elxr_1;
|