| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038 |
- (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
- const OverpassFrontend = require('overpass-frontend')
- const OverpassLayer = require('./src/OverpassLayer')
- const OverpassLayerList = require('./src/OverpassLayerList')
- if (typeof window !== 'undefined') {
- window.OverpassLayer = OverpassLayer
- window.OverpassLayerList = OverpassLayerList
- window.OverpassFrontend = OverpassFrontend
- }
- OverpassLayer.List = OverpassLayerList
- module.exports = OverpassLayer
- },{"./src/OverpassLayer":216,"./src/OverpassLayerList":218,"overpass-frontend":180}],2:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var meta_1 = require("@turf/meta");
- // Note: change RADIUS => earthRadius
- var RADIUS = 6378137;
- /**
- * Takes one or more features and returns their area in square meters.
- *
- * @name area
- * @param {GeoJSON} geojson input GeoJSON feature(s)
- * @returns {number} area in square meters
- * @example
- * var polygon = turf.polygon([[[125, -15], [113, -22], [154, -27], [144, -15], [125, -15]]]);
- *
- * var area = turf.area(polygon);
- *
- * //addToMap
- * var addToMap = [polygon]
- * polygon.properties.area = area
- */
- function area(geojson) {
- return meta_1.geomReduce(geojson, function (value, geom) {
- return value + calculateArea(geom);
- }, 0);
- }
- exports.default = area;
- /**
- * Calculate Area
- *
- * @private
- * @param {Geometry} geom GeoJSON Geometries
- * @returns {number} area
- */
- function calculateArea(geom) {
- var total = 0;
- var i;
- switch (geom.type) {
- case "Polygon":
- return polygonArea(geom.coordinates);
- case "MultiPolygon":
- for (i = 0; i < geom.coordinates.length; i++) {
- total += polygonArea(geom.coordinates[i]);
- }
- return total;
- case "Point":
- case "MultiPoint":
- case "LineString":
- case "MultiLineString":
- return 0;
- }
- return 0;
- }
- function polygonArea(coords) {
- var total = 0;
- if (coords && coords.length > 0) {
- total += Math.abs(ringArea(coords[0]));
- for (var i = 1; i < coords.length; i++) {
- total -= Math.abs(ringArea(coords[i]));
- }
- }
- return total;
- }
- /**
- * @private
- * Calculate the approximate area of the polygon were it projected onto the earth.
- * Note that this area will be positive if ring is oriented clockwise, otherwise it will be negative.
- *
- * Reference:
- * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere",
- * JPL Publication 07-03, Jet Propulsion
- * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
- *
- * @param {Array<Array<number>>} coords Ring Coordinates
- * @returns {number} The approximate signed geodesic area of the polygon in square meters.
- */
- function ringArea(coords) {
- var p1;
- var p2;
- var p3;
- var lowerIndex;
- var middleIndex;
- var upperIndex;
- var i;
- var total = 0;
- var coordsLength = coords.length;
- if (coordsLength > 2) {
- for (i = 0; i < coordsLength; i++) {
- if (i === coordsLength - 2) {
- lowerIndex = coordsLength - 2;
- middleIndex = coordsLength - 1;
- upperIndex = 0;
- }
- else if (i === coordsLength - 1) {
- lowerIndex = coordsLength - 1;
- middleIndex = 0;
- upperIndex = 1;
- }
- else {
- lowerIndex = i;
- middleIndex = i + 1;
- upperIndex = i + 2;
- }
- p1 = coords[lowerIndex];
- p2 = coords[middleIndex];
- p3 = coords[upperIndex];
- total += (rad(p3[0]) - rad(p1[0])) * Math.sin(rad(p2[1]));
- }
- total = total * RADIUS * RADIUS / 2;
- }
- return total;
- }
- function rad(num) {
- return num * Math.PI / 180;
- }
- },{"@turf/meta":16}],3:[function(require,module,exports){
- "use strict";
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- var lineclip = __importStar(require("./lib/lineclip"));
- /**
- * Takes a {@link Feature} and a bbox and clips the feature to the bbox using
- * [lineclip](https://github.com/mapbox/lineclip).
- * May result in degenerate edges when clipping Polygons.
- *
- * @name bboxClip
- * @param {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} feature feature to clip to the bbox
- * @param {BBox} bbox extent in [minX, minY, maxX, maxY] order
- * @returns {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} clipped Feature
- * @example
- * var bbox = [0, 0, 10, 10];
- * var poly = turf.polygon([[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]);
- *
- * var clipped = turf.bboxClip(poly, bbox);
- *
- * //addToMap
- * var addToMap = [bbox, poly, clipped]
- */
- function bboxClip(feature, bbox) {
- var geom = invariant_1.getGeom(feature);
- var type = geom.type;
- var properties = feature.type === "Feature" ? feature.properties : {};
- var coords = geom.coordinates;
- switch (type) {
- case "LineString":
- case "MultiLineString":
- var lines_1 = [];
- if (type === "LineString") {
- coords = [coords];
- }
- coords.forEach(function (line) {
- lineclip.polyline(line, bbox, lines_1);
- });
- if (lines_1.length === 1) {
- return helpers_1.lineString(lines_1[0], properties);
- }
- return helpers_1.multiLineString(lines_1, properties);
- case "Polygon":
- return helpers_1.polygon(clipPolygon(coords, bbox), properties);
- case "MultiPolygon":
- return helpers_1.multiPolygon(coords.map(function (poly) {
- return clipPolygon(poly, bbox);
- }), properties);
- default:
- throw new Error("geometry " + type + " not supported");
- }
- }
- exports.default = bboxClip;
- function clipPolygon(rings, bbox) {
- var outRings = [];
- for (var _i = 0, rings_1 = rings; _i < rings_1.length; _i++) {
- var ring = rings_1[_i];
- var clipped = lineclip.polygon(ring, bbox);
- if (clipped.length > 0) {
- if (clipped[0][0] !== clipped[clipped.length - 1][0] || clipped[0][1] !== clipped[clipped.length - 1][1]) {
- clipped.push(clipped[0]);
- }
- if (clipped.length >= 4) {
- outRings.push(clipped);
- }
- }
- }
- return outRings;
- }
- },{"./lib/lineclip":4,"@turf/helpers":11,"@turf/invariant":13}],4:[function(require,module,exports){
- 'use strict';
- module.exports = lineclip;
- module.exports.default = lineclip;
- lineclip.polyline = lineclip;
- lineclip.polygon = polygonclip;
- // Cohen-Sutherland line clippign algorithm, adapted to efficiently
- // handle polylines rather than just segments
- function lineclip(points, bbox, result) {
- var len = points.length,
- codeA = bitCode(points[0], bbox),
- part = [],
- i, a, b, codeB, lastCode;
- if (!result) result = [];
- for (i = 1; i < len; i++) {
- a = points[i - 1];
- b = points[i];
- codeB = lastCode = bitCode(b, bbox);
- while (true) {
- if (!(codeA | codeB)) { // accept
- part.push(a);
- if (codeB !== lastCode) { // segment went outside
- part.push(b);
- if (i < len - 1) { // start a new line
- result.push(part);
- part = [];
- }
- } else if (i === len - 1) {
- part.push(b);
- }
- break;
- } else if (codeA & codeB) { // trivial reject
- break;
- } else if (codeA) { // a outside, intersect with clip edge
- a = intersect(a, b, codeA, bbox);
- codeA = bitCode(a, bbox);
- } else { // b outside
- b = intersect(a, b, codeB, bbox);
- codeB = bitCode(b, bbox);
- }
- }
- codeA = lastCode;
- }
- if (part.length) result.push(part);
- return result;
- }
- // Sutherland-Hodgeman polygon clipping algorithm
- function polygonclip(points, bbox) {
- var result, edge, prev, prevInside, i, p, inside;
- // clip against each side of the clip rectangle
- for (edge = 1; edge <= 8; edge *= 2) {
- result = [];
- prev = points[points.length - 1];
- prevInside = !(bitCode(prev, bbox) & edge);
- for (i = 0; i < points.length; i++) {
- p = points[i];
- inside = !(bitCode(p, bbox) & edge);
- // if segment goes through the clip window, add an intersection
- if (inside !== prevInside) result.push(intersect(prev, p, edge, bbox));
- if (inside) result.push(p); // add a point if it's inside
- prev = p;
- prevInside = inside;
- }
- points = result;
- if (!points.length) break;
- }
- return result;
- }
- // intersect a segment against one of the 4 lines that make up the bbox
- function intersect(a, b, edge, bbox) {
- return edge & 8 ? [a[0] + (b[0] - a[0]) * (bbox[3] - a[1]) / (b[1] - a[1]), bbox[3]] : // top
- edge & 4 ? [a[0] + (b[0] - a[0]) * (bbox[1] - a[1]) / (b[1] - a[1]), bbox[1]] : // bottom
- edge & 2 ? [bbox[2], a[1] + (b[1] - a[1]) * (bbox[2] - a[0]) / (b[0] - a[0])] : // right
- edge & 1 ? [bbox[0], a[1] + (b[1] - a[1]) * (bbox[0] - a[0]) / (b[0] - a[0])] : // left
- null;
- }
- // bit code reflects the point position relative to the bbox:
- // left mid right
- // top 1001 1000 1010
- // mid 0001 0000 0010
- // bottom 0101 0100 0110
- function bitCode(p, bbox) {
- var code = 0;
- if (p[0] < bbox[0]) code |= 1; // left
- else if (p[0] > bbox[2]) code |= 2; // right
- if (p[1] < bbox[1]) code |= 4; // bottom
- else if (p[1] > bbox[3]) code |= 8; // top
- return code;
- }
- },{}],5:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var meta_1 = require("@turf/meta");
- /**
- * Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
- *
- * @name bbox
- * @param {GeoJSON} geojson any GeoJSON object
- * @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
- * @example
- * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);
- * var bbox = turf.bbox(line);
- * var bboxPolygon = turf.bboxPolygon(bbox);
- *
- * //addToMap
- * var addToMap = [line, bboxPolygon]
- */
- function bbox(geojson) {
- var result = [Infinity, Infinity, -Infinity, -Infinity];
- meta_1.coordEach(geojson, function (coord) {
- if (result[0] > coord[0]) {
- result[0] = coord[0];
- }
- if (result[1] > coord[1]) {
- result[1] = coord[1];
- }
- if (result[2] < coord[0]) {
- result[2] = coord[0];
- }
- if (result[3] < coord[1]) {
- result[3] = coord[1];
- }
- });
- return result;
- }
- exports.default = bbox;
- },{"@turf/meta":16}],6:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- // http://en.wikipedia.org/wiki/Haversine_formula
- // http://www.movable-type.co.uk/scripts/latlong.html
- /**
- * Takes two {@link Point|points} and finds the geographic bearing between them,
- * i.e. the angle measured in degrees from the north line (0 degrees)
- *
- * @name bearing
- * @param {Coord} start starting Point
- * @param {Coord} end ending Point
- * @param {Object} [options={}] Optional parameters
- * @param {boolean} [options.final=false] calculates the final bearing if true
- * @returns {number} bearing in decimal degrees, between -180 and 180 degrees (positive clockwise)
- * @example
- * var point1 = turf.point([-75.343, 39.984]);
- * var point2 = turf.point([-75.534, 39.123]);
- *
- * var bearing = turf.bearing(point1, point2);
- *
- * //addToMap
- * var addToMap = [point1, point2]
- * point1.properties['marker-color'] = '#f00'
- * point2.properties['marker-color'] = '#0f0'
- * point1.properties.bearing = bearing
- */
- function bearing(start, end, options) {
- if (options === void 0) { options = {}; }
- // Reverse calculation
- if (options.final === true) {
- return calculateFinalBearing(start, end);
- }
- var coordinates1 = invariant_1.getCoord(start);
- var coordinates2 = invariant_1.getCoord(end);
- var lon1 = helpers_1.degreesToRadians(coordinates1[0]);
- var lon2 = helpers_1.degreesToRadians(coordinates2[0]);
- var lat1 = helpers_1.degreesToRadians(coordinates1[1]);
- var lat2 = helpers_1.degreesToRadians(coordinates2[1]);
- var a = Math.sin(lon2 - lon1) * Math.cos(lat2);
- var b = Math.cos(lat1) * Math.sin(lat2) -
- Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
- return helpers_1.radiansToDegrees(Math.atan2(a, b));
- }
- /**
- * Calculates Final Bearing
- *
- * @private
- * @param {Coord} start starting Point
- * @param {Coord} end ending Point
- * @returns {number} bearing
- */
- function calculateFinalBearing(start, end) {
- // Swap start & end
- var bear = bearing(end, start);
- bear = (bear + 180) % 360;
- return bear;
- }
- exports.default = bearing;
- },{"@turf/helpers":11,"@turf/invariant":13}],7:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var invariant_1 = require("@turf/invariant");
- // http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule
- // modified from: https://github.com/substack/point-in-polygon/blob/master/index.js
- // which was modified from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
- /**
- * Takes a {@link Point} and a {@link Polygon} or {@link MultiPolygon} and determines if the point
- * resides inside the polygon. The polygon can be convex or concave. The function accounts for holes.
- *
- * @name booleanPointInPolygon
- * @param {Coord} point input point
- * @param {Feature<Polygon|MultiPolygon>} polygon input polygon or multipolygon
- * @param {Object} [options={}] Optional parameters
- * @param {boolean} [options.ignoreBoundary=false] True if polygon boundary should be ignored when determining if
- * the point is inside the polygon otherwise false.
- * @returns {boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon
- * @example
- * var pt = turf.point([-77, 44]);
- * var poly = turf.polygon([[
- * [-81, 41],
- * [-81, 47],
- * [-72, 47],
- * [-72, 41],
- * [-81, 41]
- * ]]);
- *
- * turf.booleanPointInPolygon(pt, poly);
- * //= true
- */
- function booleanPointInPolygon(point, polygon, options) {
- if (options === void 0) { options = {}; }
- // validation
- if (!point) {
- throw new Error("point is required");
- }
- if (!polygon) {
- throw new Error("polygon is required");
- }
- var pt = invariant_1.getCoord(point);
- var geom = invariant_1.getGeom(polygon);
- var type = geom.type;
- var bbox = polygon.bbox;
- var polys = geom.coordinates;
- // Quick elimination if point is not inside bbox
- if (bbox && inBBox(pt, bbox) === false) {
- return false;
- }
- // normalize to multipolygon
- if (type === "Polygon") {
- polys = [polys];
- }
- var insidePoly = false;
- for (var i = 0; i < polys.length && !insidePoly; i++) {
- // check if it is in the outer ring first
- if (inRing(pt, polys[i][0], options.ignoreBoundary)) {
- var inHole = false;
- var k = 1;
- // check for the point in any of the holes
- while (k < polys[i].length && !inHole) {
- if (inRing(pt, polys[i][k], !options.ignoreBoundary)) {
- inHole = true;
- }
- k++;
- }
- if (!inHole) {
- insidePoly = true;
- }
- }
- }
- return insidePoly;
- }
- exports.default = booleanPointInPolygon;
- /**
- * inRing
- *
- * @private
- * @param {Array<number>} pt [x,y]
- * @param {Array<Array<number>>} ring [[x,y], [x,y],..]
- * @param {boolean} ignoreBoundary ignoreBoundary
- * @returns {boolean} inRing
- */
- function inRing(pt, ring, ignoreBoundary) {
- var isInside = false;
- if (ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1]) {
- ring = ring.slice(0, ring.length - 1);
- }
- for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
- var xi = ring[i][0];
- var yi = ring[i][1];
- var xj = ring[j][0];
- var yj = ring[j][1];
- var onBoundary = (pt[1] * (xi - xj) + yi * (xj - pt[0]) + yj * (pt[0] - xi) === 0) &&
- ((xi - pt[0]) * (xj - pt[0]) <= 0) && ((yi - pt[1]) * (yj - pt[1]) <= 0);
- if (onBoundary) {
- return !ignoreBoundary;
- }
- var intersect = ((yi > pt[1]) !== (yj > pt[1])) &&
- (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi);
- if (intersect) {
- isInside = !isInside;
- }
- }
- return isInside;
- }
- /**
- * inBBox
- *
- * @private
- * @param {Position} pt point [x,y]
- * @param {BBox} bbox BBox [west, south, east, north]
- * @returns {boolean} true/false if point is inside BBox
- */
- function inBBox(pt, bbox) {
- return bbox[0] <= pt[0] &&
- bbox[1] <= pt[1] &&
- bbox[2] >= pt[0] &&
- bbox[3] >= pt[1];
- }
- },{"@turf/invariant":13}],8:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- // http://en.wikipedia.org/wiki/Haversine_formula
- // http://www.movable-type.co.uk/scripts/latlong.html
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- /**
- * Takes a {@link Point} and calculates the location of a destination point given a distance in
- * degrees, radians, miles, or kilometers; and bearing in degrees.
- * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
- *
- * @name destination
- * @param {Coord} origin starting point
- * @param {number} distance distance from the origin point
- * @param {number} bearing ranging from -180 to 180
- * @param {Object} [options={}] Optional parameters
- * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
- * @param {Object} [options.properties={}] Translate properties to Point
- * @returns {Feature<Point>} destination point
- * @example
- * var point = turf.point([-75.343, 39.984]);
- * var distance = 50;
- * var bearing = 90;
- * var options = {units: 'miles'};
- *
- * var destination = turf.destination(point, distance, bearing, options);
- *
- * //addToMap
- * var addToMap = [point, destination]
- * destination.properties['marker-color'] = '#f00';
- * point.properties['marker-color'] = '#0f0';
- */
- function destination(origin, distance, bearing, options) {
- if (options === void 0) { options = {}; }
- // Handle input
- var coordinates1 = invariant_1.getCoord(origin);
- var longitude1 = helpers_1.degreesToRadians(coordinates1[0]);
- var latitude1 = helpers_1.degreesToRadians(coordinates1[1]);
- var bearingRad = helpers_1.degreesToRadians(bearing);
- var radians = helpers_1.lengthToRadians(distance, options.units);
- // Main
- var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +
- Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));
- var longitude2 = longitude1 + Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));
- var lng = helpers_1.radiansToDegrees(longitude2);
- var lat = helpers_1.radiansToDegrees(latitude2);
- return helpers_1.point([lng, lat], options.properties);
- }
- exports.default = destination;
- },{"@turf/helpers":11,"@turf/invariant":13}],9:[function(require,module,exports){
- 'use strict';
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var martinez = require('martinez-polygon-clipping');
- var area = _interopDefault(require('@turf/area'));
- var helpers = require('@turf/helpers');
- var invariant = require('@turf/invariant');
- var meta = require('@turf/meta');
- /**
- * Finds the difference between two {@link Polygon|polygons} by clipping the second polygon from the first.
- *
- * @name difference
- * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
- * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
- * @returns {Feature<Polygon|MultiPolygon>|null} a Polygon or MultiPolygon feature showing the area of `polygon1` excluding the area of `polygon2` (if empty returns `null`)
- * @example
- * var polygon1 = turf.polygon([[
- * [128, -26],
- * [141, -26],
- * [141, -21],
- * [128, -21],
- * [128, -26]
- * ]], {
- * "fill": "#F00",
- * "fill-opacity": 0.1
- * });
- * var polygon2 = turf.polygon([[
- * [126, -28],
- * [140, -28],
- * [140, -20],
- * [126, -20],
- * [126, -28]
- * ]], {
- * "fill": "#00F",
- * "fill-opacity": 0.1
- * });
- *
- * var difference = turf.difference(polygon1, polygon2);
- *
- * //addToMap
- * var addToMap = [polygon1, polygon2, difference];
- */
- function difference(polygon1, polygon2) {
- var geom1 = invariant.getGeom(polygon1);
- var geom2 = invariant.getGeom(polygon2);
- var properties = polygon1.properties || {};
- // Issue #721 - JSTS/Martinez can't handle empty polygons
- geom1 = removeEmptyPolygon(geom1);
- geom2 = removeEmptyPolygon(geom2);
- if (!geom1) return null;
- if (!geom2) return helpers.feature(geom1, properties);
- var differenced = martinez.diff(geom1.coordinates, geom2.coordinates);
- if (differenced.length === 0) return null;
- if (differenced.length === 1) return helpers.polygon(differenced[0], properties);
- return helpers.multiPolygon(differenced, properties);
- }
- /**
- * Detect Empty Polygon
- *
- * @private
- * @param {Geometry<Polygon|MultiPolygon>} geom Geometry Object
- * @returns {Geometry<Polygon|MultiPolygon>|null} removed any polygons with no areas
- */
- function removeEmptyPolygon(geom) {
- switch (geom.type) {
- case 'Polygon':
- if (area(geom) > 1) return geom;
- return null;
- case 'MultiPolygon':
- var coordinates = [];
- meta.flattenEach(geom, function (feature) {
- if (area(feature) > 1) coordinates.push(feature.geometry.coordinates);
- });
- if (coordinates.length) return {type: 'MultiPolygon', coordinates: coordinates};
- }
- }
- module.exports = difference;
- },{"@turf/area":2,"@turf/helpers":11,"@turf/invariant":13,"@turf/meta":16,"martinez-polygon-clipping":173}],10:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var invariant_1 = require("@turf/invariant");
- var helpers_1 = require("@turf/helpers");
- //http://en.wikipedia.org/wiki/Haversine_formula
- //http://www.movable-type.co.uk/scripts/latlong.html
- /**
- * Calculates the distance between two {@link Point|points} in degrees, radians, miles, or kilometers.
- * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
- *
- * @name distance
- * @param {Coord} from origin point
- * @param {Coord} to destination point
- * @param {Object} [options={}] Optional parameters
- * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers
- * @returns {number} distance between the two points
- * @example
- * var from = turf.point([-75.343, 39.984]);
- * var to = turf.point([-75.534, 39.123]);
- * var options = {units: 'miles'};
- *
- * var distance = turf.distance(from, to, options);
- *
- * //addToMap
- * var addToMap = [from, to];
- * from.properties.distance = distance;
- * to.properties.distance = distance;
- */
- function distance(from, to, options) {
- if (options === void 0) { options = {}; }
- var coordinates1 = invariant_1.getCoord(from);
- var coordinates2 = invariant_1.getCoord(to);
- var dLat = helpers_1.degreesToRadians((coordinates2[1] - coordinates1[1]));
- var dLon = helpers_1.degreesToRadians((coordinates2[0] - coordinates1[0]));
- var lat1 = helpers_1.degreesToRadians(coordinates1[1]);
- var lat2 = helpers_1.degreesToRadians(coordinates2[1]);
- var a = Math.pow(Math.sin(dLat / 2), 2) +
- Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
- return helpers_1.radiansToLength(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), options.units);
- }
- exports.default = distance;
- },{"@turf/helpers":11,"@turf/invariant":13}],11:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- /**
- * @module helpers
- */
- /**
- * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
- *
- * @memberof helpers
- * @type {number}
- */
- exports.earthRadius = 6371008.8;
- /**
- * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
- *
- * @memberof helpers
- * @type {Object}
- */
- exports.factors = {
- centimeters: exports.earthRadius * 100,
- centimetres: exports.earthRadius * 100,
- degrees: exports.earthRadius / 111325,
- feet: exports.earthRadius * 3.28084,
- inches: exports.earthRadius * 39.370,
- kilometers: exports.earthRadius / 1000,
- kilometres: exports.earthRadius / 1000,
- meters: exports.earthRadius,
- metres: exports.earthRadius,
- miles: exports.earthRadius / 1609.344,
- millimeters: exports.earthRadius * 1000,
- millimetres: exports.earthRadius * 1000,
- nauticalmiles: exports.earthRadius / 1852,
- radians: 1,
- yards: exports.earthRadius / 1.0936,
- };
- /**
- * Units of measurement factors based on 1 meter.
- *
- * @memberof helpers
- * @type {Object}
- */
- exports.unitsFactors = {
- centimeters: 100,
- centimetres: 100,
- degrees: 1 / 111325,
- feet: 3.28084,
- inches: 39.370,
- kilometers: 1 / 1000,
- kilometres: 1 / 1000,
- meters: 1,
- metres: 1,
- miles: 1 / 1609.344,
- millimeters: 1000,
- millimetres: 1000,
- nauticalmiles: 1 / 1852,
- radians: 1 / exports.earthRadius,
- yards: 1 / 1.0936,
- };
- /**
- * Area of measurement factors based on 1 square meter.
- *
- * @memberof helpers
- * @type {Object}
- */
- exports.areaFactors = {
- acres: 0.000247105,
- centimeters: 10000,
- centimetres: 10000,
- feet: 10.763910417,
- inches: 1550.003100006,
- kilometers: 0.000001,
- kilometres: 0.000001,
- meters: 1,
- metres: 1,
- miles: 3.86e-7,
- millimeters: 1000000,
- millimetres: 1000000,
- yards: 1.195990046,
- };
- /**
- * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.
- *
- * @name feature
- * @param {Geometry} geometry input geometry
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature} a GeoJSON Feature
- * @example
- * var geometry = {
- * "type": "Point",
- * "coordinates": [110, 50]
- * };
- *
- * var feature = turf.feature(geometry);
- *
- * //=feature
- */
- function feature(geom, properties, options) {
- if (options === void 0) { options = {}; }
- var feat = { type: "Feature" };
- if (options.id === 0 || options.id) {
- feat.id = options.id;
- }
- if (options.bbox) {
- feat.bbox = options.bbox;
- }
- feat.properties = properties || {};
- feat.geometry = geom;
- return feat;
- }
- exports.feature = feature;
- /**
- * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.
- * For GeometryCollection type use `helpers.geometryCollection`
- *
- * @name geometry
- * @param {string} type Geometry Type
- * @param {Array<any>} coordinates Coordinates
- * @param {Object} [options={}] Optional Parameters
- * @returns {Geometry} a GeoJSON Geometry
- * @example
- * var type = "Point";
- * var coordinates = [110, 50];
- * var geometry = turf.geometry(type, coordinates);
- * // => geometry
- */
- function geometry(type, coordinates, options) {
- if (options === void 0) { options = {}; }
- switch (type) {
- case "Point": return point(coordinates).geometry;
- case "LineString": return lineString(coordinates).geometry;
- case "Polygon": return polygon(coordinates).geometry;
- case "MultiPoint": return multiPoint(coordinates).geometry;
- case "MultiLineString": return multiLineString(coordinates).geometry;
- case "MultiPolygon": return multiPolygon(coordinates).geometry;
- default: throw new Error(type + " is invalid");
- }
- }
- exports.geometry = geometry;
- /**
- * Creates a {@link Point} {@link Feature} from a Position.
- *
- * @name point
- * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<Point>} a Point feature
- * @example
- * var point = turf.point([-75.343, 39.984]);
- *
- * //=point
- */
- function point(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- var geom = {
- type: "Point",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.point = point;
- /**
- * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.
- *
- * @name points
- * @param {Array<Array<number>>} coordinates an array of Points
- * @param {Object} [properties={}] Translate these properties to each Feature
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
- * associated with the FeatureCollection
- * @param {string|number} [options.id] Identifier associated with the FeatureCollection
- * @returns {FeatureCollection<Point>} Point Feature
- * @example
- * var points = turf.points([
- * [-75, 39],
- * [-80, 45],
- * [-78, 50]
- * ]);
- *
- * //=points
- */
- function points(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- return featureCollection(coordinates.map(function (coords) {
- return point(coords, properties);
- }), options);
- }
- exports.points = points;
- /**
- * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.
- *
- * @name polygon
- * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<Polygon>} Polygon Feature
- * @example
- * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });
- *
- * //=polygon
- */
- function polygon(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {
- var ring = coordinates_1[_i];
- if (ring.length < 4) {
- throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");
- }
- for (var j = 0; j < ring[ring.length - 1].length; j++) {
- // Check if first point of Polygon contains two numbers
- if (ring[ring.length - 1][j] !== ring[0][j]) {
- throw new Error("First and last Position are not equivalent.");
- }
- }
- }
- var geom = {
- type: "Polygon",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.polygon = polygon;
- /**
- * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.
- *
- * @name polygons
- * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the FeatureCollection
- * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection
- * @example
- * var polygons = turf.polygons([
- * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],
- * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],
- * ]);
- *
- * //=polygons
- */
- function polygons(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- return featureCollection(coordinates.map(function (coords) {
- return polygon(coords, properties);
- }), options);
- }
- exports.polygons = polygons;
- /**
- * Creates a {@link LineString} {@link Feature} from an Array of Positions.
- *
- * @name lineString
- * @param {Array<Array<number>>} coordinates an array of Positions
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<LineString>} LineString Feature
- * @example
- * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});
- * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});
- *
- * //=linestring1
- * //=linestring2
- */
- function lineString(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- if (coordinates.length < 2) {
- throw new Error("coordinates must be an array of two or more positions");
- }
- var geom = {
- type: "LineString",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.lineString = lineString;
- /**
- * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.
- *
- * @name lineStrings
- * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
- * associated with the FeatureCollection
- * @param {string|number} [options.id] Identifier associated with the FeatureCollection
- * @returns {FeatureCollection<LineString>} LineString FeatureCollection
- * @example
- * var linestrings = turf.lineStrings([
- * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],
- * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]
- * ]);
- *
- * //=linestrings
- */
- function lineStrings(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- return featureCollection(coordinates.map(function (coords) {
- return lineString(coords, properties);
- }), options);
- }
- exports.lineStrings = lineStrings;
- /**
- * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.
- *
- * @name featureCollection
- * @param {Feature[]} features input features
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {FeatureCollection} FeatureCollection of Features
- * @example
- * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});
- * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});
- * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});
- *
- * var collection = turf.featureCollection([
- * locationA,
- * locationB,
- * locationC
- * ]);
- *
- * //=collection
- */
- function featureCollection(features, options) {
- if (options === void 0) { options = {}; }
- var fc = { type: "FeatureCollection" };
- if (options.id) {
- fc.id = options.id;
- }
- if (options.bbox) {
- fc.bbox = options.bbox;
- }
- fc.features = features;
- return fc;
- }
- exports.featureCollection = featureCollection;
- /**
- * Creates a {@link Feature<MultiLineString>} based on a
- * coordinate array. Properties can be added optionally.
- *
- * @name multiLineString
- * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<MultiLineString>} a MultiLineString feature
- * @throws {Error} if no coordinates are passed
- * @example
- * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);
- *
- * //=multiLine
- */
- function multiLineString(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- var geom = {
- type: "MultiLineString",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.multiLineString = multiLineString;
- /**
- * Creates a {@link Feature<MultiPoint>} based on a
- * coordinate array. Properties can be added optionally.
- *
- * @name multiPoint
- * @param {Array<Array<number>>} coordinates an array of Positions
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<MultiPoint>} a MultiPoint feature
- * @throws {Error} if no coordinates are passed
- * @example
- * var multiPt = turf.multiPoint([[0,0],[10,10]]);
- *
- * //=multiPt
- */
- function multiPoint(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- var geom = {
- type: "MultiPoint",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.multiPoint = multiPoint;
- /**
- * Creates a {@link Feature<MultiPolygon>} based on a
- * coordinate array. Properties can be added optionally.
- *
- * @name multiPolygon
- * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<MultiPolygon>} a multipolygon feature
- * @throws {Error} if no coordinates are passed
- * @example
- * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
- *
- * //=multiPoly
- *
- */
- function multiPolygon(coordinates, properties, options) {
- if (options === void 0) { options = {}; }
- var geom = {
- type: "MultiPolygon",
- coordinates: coordinates,
- };
- return feature(geom, properties, options);
- }
- exports.multiPolygon = multiPolygon;
- /**
- * Creates a {@link Feature<GeometryCollection>} based on a
- * coordinate array. Properties can be added optionally.
- *
- * @name geometryCollection
- * @param {Array<Geometry>} geometries an array of GeoJSON Geometries
- * @param {Object} [properties={}] an Object of key-value pairs to add as properties
- * @param {Object} [options={}] Optional Parameters
- * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
- * @param {string|number} [options.id] Identifier associated with the Feature
- * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature
- * @example
- * var pt = turf.geometry("Point", [100, 0]);
- * var line = turf.geometry("LineString", [[101, 0], [102, 1]]);
- * var collection = turf.geometryCollection([pt, line]);
- *
- * // => collection
- */
- function geometryCollection(geometries, properties, options) {
- if (options === void 0) { options = {}; }
- var geom = {
- type: "GeometryCollection",
- geometries: geometries,
- };
- return feature(geom, properties, options);
- }
- exports.geometryCollection = geometryCollection;
- /**
- * Round number to precision
- *
- * @param {number} num Number
- * @param {number} [precision=0] Precision
- * @returns {number} rounded number
- * @example
- * turf.round(120.4321)
- * //=120
- *
- * turf.round(120.4321, 2)
- * //=120.43
- */
- function round(num, precision) {
- if (precision === void 0) { precision = 0; }
- if (precision && !(precision >= 0)) {
- throw new Error("precision must be a positive number");
- }
- var multiplier = Math.pow(10, precision || 0);
- return Math.round(num * multiplier) / multiplier;
- }
- exports.round = round;
- /**
- * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.
- * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
- *
- * @name radiansToLength
- * @param {number} radians in radians across the sphere
- * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
- * meters, kilometres, kilometers.
- * @returns {number} distance
- */
- function radiansToLength(radians, units) {
- if (units === void 0) { units = "kilometers"; }
- var factor = exports.factors[units];
- if (!factor) {
- throw new Error(units + " units is invalid");
- }
- return radians * factor;
- }
- exports.radiansToLength = radiansToLength;
- /**
- * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
- * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
- *
- * @name lengthToRadians
- * @param {number} distance in real units
- * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
- * meters, kilometres, kilometers.
- * @returns {number} radians
- */
- function lengthToRadians(distance, units) {
- if (units === void 0) { units = "kilometers"; }
- var factor = exports.factors[units];
- if (!factor) {
- throw new Error(units + " units is invalid");
- }
- return distance / factor;
- }
- exports.lengthToRadians = lengthToRadians;
- /**
- * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees
- * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet
- *
- * @name lengthToDegrees
- * @param {number} distance in real units
- * @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
- * meters, kilometres, kilometers.
- * @returns {number} degrees
- */
- function lengthToDegrees(distance, units) {
- return radiansToDegrees(lengthToRadians(distance, units));
- }
- exports.lengthToDegrees = lengthToDegrees;
- /**
- * Converts any bearing angle from the north line direction (positive clockwise)
- * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line
- *
- * @name bearingToAzimuth
- * @param {number} bearing angle, between -180 and +180 degrees
- * @returns {number} angle between 0 and 360 degrees
- */
- function bearingToAzimuth(bearing) {
- var angle = bearing % 360;
- if (angle < 0) {
- angle += 360;
- }
- return angle;
- }
- exports.bearingToAzimuth = bearingToAzimuth;
- /**
- * Converts an angle in radians to degrees
- *
- * @name radiansToDegrees
- * @param {number} radians angle in radians
- * @returns {number} degrees between 0 and 360 degrees
- */
- function radiansToDegrees(radians) {
- var degrees = radians % (2 * Math.PI);
- return degrees * 180 / Math.PI;
- }
- exports.radiansToDegrees = radiansToDegrees;
- /**
- * Converts an angle in degrees to radians
- *
- * @name degreesToRadians
- * @param {number} degrees angle between 0 and 360 degrees
- * @returns {number} angle in radians
- */
- function degreesToRadians(degrees) {
- var radians = degrees % 360;
- return radians * Math.PI / 180;
- }
- exports.degreesToRadians = degreesToRadians;
- /**
- * Converts a length to the requested unit.
- * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
- *
- * @param {number} length to be converted
- * @param {Units} [originalUnit="kilometers"] of the length
- * @param {Units} [finalUnit="kilometers"] returned unit
- * @returns {number} the converted length
- */
- function convertLength(length, originalUnit, finalUnit) {
- if (originalUnit === void 0) { originalUnit = "kilometers"; }
- if (finalUnit === void 0) { finalUnit = "kilometers"; }
- if (!(length >= 0)) {
- throw new Error("length must be a positive number");
- }
- return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);
- }
- exports.convertLength = convertLength;
- /**
- * Converts a area to the requested unit.
- * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches
- * @param {number} area to be converted
- * @param {Units} [originalUnit="meters"] of the distance
- * @param {Units} [finalUnit="kilometers"] returned unit
- * @returns {number} the converted distance
- */
- function convertArea(area, originalUnit, finalUnit) {
- if (originalUnit === void 0) { originalUnit = "meters"; }
- if (finalUnit === void 0) { finalUnit = "kilometers"; }
- if (!(area >= 0)) {
- throw new Error("area must be a positive number");
- }
- var startFactor = exports.areaFactors[originalUnit];
- if (!startFactor) {
- throw new Error("invalid original units");
- }
- var finalFactor = exports.areaFactors[finalUnit];
- if (!finalFactor) {
- throw new Error("invalid final units");
- }
- return (area / startFactor) * finalFactor;
- }
- exports.convertArea = convertArea;
- /**
- * isNumber
- *
- * @param {*} num Number to validate
- * @returns {boolean} true/false
- * @example
- * turf.isNumber(123)
- * //=true
- * turf.isNumber('foo')
- * //=false
- */
- function isNumber(num) {
- return !isNaN(num) && num !== null && !Array.isArray(num) && !/^\s*$/.test(num);
- }
- exports.isNumber = isNumber;
- /**
- * isObject
- *
- * @param {*} input variable to validate
- * @returns {boolean} true/false
- * @example
- * turf.isObject({elevation: 10})
- * //=true
- * turf.isObject('foo')
- * //=false
- */
- function isObject(input) {
- return (!!input) && (input.constructor === Object);
- }
- exports.isObject = isObject;
- /**
- * Validate BBox
- *
- * @private
- * @param {Array<number>} bbox BBox to validate
- * @returns {void}
- * @throws Error if BBox is not valid
- * @example
- * validateBBox([-180, -40, 110, 50])
- * //=OK
- * validateBBox([-180, -40])
- * //=Error
- * validateBBox('Foo')
- * //=Error
- * validateBBox(5)
- * //=Error
- * validateBBox(null)
- * //=Error
- * validateBBox(undefined)
- * //=Error
- */
- function validateBBox(bbox) {
- if (!bbox) {
- throw new Error("bbox is required");
- }
- if (!Array.isArray(bbox)) {
- throw new Error("bbox must be an Array");
- }
- if (bbox.length !== 4 && bbox.length !== 6) {
- throw new Error("bbox must be an Array of 4 or 6 numbers");
- }
- bbox.forEach(function (num) {
- if (!isNumber(num)) {
- throw new Error("bbox must only contain numbers");
- }
- });
- }
- exports.validateBBox = validateBBox;
- /**
- * Validate Id
- *
- * @private
- * @param {string|number} id Id to validate
- * @returns {void}
- * @throws Error if Id is not valid
- * @example
- * validateId([-180, -40, 110, 50])
- * //=Error
- * validateId([-180, -40])
- * //=Error
- * validateId('Foo')
- * //=OK
- * validateId(5)
- * //=OK
- * validateId(null)
- * //=Error
- * validateId(undefined)
- * //=Error
- */
- function validateId(id) {
- if (!id) {
- throw new Error("id is required");
- }
- if (["string", "number"].indexOf(typeof id) === -1) {
- throw new Error("id must be a number or a string");
- }
- }
- exports.validateId = validateId;
- // Deprecated methods
- function radians2degrees() {
- throw new Error("method has been renamed to `radiansToDegrees`");
- }
- exports.radians2degrees = radians2degrees;
- function degrees2radians() {
- throw new Error("method has been renamed to `degreesToRadians`");
- }
- exports.degrees2radians = degrees2radians;
- function distanceToDegrees() {
- throw new Error("method has been renamed to `lengthToDegrees`");
- }
- exports.distanceToDegrees = distanceToDegrees;
- function distanceToRadians() {
- throw new Error("method has been renamed to `lengthToRadians`");
- }
- exports.distanceToRadians = distanceToRadians;
- function radiansToDistance() {
- throw new Error("method has been renamed to `radiansToLength`");
- }
- exports.radiansToDistance = radiansToDistance;
- function bearingToAngle() {
- throw new Error("method has been renamed to `bearingToAzimuth`");
- }
- exports.bearingToAngle = bearingToAngle;
- function convertDistance() {
- throw new Error("method has been renamed to `convertLength`");
- }
- exports.convertDistance = convertDistance;
- },{}],12:[function(require,module,exports){
- "use strict";
- var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- var martinez = __importStar(require("martinez-polygon-clipping"));
- /**
- * Takes two {@link Polygon|polygon} or {@link MultiPolygon|multi-polygon} geometries and
- * finds their polygonal intersection. If they don't intersect, returns null.
- *
- * @name intersect
- * @param {Feature<Polygon | MultiPolygon>} poly1 the first polygon or multipolygon
- * @param {Feature<Polygon | MultiPolygon>} poly2 the second polygon or multipolygon
- * @param {Object} [options={}] Optional Parameters
- * @param {Object} [options.properties={}] Translate GeoJSON Properties to Feature
- * @returns {Feature|null} returns a feature representing the area they share (either a {@link Polygon} or
- * {@link MultiPolygon}). If they do not share any area, returns `null`.
- * @example
- * var poly1 = turf.polygon([[
- * [-122.801742, 45.48565],
- * [-122.801742, 45.60491],
- * [-122.584762, 45.60491],
- * [-122.584762, 45.48565],
- * [-122.801742, 45.48565]
- * ]]);
- *
- * var poly2 = turf.polygon([[
- * [-122.520217, 45.535693],
- * [-122.64038, 45.553967],
- * [-122.720031, 45.526554],
- * [-122.669906, 45.507309],
- * [-122.723464, 45.446643],
- * [-122.532577, 45.408574],
- * [-122.487258, 45.477466],
- * [-122.520217, 45.535693]
- * ]]);
- *
- * var intersection = turf.intersect(poly1, poly2);
- *
- * //addToMap
- * var addToMap = [poly1, poly2, intersection];
- */
- function intersect(poly1, poly2, options) {
- if (options === void 0) { options = {}; }
- var geom1 = invariant_1.getGeom(poly1);
- var geom2 = invariant_1.getGeom(poly2);
- if (geom1.type === "Polygon" && geom2.type === "Polygon") {
- var intersection = martinez.intersection(geom1.coordinates, geom2.coordinates);
- if (intersection === null || intersection.length === 0) {
- return null;
- }
- if (intersection.length === 1) {
- var start = intersection[0][0][0];
- var end = intersection[0][0][intersection[0][0].length - 1];
- if (start[0] === end[0] && start[1] === end[1]) {
- return helpers_1.polygon(intersection[0], options.properties);
- }
- return null;
- }
- return helpers_1.multiPolygon(intersection, options.properties);
- }
- else if (geom1.type === "MultiPolygon") {
- var resultCoords = [];
- // iterate through the polygon and run intersect with each part, adding to the resultCoords.
- for (var _i = 0, _a = geom1.coordinates; _i < _a.length; _i++) {
- var coords = _a[_i];
- var subGeom = invariant_1.getGeom(helpers_1.polygon(coords));
- var subIntersection = intersect(subGeom, geom2);
- if (subIntersection) {
- var subIntGeom = invariant_1.getGeom(subIntersection);
- if (subIntGeom.type === "Polygon") {
- resultCoords.push(subIntGeom.coordinates);
- }
- else if (subIntGeom.type === "MultiPolygon") {
- resultCoords = resultCoords.concat(subIntGeom.coordinates);
- }
- else {
- throw new Error("intersection is invalid");
- }
- }
- }
- // Make a polygon with the result
- if (resultCoords.length === 0) {
- return null;
- }
- if (resultCoords.length === 1) {
- return helpers_1.polygon(resultCoords[0], options.properties);
- }
- else {
- return helpers_1.multiPolygon(resultCoords, options.properties);
- }
- }
- else if (geom2.type === "MultiPolygon") {
- // geom1 is a polygon and geom2 a multiPolygon,
- // put the multiPolygon first and fallback to the previous case.
- return intersect(geom2, geom1);
- }
- else {
- // handle invalid geometry types
- throw new Error("poly1 and poly2 must be either polygons or multiPolygons");
- }
- }
- exports.default = intersect;
- },{"@turf/helpers":11,"@turf/invariant":13,"martinez-polygon-clipping":173}],13:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- /**
- * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.
- *
- * @name getCoord
- * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers
- * @returns {Array<number>} coordinates
- * @example
- * var pt = turf.point([10, 10]);
- *
- * var coord = turf.getCoord(pt);
- * //= [10, 10]
- */
- function getCoord(coord) {
- if (!coord) {
- throw new Error("coord is required");
- }
- if (!Array.isArray(coord)) {
- if (coord.type === "Feature" && coord.geometry !== null && coord.geometry.type === "Point") {
- return coord.geometry.coordinates;
- }
- if (coord.type === "Point") {
- return coord.coordinates;
- }
- }
- if (Array.isArray(coord) && coord.length >= 2 && !Array.isArray(coord[0]) && !Array.isArray(coord[1])) {
- return coord;
- }
- throw new Error("coord must be GeoJSON Point or an Array of numbers");
- }
- exports.getCoord = getCoord;
- /**
- * Unwrap coordinates from a Feature, Geometry Object or an Array
- *
- * @name getCoords
- * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array
- * @returns {Array<any>} coordinates
- * @example
- * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);
- *
- * var coords = turf.getCoords(poly);
- * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]
- */
- function getCoords(coords) {
- if (Array.isArray(coords)) {
- return coords;
- }
- // Feature
- if (coords.type === "Feature") {
- if (coords.geometry !== null) {
- return coords.geometry.coordinates;
- }
- }
- else {
- // Geometry
- if (coords.coordinates) {
- return coords.coordinates;
- }
- }
- throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array");
- }
- exports.getCoords = getCoords;
- /**
- * Checks if coordinates contains a number
- *
- * @name containsNumber
- * @param {Array<any>} coordinates GeoJSON Coordinates
- * @returns {boolean} true if Array contains a number
- */
- function containsNumber(coordinates) {
- if (coordinates.length > 1 && helpers_1.isNumber(coordinates[0]) && helpers_1.isNumber(coordinates[1])) {
- return true;
- }
- if (Array.isArray(coordinates[0]) && coordinates[0].length) {
- return containsNumber(coordinates[0]);
- }
- throw new Error("coordinates must only contain numbers");
- }
- exports.containsNumber = containsNumber;
- /**
- * Enforce expectations about types of GeoJSON objects for Turf.
- *
- * @name geojsonType
- * @param {GeoJSON} value any GeoJSON object
- * @param {string} type expected GeoJSON type
- * @param {string} name name of calling function
- * @throws {Error} if value is not the expected type.
- */
- function geojsonType(value, type, name) {
- if (!type || !name) {
- throw new Error("type and name required");
- }
- if (!value || value.type !== type) {
- throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + value.type);
- }
- }
- exports.geojsonType = geojsonType;
- /**
- * Enforce expectations about types of {@link Feature} inputs for Turf.
- * Internally this uses {@link geojsonType} to judge geometry types.
- *
- * @name featureOf
- * @param {Feature} feature a feature with an expected geometry type
- * @param {string} type expected GeoJSON type
- * @param {string} name name of calling function
- * @throws {Error} error if value is not the expected type.
- */
- function featureOf(feature, type, name) {
- if (!feature) {
- throw new Error("No feature passed");
- }
- if (!name) {
- throw new Error(".featureOf() requires a name");
- }
- if (!feature || feature.type !== "Feature" || !feature.geometry) {
- throw new Error("Invalid input to " + name + ", Feature with geometry required");
- }
- if (!feature.geometry || feature.geometry.type !== type) {
- throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + feature.geometry.type);
- }
- }
- exports.featureOf = featureOf;
- /**
- * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.
- * Internally this uses {@link geojsonType} to judge geometry types.
- *
- * @name collectionOf
- * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged
- * @param {string} type expected GeoJSON type
- * @param {string} name name of calling function
- * @throws {Error} if value is not the expected type.
- */
- function collectionOf(featureCollection, type, name) {
- if (!featureCollection) {
- throw new Error("No featureCollection passed");
- }
- if (!name) {
- throw new Error(".collectionOf() requires a name");
- }
- if (!featureCollection || featureCollection.type !== "FeatureCollection") {
- throw new Error("Invalid input to " + name + ", FeatureCollection required");
- }
- for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {
- var feature = _a[_i];
- if (!feature || feature.type !== "Feature" || !feature.geometry) {
- throw new Error("Invalid input to " + name + ", Feature with geometry required");
- }
- if (!feature.geometry || feature.geometry.type !== type) {
- throw new Error("Invalid input to " + name + ": must be a " + type + ", given " + feature.geometry.type);
- }
- }
- }
- exports.collectionOf = collectionOf;
- /**
- * Get Geometry from Feature or Geometry Object
- *
- * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object
- * @returns {Geometry|null} GeoJSON Geometry Object
- * @throws {Error} if geojson is not a Feature or Geometry Object
- * @example
- * var point = {
- * "type": "Feature",
- * "properties": {},
- * "geometry": {
- * "type": "Point",
- * "coordinates": [110, 40]
- * }
- * }
- * var geom = turf.getGeom(point)
- * //={"type": "Point", "coordinates": [110, 40]}
- */
- function getGeom(geojson) {
- if (geojson.type === "Feature") {
- return geojson.geometry;
- }
- return geojson;
- }
- exports.getGeom = getGeom;
- /**
- * Get GeoJSON object's type, Geometry type is prioritize.
- *
- * @param {GeoJSON} geojson GeoJSON object
- * @param {string} [name="geojson"] name of the variable to display in error message
- * @returns {string} GeoJSON type
- * @example
- * var point = {
- * "type": "Feature",
- * "properties": {},
- * "geometry": {
- * "type": "Point",
- * "coordinates": [110, 40]
- * }
- * }
- * var geom = turf.getType(point)
- * //="Point"
- */
- function getType(geojson, name) {
- if (geojson.type === "FeatureCollection") {
- return "FeatureCollection";
- }
- if (geojson.type === "GeometryCollection") {
- return "GeometryCollection";
- }
- if (geojson.type === "Feature" && geojson.geometry !== null) {
- return geojson.geometry.type;
- }
- return geojson.type;
- }
- exports.getType = getType;
- },{"@turf/helpers":11}],14:[function(require,module,exports){
- "use strict";
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- }
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- var line_segment_1 = __importDefault(require("@turf/line-segment"));
- var meta_1 = require("@turf/meta");
- var geojson_rbush_1 = __importDefault(require("geojson-rbush"));
- /**
- * Takes any LineString or Polygon GeoJSON and returns the intersecting point(s).
- *
- * @name lineIntersect
- * @param {GeoJSON} line1 any LineString or Polygon
- * @param {GeoJSON} line2 any LineString or Polygon
- * @returns {FeatureCollection<Point>} point(s) that intersect both
- * @example
- * var line1 = turf.lineString([[126, -11], [129, -21]]);
- * var line2 = turf.lineString([[123, -18], [131, -14]]);
- * var intersects = turf.lineIntersect(line1, line2);
- *
- * //addToMap
- * var addToMap = [line1, line2, intersects]
- */
- function lineIntersect(line1, line2) {
- var unique = {};
- var results = [];
- // First, normalize geometries to features
- // Then, handle simple 2-vertex segments
- if (line1.type === "LineString") {
- line1 = helpers_1.feature(line1);
- }
- if (line2.type === "LineString") {
- line2 = helpers_1.feature(line2);
- }
- if (line1.type === "Feature" &&
- line2.type === "Feature" &&
- line1.geometry !== null &&
- line2.geometry !== null &&
- line1.geometry.type === "LineString" &&
- line2.geometry.type === "LineString" &&
- line1.geometry.coordinates.length === 2 &&
- line2.geometry.coordinates.length === 2) {
- var intersect = intersects(line1, line2);
- if (intersect) {
- results.push(intersect);
- }
- return helpers_1.featureCollection(results);
- }
- // Handles complex GeoJSON Geometries
- var tree = geojson_rbush_1.default();
- tree.load(line_segment_1.default(line2));
- meta_1.featureEach(line_segment_1.default(line1), function (segment) {
- meta_1.featureEach(tree.search(segment), function (match) {
- var intersect = intersects(segment, match);
- if (intersect) {
- // prevent duplicate points https://github.com/Turfjs/turf/issues/688
- var key = invariant_1.getCoords(intersect).join(",");
- if (!unique[key]) {
- unique[key] = true;
- results.push(intersect);
- }
- }
- });
- });
- return helpers_1.featureCollection(results);
- }
- /**
- * Find a point that intersects LineStrings with two coordinates each
- *
- * @private
- * @param {Feature<LineString>} line1 GeoJSON LineString (Must only contain 2 coordinates)
- * @param {Feature<LineString>} line2 GeoJSON LineString (Must only contain 2 coordinates)
- * @returns {Feature<Point>} intersecting GeoJSON Point
- */
- function intersects(line1, line2) {
- var coords1 = invariant_1.getCoords(line1);
- var coords2 = invariant_1.getCoords(line2);
- if (coords1.length !== 2) {
- throw new Error("<intersects> line1 must only contain 2 coordinates");
- }
- if (coords2.length !== 2) {
- throw new Error("<intersects> line2 must only contain 2 coordinates");
- }
- var x1 = coords1[0][0];
- var y1 = coords1[0][1];
- var x2 = coords1[1][0];
- var y2 = coords1[1][1];
- var x3 = coords2[0][0];
- var y3 = coords2[0][1];
- var x4 = coords2[1][0];
- var y4 = coords2[1][1];
- var denom = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1));
- var numeA = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3));
- var numeB = ((x2 - x1) * (y1 - y3)) - ((y2 - y1) * (x1 - x3));
- if (denom === 0) {
- if (numeA === 0 && numeB === 0) {
- return null;
- }
- return null;
- }
- var uA = numeA / denom;
- var uB = numeB / denom;
- if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
- var x = x1 + (uA * (x2 - x1));
- var y = y1 + (uA * (y2 - y1));
- return helpers_1.point([x, y]);
- }
- return null;
- }
- exports.default = lineIntersect;
- },{"@turf/helpers":11,"@turf/invariant":13,"@turf/line-segment":15,"@turf/meta":16,"geojson-rbush":44}],15:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- var meta_1 = require("@turf/meta");
- /**
- * Creates a {@link FeatureCollection} of 2-vertex {@link LineString} segments from a
- * {@link LineString|(Multi)LineString} or {@link Polygon|(Multi)Polygon}.
- *
- * @name lineSegment
- * @param {GeoJSON} geojson GeoJSON Polygon or LineString
- * @returns {FeatureCollection<LineString>} 2-vertex line segments
- * @example
- * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
- * var segments = turf.lineSegment(polygon);
- *
- * //addToMap
- * var addToMap = [polygon, segments]
- */
- function lineSegment(geojson) {
- if (!geojson) {
- throw new Error("geojson is required");
- }
- var results = [];
- meta_1.flattenEach(geojson, function (feature) {
- lineSegmentFeature(feature, results);
- });
- return helpers_1.featureCollection(results);
- }
- /**
- * Line Segment
- *
- * @private
- * @param {Feature<LineString|Polygon>} geojson Line or polygon feature
- * @param {Array} results push to results
- * @returns {void}
- */
- function lineSegmentFeature(geojson, results) {
- var coords = [];
- var geometry = geojson.geometry;
- if (geometry !== null) {
- switch (geometry.type) {
- case "Polygon":
- coords = invariant_1.getCoords(geometry);
- break;
- case "LineString":
- coords = [invariant_1.getCoords(geometry)];
- }
- coords.forEach(function (coord) {
- var segments = createSegments(coord, geojson.properties);
- segments.forEach(function (segment) {
- segment.id = results.length;
- results.push(segment);
- });
- });
- }
- }
- /**
- * Create Segments from LineString coordinates
- *
- * @private
- * @param {Array<Array<number>>} coords LineString coordinates
- * @param {*} properties GeoJSON properties
- * @returns {Array<Feature<LineString>>} line segments
- */
- function createSegments(coords, properties) {
- var segments = [];
- coords.reduce(function (previousCoords, currentCoords) {
- var segment = helpers_1.lineString([previousCoords, currentCoords], properties);
- segment.bbox = bbox(previousCoords, currentCoords);
- segments.push(segment);
- return currentCoords;
- });
- return segments;
- }
- /**
- * Create BBox between two coordinates (faster than @turf/bbox)
- *
- * @private
- * @param {Array<number>} coords1 Point coordinate
- * @param {Array<number>} coords2 Point coordinate
- * @returns {BBox} [west, south, east, north]
- */
- function bbox(coords1, coords2) {
- var x1 = coords1[0];
- var y1 = coords1[1];
- var x2 = coords2[0];
- var y2 = coords2[1];
- var west = (x1 < x2) ? x1 : x2;
- var south = (y1 < y2) ? y1 : y2;
- var east = (x1 > x2) ? x1 : x2;
- var north = (y1 > y2) ? y1 : y2;
- return [west, south, east, north];
- }
- exports.default = lineSegment;
- },{"@turf/helpers":11,"@turf/invariant":13,"@turf/meta":16}],16:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, '__esModule', { value: true });
- var helpers = require('@turf/helpers');
- /**
- * Callback for coordEach
- *
- * @callback coordEachCallback
- * @param {Array<number>} currentCoord The current coordinate being processed.
- * @param {number} coordIndex The current index of the coordinate being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- * @param {number} geometryIndex The current index of the Geometry being processed.
- */
- /**
- * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()
- *
- * @name coordEach
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)
- * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
- * @returns {void}
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {"foo": "bar"}),
- * turf.point([36, 53], {"hello": "world"})
- * ]);
- *
- * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
- * //=currentCoord
- * //=coordIndex
- * //=featureIndex
- * //=multiFeatureIndex
- * //=geometryIndex
- * });
- */
- function coordEach(geojson, callback, excludeWrapCoord) {
- // Handles null Geometry -- Skips this GeoJSON
- if (geojson === null) return;
- var j, k, l, geometry, stopG, coords,
- geometryMaybeCollection,
- wrapShrink = 0,
- coordIndex = 0,
- isGeometryCollection,
- type = geojson.type,
- isFeatureCollection = type === 'FeatureCollection',
- isFeature = type === 'Feature',
- stop = isFeatureCollection ? geojson.features.length : 1;
- // This logic may look a little weird. The reason why it is that way
- // is because it's trying to be fast. GeoJSON supports multiple kinds
- // of objects at its root: FeatureCollection, Features, Geometries.
- // This function has the responsibility of handling all of them, and that
- // means that some of the `for` loops you see below actually just don't apply
- // to certain inputs. For instance, if you give this just a
- // Point geometry, then both loops are short-circuited and all we do
- // is gradually rename the input until it's called 'geometry'.
- //
- // This also aims to allocate as few resources as possible: just a
- // few numbers and booleans, rather than any temporary arrays as would
- // be required with the normalization approach.
- for (var featureIndex = 0; featureIndex < stop; featureIndex++) {
- geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :
- (isFeature ? geojson.geometry : geojson));
- isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;
- stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
- for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {
- var multiFeatureIndex = 0;
- var geometryIndex = 0;
- geometry = isGeometryCollection ?
- geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;
- // Handles null Geometry -- Skips this geometry
- if (geometry === null) continue;
- coords = geometry.coordinates;
- var geomType = geometry.type;
- wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;
- switch (geomType) {
- case null:
- break;
- case 'Point':
- if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
- coordIndex++;
- multiFeatureIndex++;
- break;
- case 'LineString':
- case 'MultiPoint':
- for (j = 0; j < coords.length; j++) {
- if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
- coordIndex++;
- if (geomType === 'MultiPoint') multiFeatureIndex++;
- }
- if (geomType === 'LineString') multiFeatureIndex++;
- break;
- case 'Polygon':
- case 'MultiLineString':
- for (j = 0; j < coords.length; j++) {
- for (k = 0; k < coords[j].length - wrapShrink; k++) {
- if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
- coordIndex++;
- }
- if (geomType === 'MultiLineString') multiFeatureIndex++;
- if (geomType === 'Polygon') geometryIndex++;
- }
- if (geomType === 'Polygon') multiFeatureIndex++;
- break;
- case 'MultiPolygon':
- for (j = 0; j < coords.length; j++) {
- geometryIndex = 0;
- for (k = 0; k < coords[j].length; k++) {
- for (l = 0; l < coords[j][k].length - wrapShrink; l++) {
- if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
- coordIndex++;
- }
- geometryIndex++;
- }
- multiFeatureIndex++;
- }
- break;
- case 'GeometryCollection':
- for (j = 0; j < geometry.geometries.length; j++)
- if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;
- break;
- default:
- throw new Error('Unknown Geometry Type');
- }
- }
- }
- }
- /**
- * Callback for coordReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback coordReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Array<number>} currentCoord The current coordinate being processed.
- * @param {number} coordIndex The current index of the coordinate being processed.
- * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- * @param {number} geometryIndex The current index of the Geometry being processed.
- */
- /**
- * Reduce coordinates in any GeoJSON object, similar to Array.reduce()
- *
- * @name coordReduce
- * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object
- * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
- * @returns {*} The value that results from the reduction.
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {"foo": "bar"}),
- * turf.point([36, 53], {"hello": "world"})
- * ]);
- *
- * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
- * //=previousValue
- * //=currentCoord
- * //=coordIndex
- * //=featureIndex
- * //=multiFeatureIndex
- * //=geometryIndex
- * return currentCoord;
- * });
- */
- function coordReduce(geojson, callback, initialValue, excludeWrapCoord) {
- var previousValue = initialValue;
- coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
- if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;
- else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);
- }, excludeWrapCoord);
- return previousValue;
- }
- /**
- * Callback for propEach
- *
- * @callback propEachCallback
- * @param {Object} currentProperties The current Properties being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- */
- /**
- * Iterate over properties in any GeoJSON object, similar to Array.forEach()
- *
- * @name propEach
- * @param {FeatureCollection|Feature} geojson any GeoJSON object
- * @param {Function} callback a method that takes (currentProperties, featureIndex)
- * @returns {void}
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * turf.propEach(features, function (currentProperties, featureIndex) {
- * //=currentProperties
- * //=featureIndex
- * });
- */
- function propEach(geojson, callback) {
- var i;
- switch (geojson.type) {
- case 'FeatureCollection':
- for (i = 0; i < geojson.features.length; i++) {
- if (callback(geojson.features[i].properties, i) === false) break;
- }
- break;
- case 'Feature':
- callback(geojson.properties, 0);
- break;
- }
- }
- /**
- * Callback for propReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback propReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {*} currentProperties The current Properties being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- */
- /**
- * Reduce properties in any GeoJSON object into a single value,
- * similar to how Array.reduce works. However, in this case we lazily run
- * the reduction, so an array of all properties is unnecessary.
- *
- * @name propReduce
- * @param {FeatureCollection|Feature} geojson any GeoJSON object
- * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {*} The value that results from the reduction.
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {
- * //=previousValue
- * //=currentProperties
- * //=featureIndex
- * return currentProperties
- * });
- */
- function propReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- propEach(geojson, function (currentProperties, featureIndex) {
- if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;
- else previousValue = callback(previousValue, currentProperties, featureIndex);
- });
- return previousValue;
- }
- /**
- * Callback for featureEach
- *
- * @callback featureEachCallback
- * @param {Feature<any>} currentFeature The current Feature being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- */
- /**
- * Iterate over features in any GeoJSON object, similar to
- * Array.forEach.
- *
- * @name featureEach
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (currentFeature, featureIndex)
- * @returns {void}
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * turf.featureEach(features, function (currentFeature, featureIndex) {
- * //=currentFeature
- * //=featureIndex
- * });
- */
- function featureEach(geojson, callback) {
- if (geojson.type === 'Feature') {
- callback(geojson, 0);
- } else if (geojson.type === 'FeatureCollection') {
- for (var i = 0; i < geojson.features.length; i++) {
- if (callback(geojson.features[i], i) === false) break;
- }
- }
- }
- /**
- * Callback for featureReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback featureReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Feature} currentFeature The current Feature being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- */
- /**
- * Reduce features in any GeoJSON object, similar to Array.reduce().
- *
- * @name featureReduce
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {*} The value that results from the reduction.
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {"foo": "bar"}),
- * turf.point([36, 53], {"hello": "world"})
- * ]);
- *
- * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {
- * //=previousValue
- * //=currentFeature
- * //=featureIndex
- * return currentFeature
- * });
- */
- function featureReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- featureEach(geojson, function (currentFeature, featureIndex) {
- if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;
- else previousValue = callback(previousValue, currentFeature, featureIndex);
- });
- return previousValue;
- }
- /**
- * Get all coordinates from any GeoJSON object.
- *
- * @name coordAll
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @returns {Array<Array<number>>} coordinate position array
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * var coords = turf.coordAll(features);
- * //= [[26, 37], [36, 53]]
- */
- function coordAll(geojson) {
- var coords = [];
- coordEach(geojson, function (coord) {
- coords.push(coord);
- });
- return coords;
- }
- /**
- * Callback for geomEach
- *
- * @callback geomEachCallback
- * @param {Geometry} currentGeometry The current Geometry being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {Object} featureProperties The current Feature Properties being processed.
- * @param {Array<number>} featureBBox The current Feature BBox being processed.
- * @param {number|string} featureId The current Feature Id being processed.
- */
- /**
- * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()
- *
- * @name geomEach
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)
- * @returns {void}
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
- * //=currentGeometry
- * //=featureIndex
- * //=featureProperties
- * //=featureBBox
- * //=featureId
- * });
- */
- function geomEach(geojson, callback) {
- var i, j, g, geometry, stopG,
- geometryMaybeCollection,
- isGeometryCollection,
- featureProperties,
- featureBBox,
- featureId,
- featureIndex = 0,
- isFeatureCollection = geojson.type === 'FeatureCollection',
- isFeature = geojson.type === 'Feature',
- stop = isFeatureCollection ? geojson.features.length : 1;
- // This logic may look a little weird. The reason why it is that way
- // is because it's trying to be fast. GeoJSON supports multiple kinds
- // of objects at its root: FeatureCollection, Features, Geometries.
- // This function has the responsibility of handling all of them, and that
- // means that some of the `for` loops you see below actually just don't apply
- // to certain inputs. For instance, if you give this just a
- // Point geometry, then both loops are short-circuited and all we do
- // is gradually rename the input until it's called 'geometry'.
- //
- // This also aims to allocate as few resources as possible: just a
- // few numbers and booleans, rather than any temporary arrays as would
- // be required with the normalization approach.
- for (i = 0; i < stop; i++) {
- geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :
- (isFeature ? geojson.geometry : geojson));
- featureProperties = (isFeatureCollection ? geojson.features[i].properties :
- (isFeature ? geojson.properties : {}));
- featureBBox = (isFeatureCollection ? geojson.features[i].bbox :
- (isFeature ? geojson.bbox : undefined));
- featureId = (isFeatureCollection ? geojson.features[i].id :
- (isFeature ? geojson.id : undefined));
- isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;
- stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
- for (g = 0; g < stopG; g++) {
- geometry = isGeometryCollection ?
- geometryMaybeCollection.geometries[g] : geometryMaybeCollection;
- // Handle null Geometry
- if (geometry === null) {
- if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;
- continue;
- }
- switch (geometry.type) {
- case 'Point':
- case 'LineString':
- case 'MultiPoint':
- case 'Polygon':
- case 'MultiLineString':
- case 'MultiPolygon': {
- if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;
- break;
- }
- case 'GeometryCollection': {
- for (j = 0; j < geometry.geometries.length; j++) {
- if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;
- }
- break;
- }
- default:
- throw new Error('Unknown Geometry Type');
- }
- }
- // Only increase `featureIndex` per each feature
- featureIndex++;
- }
- }
- /**
- * Callback for geomReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback geomReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Geometry} currentGeometry The current Geometry being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {Object} featureProperties The current Feature Properties being processed.
- * @param {Array<number>} featureBBox The current Feature BBox being processed.
- * @param {number|string} featureId The current Feature Id being processed.
- */
- /**
- * Reduce geometry in any GeoJSON object, similar to Array.reduce().
- *
- * @name geomReduce
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {*} The value that results from the reduction.
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.point([36, 53], {hello: 'world'})
- * ]);
- *
- * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
- * //=previousValue
- * //=currentGeometry
- * //=featureIndex
- * //=featureProperties
- * //=featureBBox
- * //=featureId
- * return currentGeometry
- * });
- */
- function geomReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
- if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;
- else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);
- });
- return previousValue;
- }
- /**
- * Callback for flattenEach
- *
- * @callback flattenEachCallback
- * @param {Feature} currentFeature The current flattened feature being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- */
- /**
- * Iterate over flattened features in any GeoJSON object, similar to
- * Array.forEach.
- *
- * @name flattenEach
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
- * ]);
- *
- * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {
- * //=currentFeature
- * //=featureIndex
- * //=multiFeatureIndex
- * });
- */
- function flattenEach(geojson, callback) {
- geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {
- // Callback for single geometry
- var type = (geometry === null) ? null : geometry.type;
- switch (type) {
- case null:
- case 'Point':
- case 'LineString':
- case 'Polygon':
- if (callback(helpers.feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;
- return;
- }
- var geomType;
- // Callback for multi-geometry
- switch (type) {
- case 'MultiPoint':
- geomType = 'Point';
- break;
- case 'MultiLineString':
- geomType = 'LineString';
- break;
- case 'MultiPolygon':
- geomType = 'Polygon';
- break;
- }
- for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {
- var coordinate = geometry.coordinates[multiFeatureIndex];
- var geom = {
- type: geomType,
- coordinates: coordinate
- };
- if (callback(helpers.feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;
- }
- });
- }
- /**
- * Callback for flattenReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback flattenReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Feature} currentFeature The current Feature being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- */
- /**
- * Reduce flattened features in any GeoJSON object, similar to Array.reduce().
- *
- * @name flattenReduce
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
- * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {*} The value that results from the reduction.
- * @example
- * var features = turf.featureCollection([
- * turf.point([26, 37], {foo: 'bar'}),
- * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})
- * ]);
- *
- * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {
- * //=previousValue
- * //=currentFeature
- * //=featureIndex
- * //=multiFeatureIndex
- * return currentFeature
- * });
- */
- function flattenReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {
- if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;
- else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);
- });
- return previousValue;
- }
- /**
- * Callback for segmentEach
- *
- * @callback segmentEachCallback
- * @param {Feature<LineString>} currentSegment The current Segment being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- * @param {number} geometryIndex The current index of the Geometry being processed.
- * @param {number} segmentIndex The current index of the Segment being processed.
- * @returns {void}
- */
- /**
- * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()
- * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
- *
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON
- * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)
- * @returns {void}
- * @example
- * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
- *
- * // Iterate over GeoJSON by 2-vertex segments
- * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
- * //=currentSegment
- * //=featureIndex
- * //=multiFeatureIndex
- * //=geometryIndex
- * //=segmentIndex
- * });
- *
- * // Calculate the total number of segments
- * var total = 0;
- * turf.segmentEach(polygon, function () {
- * total++;
- * });
- */
- function segmentEach(geojson, callback) {
- flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {
- var segmentIndex = 0;
- // Exclude null Geometries
- if (!feature.geometry) return;
- // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
- var type = feature.geometry.type;
- if (type === 'Point' || type === 'MultiPoint') return;
- // Generate 2-vertex line segments
- var previousCoords;
- var previousFeatureIndex = 0;
- var previousMultiIndex = 0;
- var prevGeomIndex = 0;
- if (coordEach(feature, function (currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex) {
- // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`
- if (previousCoords === undefined || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex) {
- previousCoords = currentCoord;
- previousFeatureIndex = featureIndex;
- previousMultiIndex = multiPartIndexCoord;
- prevGeomIndex = geometryIndex;
- segmentIndex = 0;
- return;
- }
- var currentSegment = helpers.lineString([previousCoords, currentCoord], feature.properties);
- if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;
- segmentIndex++;
- previousCoords = currentCoord;
- }) === false) return false;
- });
- }
- /**
- * Callback for segmentReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback segmentReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Feature<LineString>} currentSegment The current Segment being processed.
- * @param {number} featureIndex The current index of the Feature being processed.
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
- * @param {number} geometryIndex The current index of the Geometry being processed.
- * @param {number} segmentIndex The current index of the Segment being processed.
- */
- /**
- * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()
- * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.
- *
- * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON
- * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {void}
- * @example
- * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);
- *
- * // Iterate over GeoJSON by 2-vertex segments
- * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
- * //= previousSegment
- * //= currentSegment
- * //= featureIndex
- * //= multiFeatureIndex
- * //= geometryIndex
- * //= segmentInex
- * return currentSegment
- * });
- *
- * // Calculate the total number of segments
- * var initialValue = 0
- * var total = turf.segmentReduce(polygon, function (previousValue) {
- * previousValue++;
- * return previousValue;
- * }, initialValue);
- */
- function segmentReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- var started = false;
- segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
- if (started === false && initialValue === undefined) previousValue = currentSegment;
- else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);
- started = true;
- });
- return previousValue;
- }
- /**
- * Callback for lineEach
- *
- * @callback lineEachCallback
- * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed
- * @param {number} featureIndex The current index of the Feature being processed
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed
- * @param {number} geometryIndex The current index of the Geometry being processed
- */
- /**
- * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,
- * similar to Array.forEach.
- *
- * @name lineEach
- * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
- * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)
- * @example
- * var multiLine = turf.multiLineString([
- * [[26, 37], [35, 45]],
- * [[36, 53], [38, 50], [41, 55]]
- * ]);
- *
- * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
- * //=currentLine
- * //=featureIndex
- * //=multiFeatureIndex
- * //=geometryIndex
- * });
- */
- function lineEach(geojson, callback) {
- // validation
- if (!geojson) throw new Error('geojson is required');
- flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {
- if (feature.geometry === null) return;
- var type = feature.geometry.type;
- var coords = feature.geometry.coordinates;
- switch (type) {
- case 'LineString':
- if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false) return false;
- break;
- case 'Polygon':
- for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {
- if (callback(helpers.lineString(coords[geometryIndex], feature.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
- }
- break;
- }
- });
- }
- /**
- * Callback for lineReduce
- *
- * The first time the callback function is called, the values provided as arguments depend
- * on whether the reduce method has an initialValue argument.
- *
- * If an initialValue is provided to the reduce method:
- * - The previousValue argument is initialValue.
- * - The currentValue argument is the value of the first element present in the array.
- *
- * If an initialValue is not provided:
- * - The previousValue argument is the value of the first element present in the array.
- * - The currentValue argument is the value of the second element present in the array.
- *
- * @callback lineReduceCallback
- * @param {*} previousValue The accumulated value previously returned in the last invocation
- * of the callback, or initialValue, if supplied.
- * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.
- * @param {number} featureIndex The current index of the Feature being processed
- * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed
- * @param {number} geometryIndex The current index of the Geometry being processed
- */
- /**
- * Reduce features in any GeoJSON object, similar to Array.reduce().
- *
- * @name lineReduce
- * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object
- * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)
- * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
- * @returns {*} The value that results from the reduction.
- * @example
- * var multiPoly = turf.multiPolygon([
- * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),
- * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])
- * ]);
- *
- * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
- * //=previousValue
- * //=currentLine
- * //=featureIndex
- * //=multiFeatureIndex
- * //=geometryIndex
- * return currentLine
- * });
- */
- function lineReduce(geojson, callback, initialValue) {
- var previousValue = initialValue;
- lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
- if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;
- else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);
- });
- return previousValue;
- }
- /**
- * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.
- *
- * Negative indexes are permitted.
- * Point & MultiPoint will always return null.
- *
- * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry
- * @param {Object} [options={}] Optional parameters
- * @param {number} [options.featureIndex=0] Feature Index
- * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index
- * @param {number} [options.geometryIndex=0] Geometry Index
- * @param {number} [options.segmentIndex=0] Segment Index
- * @param {Object} [options.properties={}] Translate Properties to output LineString
- * @param {BBox} [options.bbox={}] Translate BBox to output LineString
- * @param {number|string} [options.id={}] Translate Id to output LineString
- * @returns {Feature<LineString>} 2-vertex GeoJSON Feature LineString
- * @example
- * var multiLine = turf.multiLineString([
- * [[10, 10], [50, 30], [30, 40]],
- * [[-10, -10], [-50, -30], [-30, -40]]
- * ]);
- *
- * // First Segment (defaults are 0)
- * turf.findSegment(multiLine);
- * // => Feature<LineString<[[10, 10], [50, 30]]>>
- *
- * // First Segment of 2nd Multi Feature
- * turf.findSegment(multiLine, {multiFeatureIndex: 1});
- * // => Feature<LineString<[[-10, -10], [-50, -30]]>>
- *
- * // Last Segment of Last Multi Feature
- * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});
- * // => Feature<LineString<[[-50, -30], [-30, -40]]>>
- */
- function findSegment(geojson, options) {
- // Optional Parameters
- options = options || {};
- if (!helpers.isObject(options)) throw new Error('options is invalid');
- var featureIndex = options.featureIndex || 0;
- var multiFeatureIndex = options.multiFeatureIndex || 0;
- var geometryIndex = options.geometryIndex || 0;
- var segmentIndex = options.segmentIndex || 0;
- // Find FeatureIndex
- var properties = options.properties;
- var geometry;
- switch (geojson.type) {
- case 'FeatureCollection':
- if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;
- properties = properties || geojson.features[featureIndex].properties;
- geometry = geojson.features[featureIndex].geometry;
- break;
- case 'Feature':
- properties = properties || geojson.properties;
- geometry = geojson.geometry;
- break;
- case 'Point':
- case 'MultiPoint':
- return null;
- case 'LineString':
- case 'Polygon':
- case 'MultiLineString':
- case 'MultiPolygon':
- geometry = geojson;
- break;
- default:
- throw new Error('geojson is invalid');
- }
- // Find SegmentIndex
- if (geometry === null) return null;
- var coords = geometry.coordinates;
- switch (geometry.type) {
- case 'Point':
- case 'MultiPoint':
- return null;
- case 'LineString':
- if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;
- return helpers.lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);
- case 'Polygon':
- if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
- if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;
- return helpers.lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);
- case 'MultiLineString':
- if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
- if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;
- return helpers.lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);
- case 'MultiPolygon':
- if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
- if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
- if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;
- return helpers.lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);
- }
- throw new Error('geojson is invalid');
- }
- /**
- * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.
- *
- * Negative indexes are permitted.
- *
- * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry
- * @param {Object} [options={}] Optional parameters
- * @param {number} [options.featureIndex=0] Feature Index
- * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index
- * @param {number} [options.geometryIndex=0] Geometry Index
- * @param {number} [options.coordIndex=0] Coord Index
- * @param {Object} [options.properties={}] Translate Properties to output Point
- * @param {BBox} [options.bbox={}] Translate BBox to output Point
- * @param {number|string} [options.id={}] Translate Id to output Point
- * @returns {Feature<Point>} 2-vertex GeoJSON Feature Point
- * @example
- * var multiLine = turf.multiLineString([
- * [[10, 10], [50, 30], [30, 40]],
- * [[-10, -10], [-50, -30], [-30, -40]]
- * ]);
- *
- * // First Segment (defaults are 0)
- * turf.findPoint(multiLine);
- * // => Feature<Point<[10, 10]>>
- *
- * // First Segment of the 2nd Multi-Feature
- * turf.findPoint(multiLine, {multiFeatureIndex: 1});
- * // => Feature<Point<[-10, -10]>>
- *
- * // Last Segment of last Multi-Feature
- * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});
- * // => Feature<Point<[-30, -40]>>
- */
- function findPoint(geojson, options) {
- // Optional Parameters
- options = options || {};
- if (!helpers.isObject(options)) throw new Error('options is invalid');
- var featureIndex = options.featureIndex || 0;
- var multiFeatureIndex = options.multiFeatureIndex || 0;
- var geometryIndex = options.geometryIndex || 0;
- var coordIndex = options.coordIndex || 0;
- // Find FeatureIndex
- var properties = options.properties;
- var geometry;
- switch (geojson.type) {
- case 'FeatureCollection':
- if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;
- properties = properties || geojson.features[featureIndex].properties;
- geometry = geojson.features[featureIndex].geometry;
- break;
- case 'Feature':
- properties = properties || geojson.properties;
- geometry = geojson.geometry;
- break;
- case 'Point':
- case 'MultiPoint':
- return null;
- case 'LineString':
- case 'Polygon':
- case 'MultiLineString':
- case 'MultiPolygon':
- geometry = geojson;
- break;
- default:
- throw new Error('geojson is invalid');
- }
- // Find Coord Index
- if (geometry === null) return null;
- var coords = geometry.coordinates;
- switch (geometry.type) {
- case 'Point':
- return helpers.point(coords, properties, options);
- case 'MultiPoint':
- if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
- return helpers.point(coords[multiFeatureIndex], properties, options);
- case 'LineString':
- if (coordIndex < 0) coordIndex = coords.length + coordIndex;
- return helpers.point(coords[coordIndex], properties, options);
- case 'Polygon':
- if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
- if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;
- return helpers.point(coords[geometryIndex][coordIndex], properties, options);
- case 'MultiLineString':
- if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
- if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;
- return helpers.point(coords[multiFeatureIndex][coordIndex], properties, options);
- case 'MultiPolygon':
- if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;
- if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
- if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;
- return helpers.point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);
- }
- throw new Error('geojson is invalid');
- }
- exports.coordEach = coordEach;
- exports.coordReduce = coordReduce;
- exports.propEach = propEach;
- exports.propReduce = propReduce;
- exports.featureEach = featureEach;
- exports.featureReduce = featureReduce;
- exports.coordAll = coordAll;
- exports.geomEach = geomEach;
- exports.geomReduce = geomReduce;
- exports.flattenEach = flattenEach;
- exports.flattenReduce = flattenReduce;
- exports.segmentEach = segmentEach;
- exports.segmentReduce = segmentReduce;
- exports.lineEach = lineEach;
- exports.lineReduce = lineReduce;
- exports.findSegment = findSegment;
- exports.findPoint = findPoint;
- },{"@turf/helpers":11}],17:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var bearing_1 = require("@turf/bearing");
- var distance_1 = require("@turf/distance");
- var destination_1 = require("@turf/destination");
- var line_intersect_1 = require("@turf/line-intersect");
- var meta_1 = require("@turf/meta");
- var helpers_1 = require("@turf/helpers");
- var invariant_1 = require("@turf/invariant");
- /**
- * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the (Multi)LineString.
- *
- * @name nearestPointOnLine
- * @param {Geometry|Feature<LineString|MultiLineString>} lines lines to snap to
- * @param {Geometry|Feature<Point>|number[]} pt point to snap from
- * @param {Object} [options={}] Optional parameters
- * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers
- * @returns {Feature<Point>} closest point on the `line` to `point`. The properties object will contain three values: `index`: closest point was found on nth line part, `dist`: distance between pt and the closest point, `location`: distance along the line between start and the closest point.
- * @example
- * var line = turf.lineString([
- * [-77.031669, 38.878605],
- * [-77.029609, 38.881946],
- * [-77.020339, 38.884084],
- * [-77.025661, 38.885821],
- * [-77.021884, 38.889563],
- * [-77.019824, 38.892368]
- * ]);
- * var pt = turf.point([-77.037076, 38.884017]);
- *
- * var snapped = turf.nearestPointOnLine(line, pt, {units: 'miles'});
- *
- * //addToMap
- * var addToMap = [line, pt, snapped];
- * snapped.properties['marker-color'] = '#00f';
- */
- function nearestPointOnLine(lines, pt, options) {
- if (options === void 0) { options = {}; }
- var closestPt = helpers_1.point([Infinity, Infinity], {
- dist: Infinity
- });
- var length = 0.0;
- meta_1.flattenEach(lines, function (line) {
- var coords = invariant_1.getCoords(line);
- for (var i = 0; i < coords.length - 1; i++) {
- //start
- var start = helpers_1.point(coords[i]);
- start.properties.dist = distance_1.default(pt, start, options);
- //stop
- var stop_1 = helpers_1.point(coords[i + 1]);
- stop_1.properties.dist = distance_1.default(pt, stop_1, options);
- // sectionLength
- var sectionLength = distance_1.default(start, stop_1, options);
- //perpendicular
- var heightDistance = Math.max(start.properties.dist, stop_1.properties.dist);
- var direction = bearing_1.default(start, stop_1);
- var perpendicularPt1 = destination_1.default(pt, heightDistance, direction + 90, options);
- var perpendicularPt2 = destination_1.default(pt, heightDistance, direction - 90, options);
- var intersect = line_intersect_1.default(helpers_1.lineString([perpendicularPt1.geometry.coordinates, perpendicularPt2.geometry.coordinates]), helpers_1.lineString([start.geometry.coordinates, stop_1.geometry.coordinates]));
- var intersectPt = null;
- if (intersect.features.length > 0) {
- intersectPt = intersect.features[0];
- intersectPt.properties.dist = distance_1.default(pt, intersectPt, options);
- intersectPt.properties.location = length + distance_1.default(start, intersectPt, options);
- }
- if (start.properties.dist < closestPt.properties.dist) {
- closestPt = start;
- closestPt.properties.index = i;
- closestPt.properties.location = length;
- }
- if (stop_1.properties.dist < closestPt.properties.dist) {
- closestPt = stop_1;
- closestPt.properties.index = i + 1;
- closestPt.properties.location = length + sectionLength;
- }
- if (intersectPt && intersectPt.properties.dist < closestPt.properties.dist) {
- closestPt = intersectPt;
- closestPt.properties.index = i;
- }
- // update length
- length += sectionLength;
- }
- });
- return closestPt;
- }
- exports.default = nearestPointOnLine;
- },{"@turf/bearing":6,"@turf/destination":8,"@turf/distance":10,"@turf/helpers":11,"@turf/invariant":13,"@turf/line-intersect":14,"@turf/meta":16}],18:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- var martinez = require("martinez-polygon-clipping");
- var invariant_1 = require("@turf/invariant");
- var helpers_1 = require("@turf/helpers");
- /**
- * Takes two {@link (Multi)Polygon(s)} and returns a combined polygon. If the input polygons are not contiguous, this function returns a {@link MultiPolygon} feature.
- *
- * @name union
- * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
- * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
- * @param {Object} [options={}] Optional Parameters
- * @param {Object} [options.properties={}] Translate Properties to output Feature
- * @returns {Feature<(Polygon|MultiPolygon)>} a combined {@link Polygon} or {@link MultiPolygon} feature
- * @example
- * var poly1 = turf.polygon([[
- * [-82.574787, 35.594087],
- * [-82.574787, 35.615581],
- * [-82.545261, 35.615581],
- * [-82.545261, 35.594087],
- * [-82.574787, 35.594087]
- * ]], {"fill": "#0f0"});
- * var poly2 = turf.polygon([[
- * [-82.560024, 35.585153],
- * [-82.560024, 35.602602],
- * [-82.52964, 35.602602],
- * [-82.52964, 35.585153],
- * [-82.560024, 35.585153]
- * ]], {"fill": "#00f"});
- *
- * var union = turf.union(poly1, poly2);
- *
- * //addToMap
- * var addToMap = [poly1, poly2, union];
- */
- function union(polygon1, polygon2, options) {
- if (options === void 0) { options = {}; }
- var coords1 = invariant_1.getGeom(polygon1).coordinates;
- var coords2 = invariant_1.getGeom(polygon2).coordinates;
- var unioned = martinez.union(coords1, coords2);
- if (unioned.length === 0)
- return null;
- if (unioned.length === 1)
- return helpers_1.polygon(unioned[0], options.properties);
- else
- return helpers_1.multiPolygon(unioned, options.properties);
- }
- exports.default = union;
- },{"@turf/helpers":11,"@turf/invariant":13,"martinez-polygon-clipping":173}],19:[function(require,module,exports){
- (function (process,global,setImmediate){
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global.async = global.async || {})));
- }(this, (function (exports) { 'use strict';
- function slice(arrayLike, start) {
- start = start|0;
- var newLen = Math.max(arrayLike.length - start, 0);
- var newArr = Array(newLen);
- for(var idx = 0; idx < newLen; idx++) {
- newArr[idx] = arrayLike[start + idx];
- }
- return newArr;
- }
- /**
- * Creates a continuation function with some arguments already applied.
- *
- * Useful as a shorthand when combined with other control flow functions. Any
- * arguments passed to the returned function are added to the arguments
- * originally passed to apply.
- *
- * @name apply
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {Function} fn - The function you want to eventually apply all
- * arguments to. Invokes with (arguments...).
- * @param {...*} arguments... - Any number of arguments to automatically apply
- * when the continuation is called.
- * @returns {Function} the partially-applied function
- * @example
- *
- * // using apply
- * async.parallel([
- * async.apply(fs.writeFile, 'testfile1', 'test1'),
- * async.apply(fs.writeFile, 'testfile2', 'test2')
- * ]);
- *
- *
- * // the same process without using apply
- * async.parallel([
- * function(callback) {
- * fs.writeFile('testfile1', 'test1', callback);
- * },
- * function(callback) {
- * fs.writeFile('testfile2', 'test2', callback);
- * }
- * ]);
- *
- * // It's possible to pass any number of additional arguments when calling the
- * // continuation:
- *
- * node> var fn = async.apply(sys.puts, 'one');
- * node> fn('two', 'three');
- * one
- * two
- * three
- */
- var apply = function(fn/*, ...args*/) {
- var args = slice(arguments, 1);
- return function(/*callArgs*/) {
- var callArgs = slice(arguments);
- return fn.apply(null, args.concat(callArgs));
- };
- };
- var initialParams = function (fn) {
- return function (/*...args, callback*/) {
- var args = slice(arguments);
- var callback = args.pop();
- fn.call(this, args, callback);
- };
- };
- /**
- * 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(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
- }
- var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
- var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
- function fallback(fn) {
- setTimeout(fn, 0);
- }
- function wrap(defer) {
- return function (fn/*, ...args*/) {
- var args = slice(arguments, 1);
- defer(function () {
- fn.apply(null, args);
- });
- };
- }
- var _defer;
- if (hasSetImmediate) {
- _defer = setImmediate;
- } else if (hasNextTick) {
- _defer = process.nextTick;
- } else {
- _defer = fallback;
- }
- var setImmediate$1 = wrap(_defer);
- /**
- * Take a sync function and make it async, passing its return value to a
- * callback. This is useful for plugging sync functions into a waterfall,
- * series, or other async functions. Any arguments passed to the generated
- * function will be passed to the wrapped function (except for the final
- * callback argument). Errors thrown will be passed to the callback.
- *
- * If the function passed to `asyncify` returns a Promise, that promises's
- * resolved/rejected state will be used to call the callback, rather than simply
- * the synchronous return value.
- *
- * This also means you can asyncify ES2017 `async` functions.
- *
- * @name asyncify
- * @static
- * @memberOf module:Utils
- * @method
- * @alias wrapSync
- * @category Util
- * @param {Function} func - The synchronous function, or Promise-returning
- * function to convert to an {@link AsyncFunction}.
- * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
- * invoked with `(args..., callback)`.
- * @example
- *
- * // passing a regular synchronous function
- * async.waterfall([
- * async.apply(fs.readFile, filename, "utf8"),
- * async.asyncify(JSON.parse),
- * function (data, next) {
- * // data is the result of parsing the text.
- * // If there was a parsing error, it would have been caught.
- * }
- * ], callback);
- *
- * // passing a function returning a promise
- * async.waterfall([
- * async.apply(fs.readFile, filename, "utf8"),
- * async.asyncify(function (contents) {
- * return db.model.create(contents);
- * }),
- * function (model, next) {
- * // `model` is the instantiated model object.
- * // If there was an error, this function would be skipped.
- * }
- * ], callback);
- *
- * // es2017 example, though `asyncify` is not needed if your JS environment
- * // supports async functions out of the box
- * var q = async.queue(async.asyncify(async function(file) {
- * var intermediateStep = await processFile(file);
- * return await somePromise(intermediateStep)
- * }));
- *
- * q.push(files);
- */
- function asyncify(func) {
- return initialParams(function (args, callback) {
- var result;
- try {
- result = func.apply(this, args);
- } catch (e) {
- return callback(e);
- }
- // if result is Promise object
- if (isObject(result) && typeof result.then === 'function') {
- result.then(function(value) {
- invokeCallback(callback, null, value);
- }, function(err) {
- invokeCallback(callback, err.message ? err : new Error(err));
- });
- } else {
- callback(null, result);
- }
- });
- }
- function invokeCallback(callback, error, value) {
- try {
- callback(error, value);
- } catch (e) {
- setImmediate$1(rethrow, e);
- }
- }
- function rethrow(error) {
- throw error;
- }
- var supportsSymbol = typeof Symbol === 'function';
- function isAsync(fn) {
- return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
- }
- function wrapAsync(asyncFn) {
- return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
- }
- function applyEach$1(eachfn) {
- return function(fns/*, ...args*/) {
- var args = slice(arguments, 1);
- var go = initialParams(function(args, callback) {
- var that = this;
- return eachfn(fns, function (fn, cb) {
- wrapAsync(fn).apply(that, args.concat(cb));
- }, callback);
- });
- if (args.length) {
- return go.apply(this, args);
- }
- else {
- return go;
- }
- };
- }
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
- /** 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')();
- /** Built-in value references. */
- var Symbol$1 = root.Symbol;
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto.toString;
- /** Built-in value references. */
- var symToStringTag$1 = Symbol$1 ? Symbol$1.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.call(value, symToStringTag$1),
- tag = value[symToStringTag$1];
- try {
- value[symToStringTag$1] = undefined;
- var unmasked = true;
- } catch (e) {}
- var result = nativeObjectToString.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag$1] = tag;
- } else {
- delete value[symToStringTag$1];
- }
- }
- return result;
- }
- /** Used for built-in method references. */
- var objectProto$1 = Object.prototype;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString$1 = objectProto$1.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$1.call(value);
- }
- /** `Object#toString` result references. */
- var nullTag = '[object Null]';
- var undefinedTag = '[object Undefined]';
- /** Built-in value references. */
- var symToStringTag = Symbol$1 ? Symbol$1.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);
- }
- /** `Object#toString` result references. */
- var asyncTag = '[object AsyncFunction]';
- var funcTag = '[object Function]';
- var genTag = '[object GeneratorFunction]';
- var 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(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 || tag == genTag || tag == asyncTag || tag == proxyTag;
- }
- /** 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;
- }
- /**
- * 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(value.length) && !isFunction(value);
- }
- // A temporary value used to identify if the loop should be broken.
- // See #1064, #1293
- var breakLoop = {};
- /**
- * This method returns `undefined`.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Util
- * @example
- *
- * _.times(2, _.noop);
- * // => [undefined, undefined]
- */
- function noop() {
- // No operation performed.
- }
- function once(fn) {
- return function () {
- if (fn === null) return;
- var callFn = fn;
- fn = null;
- callFn.apply(this, arguments);
- };
- }
- var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
- var getIterator = function (coll) {
- return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
- };
- /**
- * 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;
- }
- /**
- * 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';
- }
- /** `Object#toString` result references. */
- var argsTag = '[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(value) && baseGetTag(value) == argsTag;
- }
- /** Used for built-in method references. */
- var objectProto$3 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
- /** Built-in value references. */
- var propertyIsEnumerable = objectProto$3.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(value) && hasOwnProperty$2.call(value, 'callee') &&
- !propertyIsEnumerable.call(value, 'callee');
- };
- /**
- * 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 = Array.isArray;
- /**
- * 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;
- }
- /** Detect free variable `exports`. */
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && typeof module == '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;
- /** 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);
- }
- /** `Object#toString` result references. */
- var argsTag$1 = '[object Arguments]';
- var arrayTag = '[object Array]';
- var boolTag = '[object Boolean]';
- var dateTag = '[object Date]';
- var errorTag = '[object Error]';
- var funcTag$1 = '[object Function]';
- var mapTag = '[object Map]';
- var numberTag = '[object Number]';
- var objectTag = '[object Object]';
- var regexpTag = '[object RegExp]';
- var setTag = '[object Set]';
- var stringTag = '[object String]';
- var weakMapTag = '[object WeakMap]';
- var arrayBufferTag = '[object ArrayBuffer]';
- var dataViewTag = '[object DataView]';
- var float32Tag = '[object Float32Array]';
- var float64Tag = '[object Float64Array]';
- var int8Tag = '[object Int8Array]';
- var int16Tag = '[object Int16Array]';
- var int32Tag = '[object Int32Array]';
- var uint8Tag = '[object Uint8Array]';
- var uint8ClampedTag = '[object Uint8ClampedArray]';
- var uint16Tag = '[object Uint16Array]';
- var uint32Tag = '[object Uint32Array]';
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
- typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
- typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
- typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
- typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
- typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
- typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
- typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
- typedArrayTags[mapTag] = typedArrayTags[numberTag] =
- typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
- typedArrayTags[setTag] = typedArrayTags[stringTag] =
- typedArrayTags[weakMapTag] = 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(value) &&
- isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
- }
- /**
- * 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);
- };
- }
- /** Detect free variable `exports`. */
- var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
- /** Detect free variable `process` from Node.js. */
- var freeProcess = moduleExports$1 && freeGlobal.process;
- /** Used to access faster Node.js helpers. */
- var nodeUtil = (function() {
- try {
- // Use `util.types` for Node.js 10+.
- var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
- if (types) {
- return types;
- }
- // Legacy `process.binding('util')` for Node.js < 10.
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
- } catch (e) {}
- }());
- /* 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;
- /** Used for built-in method references. */
- var objectProto$2 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$1 = objectProto$2.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(value),
- isArg = !isArr && isArguments(value),
- isBuff = !isArr && !isArg && isBuffer(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? baseTimes(value.length, String) : [],
- length = result.length;
- for (var key in value) {
- if ((inherited || hasOwnProperty$1.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;
- }
- /** Used for built-in method references. */
- var objectProto$5 = 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$5;
- return value === proto;
- }
- /**
- * 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));
- };
- }
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeKeys = overArg(Object.keys, Object);
- /** Used for built-in method references. */
- var objectProto$4 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$3 = objectProto$4.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$3.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * 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(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
- function createArrayIterator(coll) {
- var i = -1;
- var len = coll.length;
- return function next() {
- return ++i < len ? {value: coll[i], key: i} : null;
- }
- }
- function createES2015Iterator(iterator) {
- var i = -1;
- return function next() {
- var item = iterator.next();
- if (item.done)
- return null;
- i++;
- return {value: item.value, key: i};
- }
- }
- function createObjectIterator(obj) {
- var okeys = keys(obj);
- var i = -1;
- var len = okeys.length;
- return function next() {
- var key = okeys[++i];
- return i < len ? {value: obj[key], key: key} : null;
- };
- }
- function iterator(coll) {
- if (isArrayLike(coll)) {
- return createArrayIterator(coll);
- }
- var iterator = getIterator(coll);
- return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
- }
- function onlyOnce(fn) {
- return function() {
- if (fn === null) throw new Error("Callback was already called.");
- var callFn = fn;
- fn = null;
- callFn.apply(this, arguments);
- };
- }
- function _eachOfLimit(limit) {
- return function (obj, iteratee, callback) {
- callback = once(callback || noop);
- if (limit <= 0 || !obj) {
- return callback(null);
- }
- var nextElem = iterator(obj);
- var done = false;
- var running = 0;
- var looping = false;
- function iterateeCallback(err, value) {
- running -= 1;
- if (err) {
- done = true;
- callback(err);
- }
- else if (value === breakLoop || (done && running <= 0)) {
- done = true;
- return callback(null);
- }
- else if (!looping) {
- replenish();
- }
- }
- function replenish () {
- looping = true;
- while (running < limit && !done) {
- var elem = nextElem();
- if (elem === null) {
- done = true;
- if (running <= 0) {
- callback(null);
- }
- return;
- }
- running += 1;
- iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
- }
- looping = false;
- }
- replenish();
- };
- }
- /**
- * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name eachOfLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.eachOf]{@link module:Collections.eachOf}
- * @alias forEachOfLimit
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each
- * item in `coll`. The `key` is the item's key, or index in the case of an
- * array.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- */
- function eachOfLimit(coll, limit, iteratee, callback) {
- _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
- }
- function doLimit(fn, limit) {
- return function (iterable, iteratee, callback) {
- return fn(iterable, limit, iteratee, callback);
- };
- }
- // eachOf implementation optimized for array-likes
- function eachOfArrayLike(coll, iteratee, callback) {
- callback = once(callback || noop);
- var index = 0,
- completed = 0,
- length = coll.length;
- if (length === 0) {
- callback(null);
- }
- function iteratorCallback(err, value) {
- if (err) {
- callback(err);
- } else if ((++completed === length) || value === breakLoop) {
- callback(null);
- }
- }
- for (; index < length; index++) {
- iteratee(coll[index], index, onlyOnce(iteratorCallback));
- }
- }
- // a generic version of eachOf which can handle array, object, and iterator cases.
- var eachOfGeneric = doLimit(eachOfLimit, Infinity);
- /**
- * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
- * to the iteratee.
- *
- * @name eachOf
- * @static
- * @memberOf module:Collections
- * @method
- * @alias forEachOf
- * @category Collection
- * @see [async.each]{@link module:Collections.each}
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each
- * item in `coll`.
- * The `key` is the item's key, or index in the case of an array.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- * @example
- *
- * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
- * var configs = {};
- *
- * async.forEachOf(obj, function (value, key, callback) {
- * fs.readFile(__dirname + value, "utf8", function (err, data) {
- * if (err) return callback(err);
- * try {
- * configs[key] = JSON.parse(data);
- * } catch (e) {
- * return callback(e);
- * }
- * callback();
- * });
- * }, function (err) {
- * if (err) console.error(err.message);
- * // configs is now a map of JSON data
- * doSomethingWith(configs);
- * });
- */
- var eachOf = function(coll, iteratee, callback) {
- var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
- eachOfImplementation(coll, wrapAsync(iteratee), callback);
- };
- function doParallel(fn) {
- return function (obj, iteratee, callback) {
- return fn(eachOf, obj, wrapAsync(iteratee), callback);
- };
- }
- function _asyncMap(eachfn, arr, iteratee, callback) {
- callback = callback || noop;
- arr = arr || [];
- var results = [];
- var counter = 0;
- var _iteratee = wrapAsync(iteratee);
- eachfn(arr, function (value, _, callback) {
- var index = counter++;
- _iteratee(value, function (err, v) {
- results[index] = v;
- callback(err);
- });
- }, function (err) {
- callback(err, results);
- });
- }
- /**
- * Produces a new collection of values by mapping each value in `coll` through
- * the `iteratee` function. The `iteratee` is called with an item from `coll`
- * and a callback for when it has finished processing. Each of these callback
- * takes 2 arguments: an `error`, and the transformed item from `coll`. If
- * `iteratee` passes an error to its callback, the main `callback` (for the
- * `map` function) is immediately called with the error.
- *
- * Note, that since this function applies the `iteratee` to each item in
- * parallel, there is no guarantee that the `iteratee` functions will complete
- * in order. However, the results array will be in the same order as the
- * original `coll`.
- *
- * If `map` is passed an Object, the results will be an Array. The results
- * will roughly be in the order of the original Objects' keys (but this can
- * vary across JavaScript engines).
- *
- * @name map
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with the transformed item.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Results is an Array of the
- * transformed items from the `coll`. Invoked with (err, results).
- * @example
- *
- * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
- * // results is now an array of stats for each file
- * });
- */
- var map = doParallel(_asyncMap);
- /**
- * Applies the provided arguments to each function in the array, calling
- * `callback` after all functions have completed. If you only provide the first
- * argument, `fns`, then it will return a function which lets you pass in the
- * arguments as if it were a single function call. If more arguments are
- * provided, `callback` is required while `args` is still optional.
- *
- * @name applyEach
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s
- * to all call with the same arguments
- * @param {...*} [args] - any number of separate arguments to pass to the
- * function.
- * @param {Function} [callback] - the final argument should be the callback,
- * called when all functions have completed processing.
- * @returns {Function} - If only the first argument, `fns`, is provided, it will
- * return a function which lets you pass in the arguments as if it were a single
- * function call. The signature is `(..args, callback)`. If invoked with any
- * arguments, `callback` is required.
- * @example
- *
- * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
- *
- * // partial application example:
- * async.each(
- * buckets,
- * async.applyEach([enableSearch, updateSchema]),
- * callback
- * );
- */
- var applyEach = applyEach$1(map);
- function doParallelLimit(fn) {
- return function (obj, limit, iteratee, callback) {
- return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback);
- };
- }
- /**
- * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
- *
- * @name mapLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.map]{@link module:Collections.map}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with the transformed item.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Results is an array of the
- * transformed items from the `coll`. Invoked with (err, results).
- */
- var mapLimit = doParallelLimit(_asyncMap);
- /**
- * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
- *
- * @name mapSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.map]{@link module:Collections.map}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with the transformed item.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Results is an array of the
- * transformed items from the `coll`. Invoked with (err, results).
- */
- var mapSeries = doLimit(mapLimit, 1);
- /**
- * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
- *
- * @name applyEachSeries
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.applyEach]{@link module:ControlFlow.applyEach}
- * @category Control Flow
- * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all
- * call with the same arguments
- * @param {...*} [args] - any number of separate arguments to pass to the
- * function.
- * @param {Function} [callback] - the final argument should be the callback,
- * called when all functions have completed processing.
- * @returns {Function} - If only the first argument is provided, it will return
- * a function which lets you pass in the arguments as if it were a single
- * function call.
- */
- var applyEachSeries = applyEach$1(mapSeries);
- /**
- * 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;
- }
- /**
- * Creates a base function for methods like `_.forIn` and `_.forOwn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseFor(fromRight) {
- return function(object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
- }
- /**
- * The base implementation of `baseForOwn` which iterates over `object`
- * properties returned by `keysFunc` and invokes `iteratee` for each property.
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
- var baseFor = createBaseFor();
- /**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
- function baseForOwn(object, iteratee) {
- return object && baseFor(object, iteratee, keys);
- }
- /**
- * 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;
- }
- /**
- * 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;
- }
- /**
- * 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;
- }
- /**
- * 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);
- }
- /**
- * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
- * their requirements. Each function can optionally depend on other functions
- * being completed first, and each function is run as soon as its requirements
- * are satisfied.
- *
- * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
- * will stop. Further tasks will not execute (so any other functions depending
- * on it will not run), and the main `callback` is immediately called with the
- * error.
- *
- * {@link AsyncFunction}s also receive an object containing the results of functions which
- * have completed so far as the first argument, if they have dependencies. If a
- * task function has no dependencies, it will only be passed a callback.
- *
- * @name auto
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Object} tasks - An object. Each of its properties is either a
- * function or an array of requirements, with the {@link AsyncFunction} itself the last item
- * in the array. The object's key of a property serves as the name of the task
- * defined by that property, i.e. can be used when specifying requirements for
- * other tasks. The function receives one or two arguments:
- * * a `results` object, containing the results of the previously executed
- * functions, only passed if the task has any dependencies,
- * * a `callback(err, result)` function, which must be called when finished,
- * passing an `error` (which can be `null`) and the result of the function's
- * execution.
- * @param {number} [concurrency=Infinity] - An optional `integer` for
- * determining the maximum number of tasks that can be run in parallel. By
- * default, as many as possible.
- * @param {Function} [callback] - An optional callback which is called when all
- * the tasks have been completed. It receives the `err` argument if any `tasks`
- * pass an error to their callback. Results are always returned; however, if an
- * error occurs, no further `tasks` will be performed, and the results object
- * will only contain partial results. Invoked with (err, results).
- * @returns undefined
- * @example
- *
- * async.auto({
- * // this function will just be passed a callback
- * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
- * showData: ['readData', function(results, cb) {
- * // results.readData is the file's contents
- * // ...
- * }]
- * }, callback);
- *
- * async.auto({
- * get_data: function(callback) {
- * console.log('in get_data');
- * // async code to get some data
- * callback(null, 'data', 'converted to array');
- * },
- * make_folder: function(callback) {
- * console.log('in make_folder');
- * // async code to create a directory to store a file in
- * // this is run at the same time as getting the data
- * callback(null, 'folder');
- * },
- * write_file: ['get_data', 'make_folder', function(results, callback) {
- * console.log('in write_file', JSON.stringify(results));
- * // once there is some data and the directory exists,
- * // write the data to a file in the directory
- * callback(null, 'filename');
- * }],
- * email_link: ['write_file', function(results, callback) {
- * console.log('in email_link', JSON.stringify(results));
- * // once the file is written let's email a link to it...
- * // results.write_file contains the filename returned by write_file.
- * callback(null, {'file':results.write_file, 'email':'user@example.com'});
- * }]
- * }, function(err, results) {
- * console.log('err = ', err);
- * console.log('results = ', results);
- * });
- */
- var auto = function (tasks, concurrency, callback) {
- if (typeof concurrency === 'function') {
- // concurrency is optional, shift the args.
- callback = concurrency;
- concurrency = null;
- }
- callback = once(callback || noop);
- var keys$$1 = keys(tasks);
- var numTasks = keys$$1.length;
- if (!numTasks) {
- return callback(null);
- }
- if (!concurrency) {
- concurrency = numTasks;
- }
- var results = {};
- var runningTasks = 0;
- var hasError = false;
- var listeners = Object.create(null);
- var readyTasks = [];
- // for cycle detection:
- var readyToCheck = []; // tasks that have been identified as reachable
- // without the possibility of returning to an ancestor task
- var uncheckedDependencies = {};
- baseForOwn(tasks, function (task, key) {
- if (!isArray(task)) {
- // no dependencies
- enqueueTask(key, [task]);
- readyToCheck.push(key);
- return;
- }
- var dependencies = task.slice(0, task.length - 1);
- var remainingDependencies = dependencies.length;
- if (remainingDependencies === 0) {
- enqueueTask(key, task);
- readyToCheck.push(key);
- return;
- }
- uncheckedDependencies[key] = remainingDependencies;
- arrayEach(dependencies, function (dependencyName) {
- if (!tasks[dependencyName]) {
- throw new Error('async.auto task `' + key +
- '` has a non-existent dependency `' +
- dependencyName + '` in ' +
- dependencies.join(', '));
- }
- addListener(dependencyName, function () {
- remainingDependencies--;
- if (remainingDependencies === 0) {
- enqueueTask(key, task);
- }
- });
- });
- });
- checkForDeadlocks();
- processQueue();
- function enqueueTask(key, task) {
- readyTasks.push(function () {
- runTask(key, task);
- });
- }
- function processQueue() {
- if (readyTasks.length === 0 && runningTasks === 0) {
- return callback(null, results);
- }
- while(readyTasks.length && runningTasks < concurrency) {
- var run = readyTasks.shift();
- run();
- }
- }
- function addListener(taskName, fn) {
- var taskListeners = listeners[taskName];
- if (!taskListeners) {
- taskListeners = listeners[taskName] = [];
- }
- taskListeners.push(fn);
- }
- function taskComplete(taskName) {
- var taskListeners = listeners[taskName] || [];
- arrayEach(taskListeners, function (fn) {
- fn();
- });
- processQueue();
- }
- function runTask(key, task) {
- if (hasError) return;
- var taskCallback = onlyOnce(function(err, result) {
- runningTasks--;
- if (arguments.length > 2) {
- result = slice(arguments, 1);
- }
- if (err) {
- var safeResults = {};
- baseForOwn(results, function(val, rkey) {
- safeResults[rkey] = val;
- });
- safeResults[key] = result;
- hasError = true;
- listeners = Object.create(null);
- callback(err, safeResults);
- } else {
- results[key] = result;
- taskComplete(key);
- }
- });
- runningTasks++;
- var taskFn = wrapAsync(task[task.length - 1]);
- if (task.length > 1) {
- taskFn(results, taskCallback);
- } else {
- taskFn(taskCallback);
- }
- }
- function checkForDeadlocks() {
- // Kahn's algorithm
- // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
- // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
- var currentTask;
- var counter = 0;
- while (readyToCheck.length) {
- currentTask = readyToCheck.pop();
- counter++;
- arrayEach(getDependents(currentTask), function (dependent) {
- if (--uncheckedDependencies[dependent] === 0) {
- readyToCheck.push(dependent);
- }
- });
- }
- if (counter !== numTasks) {
- throw new Error(
- 'async.auto cannot execute tasks due to a recursive dependency'
- );
- }
- }
- function getDependents(taskName) {
- var result = [];
- baseForOwn(tasks, function (task, key) {
- if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
- result.push(key);
- }
- });
- return result;
- }
- };
- /**
- * 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;
- }
- /** `Object#toString` result references. */
- var symbolTag = '[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(value) && baseGetTag(value) == symbolTag);
- }
- /** Used as references for various `Number` constants. */
- var INFINITY = 1 / 0;
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
- var 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(value)) {
- // Recursively convert values (susceptible to call stack limits).
- return arrayMap(value, baseToString) + '';
- }
- if (isSymbol(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
- /**
- * The base implementation of `_.slice` without an iteratee call guard.
- *
- * @private
- * @param {Array} array The array to slice.
- * @param {number} [start=0] The start position.
- * @param {number} [end=array.length] The end position.
- * @returns {Array} Returns the slice of `array`.
- */
- function baseSlice(array, start, end) {
- var index = -1,
- length = array.length;
- if (start < 0) {
- start = -start > length ? 0 : (length + start);
- }
- end = end > length ? length : end;
- if (end < 0) {
- end += length;
- }
- length = start > end ? 0 : ((end - start) >>> 0);
- start >>>= 0;
- var result = Array(length);
- while (++index < length) {
- result[index] = array[index + start];
- }
- return result;
- }
- /**
- * Casts `array` to a slice if it's needed.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {number} start The start position.
- * @param {number} [end=array.length] The end position.
- * @returns {Array} Returns the cast slice.
- */
- function castSlice(array, start, end) {
- var length = array.length;
- end = end === undefined ? length : end;
- return (!start && end >= length) ? array : baseSlice(array, start, end);
- }
- /**
- * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
- * that is not found in the character symbols.
- *
- * @private
- * @param {Array} strSymbols The string symbols to inspect.
- * @param {Array} chrSymbols The character symbols to find.
- * @returns {number} Returns the index of the last unmatched string symbol.
- */
- function charsEndIndex(strSymbols, chrSymbols) {
- var index = strSymbols.length;
- while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
- return index;
- }
- /**
- * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
- * that is not found in the character symbols.
- *
- * @private
- * @param {Array} strSymbols The string symbols to inspect.
- * @param {Array} chrSymbols The character symbols to find.
- * @returns {number} Returns the index of the first unmatched string symbol.
- */
- function charsStartIndex(strSymbols, chrSymbols) {
- var index = -1,
- length = strSymbols.length;
- while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
- return index;
- }
- /**
- * Converts an ASCII `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function asciiToArray(string) {
- return string.split('');
- }
- /** Used to compose unicode character classes. */
- var rsAstralRange = '\\ud800-\\udfff';
- var rsComboMarksRange = '\\u0300-\\u036f';
- var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
- var rsComboSymbolsRange = '\\u20d0-\\u20ff';
- var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
- var rsVarRange = '\\ufe0e\\ufe0f';
- /** Used to compose unicode capture groups. */
- var rsZWJ = '\\u200d';
- /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
- var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
- /**
- * Checks if `string` contains Unicode symbols.
- *
- * @private
- * @param {string} string The string to inspect.
- * @returns {boolean} Returns `true` if a symbol is found, else `false`.
- */
- function hasUnicode(string) {
- return reHasUnicode.test(string);
- }
- /** Used to compose unicode character classes. */
- var rsAstralRange$1 = '\\ud800-\\udfff';
- var rsComboMarksRange$1 = '\\u0300-\\u036f';
- var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
- var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
- var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
- var rsVarRange$1 = '\\ufe0e\\ufe0f';
- /** Used to compose unicode capture groups. */
- var rsAstral = '[' + rsAstralRange$1 + ']';
- var rsCombo = '[' + rsComboRange$1 + ']';
- var rsFitz = '\\ud83c[\\udffb-\\udfff]';
- var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
- var rsNonAstral = '[^' + rsAstralRange$1 + ']';
- var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
- var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
- var rsZWJ$1 = '\\u200d';
- /** Used to compose unicode regexes. */
- var reOptMod = rsModifier + '?';
- var rsOptVar = '[' + rsVarRange$1 + ']?';
- var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
- var rsSeq = rsOptVar + reOptMod + rsOptJoin;
- var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
- /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
- var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
- /**
- * Converts a Unicode `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function unicodeToArray(string) {
- return string.match(reUnicode) || [];
- }
- /**
- * Converts `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function stringToArray(string) {
- return hasUnicode(string)
- ? unicodeToArray(string)
- : asciiToArray(string);
- }
- /**
- * 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);
- }
- /** Used to match leading and trailing whitespace. */
- var reTrim = /^\s+|\s+$/g;
- /**
- * Removes leading and trailing whitespace or specified characters from `string`.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to trim.
- * @param {string} [chars=whitespace] The characters to trim.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {string} Returns the trimmed string.
- * @example
- *
- * _.trim(' abc ');
- * // => 'abc'
- *
- * _.trim('-_-abc-_-', '_-');
- * // => 'abc'
- *
- * _.map([' foo ', ' bar '], _.trim);
- * // => ['foo', 'bar']
- */
- function trim(string, chars, guard) {
- string = toString(string);
- if (string && (guard || chars === undefined)) {
- return string.replace(reTrim, '');
- }
- if (!string || !(chars = baseToString(chars))) {
- return string;
- }
- var strSymbols = stringToArray(string),
- chrSymbols = stringToArray(chars),
- start = charsStartIndex(strSymbols, chrSymbols),
- end = charsEndIndex(strSymbols, chrSymbols) + 1;
- return castSlice(strSymbols, start, end).join('');
- }
- var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
- var FN_ARG_SPLIT = /,/;
- var FN_ARG = /(=.+)?(\s*)$/;
- var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
- function parseParams(func) {
- func = func.toString().replace(STRIP_COMMENTS, '');
- func = func.match(FN_ARGS)[2].replace(' ', '');
- func = func ? func.split(FN_ARG_SPLIT) : [];
- func = func.map(function (arg){
- return trim(arg.replace(FN_ARG, ''));
- });
- return func;
- }
- /**
- * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
- * tasks are specified as parameters to the function, after the usual callback
- * parameter, with the parameter names matching the names of the tasks it
- * depends on. This can provide even more readable task graphs which can be
- * easier to maintain.
- *
- * If a final callback is specified, the task results are similarly injected,
- * specified as named parameters after the initial error parameter.
- *
- * The autoInject function is purely syntactic sugar and its semantics are
- * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
- *
- * @name autoInject
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.auto]{@link module:ControlFlow.auto}
- * @category Control Flow
- * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
- * the form 'func([dependencies...], callback). The object's key of a property
- * serves as the name of the task defined by that property, i.e. can be used
- * when specifying requirements for other tasks.
- * * The `callback` parameter is a `callback(err, result)` which must be called
- * when finished, passing an `error` (which can be `null`) and the result of
- * the function's execution. The remaining parameters name other tasks on
- * which the task is dependent, and the results from those tasks are the
- * arguments of those parameters.
- * @param {Function} [callback] - An optional callback which is called when all
- * the tasks have been completed. It receives the `err` argument if any `tasks`
- * pass an error to their callback, and a `results` object with any completed
- * task results, similar to `auto`.
- * @example
- *
- * // The example from `auto` can be rewritten as follows:
- * async.autoInject({
- * get_data: function(callback) {
- * // async code to get some data
- * callback(null, 'data', 'converted to array');
- * },
- * make_folder: function(callback) {
- * // async code to create a directory to store a file in
- * // this is run at the same time as getting the data
- * callback(null, 'folder');
- * },
- * write_file: function(get_data, make_folder, callback) {
- * // once there is some data and the directory exists,
- * // write the data to a file in the directory
- * callback(null, 'filename');
- * },
- * email_link: function(write_file, callback) {
- * // once the file is written let's email a link to it...
- * // write_file contains the filename returned by write_file.
- * callback(null, {'file':write_file, 'email':'user@example.com'});
- * }
- * }, function(err, results) {
- * console.log('err = ', err);
- * console.log('email_link = ', results.email_link);
- * });
- *
- * // If you are using a JS minifier that mangles parameter names, `autoInject`
- * // will not work with plain functions, since the parameter names will be
- * // collapsed to a single letter identifier. To work around this, you can
- * // explicitly specify the names of the parameters your task function needs
- * // in an array, similar to Angular.js dependency injection.
- *
- * // This still has an advantage over plain `auto`, since the results a task
- * // depends on are still spread into arguments.
- * async.autoInject({
- * //...
- * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
- * callback(null, 'filename');
- * }],
- * email_link: ['write_file', function(write_file, callback) {
- * callback(null, {'file':write_file, 'email':'user@example.com'});
- * }]
- * //...
- * }, function(err, results) {
- * console.log('err = ', err);
- * console.log('email_link = ', results.email_link);
- * });
- */
- function autoInject(tasks, callback) {
- var newTasks = {};
- baseForOwn(tasks, function (taskFn, key) {
- var params;
- var fnIsAsync = isAsync(taskFn);
- var hasNoDeps =
- (!fnIsAsync && taskFn.length === 1) ||
- (fnIsAsync && taskFn.length === 0);
- if (isArray(taskFn)) {
- params = taskFn.slice(0, -1);
- taskFn = taskFn[taskFn.length - 1];
- newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
- } else if (hasNoDeps) {
- // no dependencies, use the function as-is
- newTasks[key] = taskFn;
- } else {
- params = parseParams(taskFn);
- if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
- throw new Error("autoInject task functions require explicit parameters.");
- }
- // remove callback param
- if (!fnIsAsync) params.pop();
- newTasks[key] = params.concat(newTask);
- }
- function newTask(results, taskCb) {
- var newArgs = arrayMap(params, function (name) {
- return results[name];
- });
- newArgs.push(taskCb);
- wrapAsync(taskFn).apply(null, newArgs);
- }
- });
- auto(newTasks, callback);
- }
- // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
- // used for queues. This implementation assumes that the node provided by the user can be modified
- // to adjust the next and last properties. We implement only the minimal functionality
- // for queue support.
- function DLL() {
- this.head = this.tail = null;
- this.length = 0;
- }
- function setInitial(dll, node) {
- dll.length = 1;
- dll.head = dll.tail = node;
- }
- DLL.prototype.removeLink = function(node) {
- if (node.prev) node.prev.next = node.next;
- else this.head = node.next;
- if (node.next) node.next.prev = node.prev;
- else this.tail = node.prev;
- node.prev = node.next = null;
- this.length -= 1;
- return node;
- };
- DLL.prototype.empty = function () {
- while(this.head) this.shift();
- return this;
- };
- DLL.prototype.insertAfter = function(node, newNode) {
- newNode.prev = node;
- newNode.next = node.next;
- if (node.next) node.next.prev = newNode;
- else this.tail = newNode;
- node.next = newNode;
- this.length += 1;
- };
- DLL.prototype.insertBefore = function(node, newNode) {
- newNode.prev = node.prev;
- newNode.next = node;
- if (node.prev) node.prev.next = newNode;
- else this.head = newNode;
- node.prev = newNode;
- this.length += 1;
- };
- DLL.prototype.unshift = function(node) {
- if (this.head) this.insertBefore(this.head, node);
- else setInitial(this, node);
- };
- DLL.prototype.push = function(node) {
- if (this.tail) this.insertAfter(this.tail, node);
- else setInitial(this, node);
- };
- DLL.prototype.shift = function() {
- return this.head && this.removeLink(this.head);
- };
- DLL.prototype.pop = function() {
- return this.tail && this.removeLink(this.tail);
- };
- DLL.prototype.toArray = function () {
- var arr = Array(this.length);
- var curr = this.head;
- for(var idx = 0; idx < this.length; idx++) {
- arr[idx] = curr.data;
- curr = curr.next;
- }
- return arr;
- };
- DLL.prototype.remove = function (testFn) {
- var curr = this.head;
- while(!!curr) {
- var next = curr.next;
- if (testFn(curr)) {
- this.removeLink(curr);
- }
- curr = next;
- }
- return this;
- };
- function queue(worker, concurrency, payload) {
- if (concurrency == null) {
- concurrency = 1;
- }
- else if(concurrency === 0) {
- throw new Error('Concurrency must not be zero');
- }
- var _worker = wrapAsync(worker);
- var numRunning = 0;
- var workersList = [];
- var processingScheduled = false;
- function _insert(data, insertAtFront, callback) {
- if (callback != null && typeof callback !== 'function') {
- throw new Error('task callback must be a function');
- }
- q.started = true;
- if (!isArray(data)) {
- data = [data];
- }
- if (data.length === 0 && q.idle()) {
- // call drain immediately if there are no tasks
- return setImmediate$1(function() {
- q.drain();
- });
- }
- for (var i = 0, l = data.length; i < l; i++) {
- var item = {
- data: data[i],
- callback: callback || noop
- };
- if (insertAtFront) {
- q._tasks.unshift(item);
- } else {
- q._tasks.push(item);
- }
- }
- if (!processingScheduled) {
- processingScheduled = true;
- setImmediate$1(function() {
- processingScheduled = false;
- q.process();
- });
- }
- }
- function _next(tasks) {
- return function(err){
- numRunning -= 1;
- for (var i = 0, l = tasks.length; i < l; i++) {
- var task = tasks[i];
- var index = baseIndexOf(workersList, task, 0);
- if (index === 0) {
- workersList.shift();
- } else if (index > 0) {
- workersList.splice(index, 1);
- }
- task.callback.apply(task, arguments);
- if (err != null) {
- q.error(err, task.data);
- }
- }
- if (numRunning <= (q.concurrency - q.buffer) ) {
- q.unsaturated();
- }
- if (q.idle()) {
- q.drain();
- }
- q.process();
- };
- }
- var isProcessing = false;
- var q = {
- _tasks: new DLL(),
- concurrency: concurrency,
- payload: payload,
- saturated: noop,
- unsaturated:noop,
- buffer: concurrency / 4,
- empty: noop,
- drain: noop,
- error: noop,
- started: false,
- paused: false,
- push: function (data, callback) {
- _insert(data, false, callback);
- },
- kill: function () {
- q.drain = noop;
- q._tasks.empty();
- },
- unshift: function (data, callback) {
- _insert(data, true, callback);
- },
- remove: function (testFn) {
- q._tasks.remove(testFn);
- },
- process: function () {
- // Avoid trying to start too many processing operations. This can occur
- // when callbacks resolve synchronously (#1267).
- if (isProcessing) {
- return;
- }
- isProcessing = true;
- while(!q.paused && numRunning < q.concurrency && q._tasks.length){
- var tasks = [], data = [];
- var l = q._tasks.length;
- if (q.payload) l = Math.min(l, q.payload);
- for (var i = 0; i < l; i++) {
- var node = q._tasks.shift();
- tasks.push(node);
- workersList.push(node);
- data.push(node.data);
- }
- numRunning += 1;
- if (q._tasks.length === 0) {
- q.empty();
- }
- if (numRunning === q.concurrency) {
- q.saturated();
- }
- var cb = onlyOnce(_next(tasks));
- _worker(data, cb);
- }
- isProcessing = false;
- },
- length: function () {
- return q._tasks.length;
- },
- running: function () {
- return numRunning;
- },
- workersList: function () {
- return workersList;
- },
- idle: function() {
- return q._tasks.length + numRunning === 0;
- },
- pause: function () {
- q.paused = true;
- },
- resume: function () {
- if (q.paused === false) { return; }
- q.paused = false;
- setImmediate$1(q.process);
- }
- };
- return q;
- }
- /**
- * A cargo of tasks for the worker function to complete. Cargo inherits all of
- * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
- * @typedef {Object} CargoObject
- * @memberOf module:ControlFlow
- * @property {Function} length - A function returning the number of items
- * waiting to be processed. Invoke like `cargo.length()`.
- * @property {number} payload - An `integer` for determining how many tasks
- * should be process per round. This property can be changed after a `cargo` is
- * created to alter the payload on-the-fly.
- * @property {Function} push - Adds `task` to the `queue`. The callback is
- * called once the `worker` has finished processing the task. Instead of a
- * single task, an array of `tasks` can be submitted. The respective callback is
- * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
- * @property {Function} saturated - A callback that is called when the
- * `queue.length()` hits the concurrency and further tasks will be queued.
- * @property {Function} empty - A callback that is called when the last item
- * from the `queue` is given to a `worker`.
- * @property {Function} drain - A callback that is called when the last item
- * from the `queue` has returned from the `worker`.
- * @property {Function} idle - a function returning false if there are items
- * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
- * @property {Function} pause - a function that pauses the processing of tasks
- * until `resume()` is called. Invoke like `cargo.pause()`.
- * @property {Function} resume - a function that resumes the processing of
- * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
- * @property {Function} kill - a function that removes the `drain` callback and
- * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
- */
- /**
- * Creates a `cargo` object with the specified payload. Tasks added to the
- * cargo will be processed altogether (up to the `payload` limit). If the
- * `worker` is in progress, the task is queued until it becomes available. Once
- * the `worker` has completed some tasks, each callback of those tasks is
- * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
- * for how `cargo` and `queue` work.
- *
- * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
- * at a time, cargo passes an array of tasks to a single worker, repeating
- * when the worker is finished.
- *
- * @name cargo
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.queue]{@link module:ControlFlow.queue}
- * @category Control Flow
- * @param {AsyncFunction} worker - An asynchronous function for processing an array
- * of queued tasks. Invoked with `(tasks, callback)`.
- * @param {number} [payload=Infinity] - An optional `integer` for determining
- * how many tasks should be processed per round; if omitted, the default is
- * unlimited.
- * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
- * attached as certain properties to listen for specific events during the
- * lifecycle of the cargo and inner queue.
- * @example
- *
- * // create a cargo object with payload 2
- * var cargo = async.cargo(function(tasks, callback) {
- * for (var i=0; i<tasks.length; i++) {
- * console.log('hello ' + tasks[i].name);
- * }
- * callback();
- * }, 2);
- *
- * // add some items
- * cargo.push({name: 'foo'}, function(err) {
- * console.log('finished processing foo');
- * });
- * cargo.push({name: 'bar'}, function(err) {
- * console.log('finished processing bar');
- * });
- * cargo.push({name: 'baz'}, function(err) {
- * console.log('finished processing baz');
- * });
- */
- function cargo(worker, payload) {
- return queue(worker, 1, payload);
- }
- /**
- * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
- *
- * @name eachOfSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.eachOf]{@link module:Collections.eachOf}
- * @alias forEachOfSeries
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Invoked with (err).
- */
- var eachOfSeries = doLimit(eachOfLimit, 1);
- /**
- * Reduces `coll` into a single value using an async `iteratee` to return each
- * successive step. `memo` is the initial state of the reduction. This function
- * only operates in series.
- *
- * For performance reasons, it may make sense to split a call to this function
- * into a parallel map, and then use the normal `Array.prototype.reduce` on the
- * results. This function is for situations where each step in the reduction
- * needs to be async; if you can get the data before reducing it, then it's
- * probably a good idea to do so.
- *
- * @name reduce
- * @static
- * @memberOf module:Collections
- * @method
- * @alias inject
- * @alias foldl
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {*} memo - The initial state of the reduction.
- * @param {AsyncFunction} iteratee - A function applied to each item in the
- * array to produce the next step in the reduction.
- * The `iteratee` should complete with the next state of the reduction.
- * If the iteratee complete with an error, the reduction is stopped and the
- * main `callback` is immediately called with the error.
- * Invoked with (memo, item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result is the reduced value. Invoked with
- * (err, result).
- * @example
- *
- * async.reduce([1,2,3], 0, function(memo, item, callback) {
- * // pointless async:
- * process.nextTick(function() {
- * callback(null, memo + item)
- * });
- * }, function(err, result) {
- * // result is now equal to the last value of memo, which is 6
- * });
- */
- function reduce(coll, memo, iteratee, callback) {
- callback = once(callback || noop);
- var _iteratee = wrapAsync(iteratee);
- eachOfSeries(coll, function(x, i, callback) {
- _iteratee(memo, x, function(err, v) {
- memo = v;
- callback(err);
- });
- }, function(err) {
- callback(err, memo);
- });
- }
- /**
- * Version of the compose function that is more natural to read. Each function
- * consumes the return value of the previous function. It is the equivalent of
- * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
- *
- * Each function is executed with the `this` binding of the composed function.
- *
- * @name seq
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.compose]{@link module:ControlFlow.compose}
- * @category Control Flow
- * @param {...AsyncFunction} functions - the asynchronous functions to compose
- * @returns {Function} a function that composes the `functions` in order
- * @example
- *
- * // Requires lodash (or underscore), express3 and dresende's orm2.
- * // Part of an app, that fetches cats of the logged user.
- * // This example uses `seq` function to avoid overnesting and error
- * // handling clutter.
- * app.get('/cats', function(request, response) {
- * var User = request.models.User;
- * async.seq(
- * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
- * function(user, fn) {
- * user.getCats(fn); // 'getCats' has signature (callback(err, data))
- * }
- * )(req.session.user_id, function (err, cats) {
- * if (err) {
- * console.error(err);
- * response.json({ status: 'error', message: err.message });
- * } else {
- * response.json({ status: 'ok', message: 'Cats found', data: cats });
- * }
- * });
- * });
- */
- function seq(/*...functions*/) {
- var _functions = arrayMap(arguments, wrapAsync);
- return function(/*...args*/) {
- var args = slice(arguments);
- var that = this;
- var cb = args[args.length - 1];
- if (typeof cb == 'function') {
- args.pop();
- } else {
- cb = noop;
- }
- reduce(_functions, args, function(newargs, fn, cb) {
- fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) {
- var nextargs = slice(arguments, 1);
- cb(err, nextargs);
- }));
- },
- function(err, results) {
- cb.apply(that, [err].concat(results));
- });
- };
- }
- /**
- * Creates a function which is a composition of the passed asynchronous
- * functions. Each function consumes the return value of the function that
- * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
- * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
- *
- * Each function is executed with the `this` binding of the composed function.
- *
- * @name compose
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {...AsyncFunction} functions - the asynchronous functions to compose
- * @returns {Function} an asynchronous function that is the composed
- * asynchronous `functions`
- * @example
- *
- * function add1(n, callback) {
- * setTimeout(function () {
- * callback(null, n + 1);
- * }, 10);
- * }
- *
- * function mul3(n, callback) {
- * setTimeout(function () {
- * callback(null, n * 3);
- * }, 10);
- * }
- *
- * var add1mul3 = async.compose(mul3, add1);
- * add1mul3(4, function (err, result) {
- * // result now equals 15
- * });
- */
- var compose = function(/*...args*/) {
- return seq.apply(null, slice(arguments).reverse());
- };
- var _concat = Array.prototype.concat;
- /**
- * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
- *
- * @name concatLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.concat]{@link module:Collections.concat}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
- * which should use an array as its result. Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished, or an error occurs. Results is an array
- * containing the concatenated results of the `iteratee` function. Invoked with
- * (err, results).
- */
- var concatLimit = function(coll, limit, iteratee, callback) {
- callback = callback || noop;
- var _iteratee = wrapAsync(iteratee);
- mapLimit(coll, limit, function(val, callback) {
- _iteratee(val, function(err /*, ...args*/) {
- if (err) return callback(err);
- return callback(null, slice(arguments, 1));
- });
- }, function(err, mapResults) {
- var result = [];
- for (var i = 0; i < mapResults.length; i++) {
- if (mapResults[i]) {
- result = _concat.apply(result, mapResults[i]);
- }
- }
- return callback(err, result);
- });
- };
- /**
- * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
- * the concatenated list. The `iteratee`s are called in parallel, and the
- * results are concatenated as they return. There is no guarantee that the
- * results array will be returned in the original order of `coll` passed to the
- * `iteratee` function.
- *
- * @name concat
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
- * which should use an array as its result. Invoked with (item, callback).
- * @param {Function} [callback(err)] - A callback which is called after all the
- * `iteratee` functions have finished, or an error occurs. Results is an array
- * containing the concatenated results of the `iteratee` function. Invoked with
- * (err, results).
- * @example
- *
- * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
- * // files is now a list of filenames that exist in the 3 directories
- * });
- */
- var concat = doLimit(concatLimit, Infinity);
- /**
- * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
- *
- * @name concatSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.concat]{@link module:Collections.concat}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
- * The iteratee should complete with an array an array of results.
- * Invoked with (item, callback).
- * @param {Function} [callback(err)] - A callback which is called after all the
- * `iteratee` functions have finished, or an error occurs. Results is an array
- * containing the concatenated results of the `iteratee` function. Invoked with
- * (err, results).
- */
- var concatSeries = doLimit(concatLimit, 1);
- /**
- * Returns a function that when called, calls-back with the values provided.
- * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
- * [`auto`]{@link module:ControlFlow.auto}.
- *
- * @name constant
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {...*} arguments... - Any number of arguments to automatically invoke
- * callback with.
- * @returns {AsyncFunction} Returns a function that when invoked, automatically
- * invokes the callback with the previous given arguments.
- * @example
- *
- * async.waterfall([
- * async.constant(42),
- * function (value, next) {
- * // value === 42
- * },
- * //...
- * ], callback);
- *
- * async.waterfall([
- * async.constant(filename, "utf8"),
- * fs.readFile,
- * function (fileData, next) {
- * //...
- * }
- * //...
- * ], callback);
- *
- * async.auto({
- * hostname: async.constant("https://server.net/"),
- * port: findFreePort,
- * launchServer: ["hostname", "port", function (options, cb) {
- * startServer(options, cb);
- * }],
- * //...
- * }, callback);
- */
- var constant = function(/*...values*/) {
- var values = slice(arguments);
- var args = [null].concat(values);
- return function (/*...ignoredArgs, callback*/) {
- var callback = arguments[arguments.length - 1];
- return callback.apply(this, args);
- };
- };
- /**
- * 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;
- }
- function _createTester(check, getResult) {
- return function(eachfn, arr, iteratee, cb) {
- cb = cb || noop;
- var testPassed = false;
- var testResult;
- eachfn(arr, function(value, _, callback) {
- iteratee(value, function(err, result) {
- if (err) {
- callback(err);
- } else if (check(result) && !testResult) {
- testPassed = true;
- testResult = getResult(true, value);
- callback(null, breakLoop);
- } else {
- callback();
- }
- });
- }, function(err) {
- if (err) {
- cb(err);
- } else {
- cb(null, testPassed ? testResult : getResult(false));
- }
- });
- };
- }
- function _findGetResult(v, x) {
- return x;
- }
- /**
- * Returns the first value in `coll` that passes an async truth test. The
- * `iteratee` is applied in parallel, meaning the first iteratee to return
- * `true` will fire the detect `callback` with that result. That means the
- * result might not be the first item in the original `coll` (in terms of order)
- * that passes the test.
- * If order within the original `coll` is important, then look at
- * [`detectSeries`]{@link module:Collections.detectSeries}.
- *
- * @name detect
- * @static
- * @memberOf module:Collections
- * @method
- * @alias find
- * @category Collections
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
- * The iteratee must complete with a boolean value as its result.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the `iteratee` functions have finished.
- * Result will be the first item in the array that passes the truth test
- * (iteratee) or the value `undefined` if none passed. Invoked with
- * (err, result).
- * @example
- *
- * async.detect(['file1','file2','file3'], function(filePath, callback) {
- * fs.access(filePath, function(err) {
- * callback(null, !err)
- * });
- * }, function(err, result) {
- * // result now equals the first file in the list that exists
- * });
- */
- var detect = doParallel(_createTester(identity, _findGetResult));
- /**
- * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name detectLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.detect]{@link module:Collections.detect}
- * @alias findLimit
- * @category Collections
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
- * The iteratee must complete with a boolean value as its result.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the `iteratee` functions have finished.
- * Result will be the first item in the array that passes the truth test
- * (iteratee) or the value `undefined` if none passed. Invoked with
- * (err, result).
- */
- var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
- /**
- * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
- *
- * @name detectSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.detect]{@link module:Collections.detect}
- * @alias findSeries
- * @category Collections
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
- * The iteratee must complete with a boolean value as its result.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the `iteratee` functions have finished.
- * Result will be the first item in the array that passes the truth test
- * (iteratee) or the value `undefined` if none passed. Invoked with
- * (err, result).
- */
- var detectSeries = doLimit(detectLimit, 1);
- function consoleFunc(name) {
- return function (fn/*, ...args*/) {
- var args = slice(arguments, 1);
- args.push(function (err/*, ...args*/) {
- var args = slice(arguments, 1);
- if (typeof console === 'object') {
- if (err) {
- if (console.error) {
- console.error(err);
- }
- } else if (console[name]) {
- arrayEach(args, function (x) {
- console[name](x);
- });
- }
- }
- });
- wrapAsync(fn).apply(null, args);
- };
- }
- /**
- * Logs the result of an [`async` function]{@link AsyncFunction} to the
- * `console` using `console.dir` to display the properties of the resulting object.
- * Only works in Node.js or in browsers that support `console.dir` and
- * `console.error` (such as FF and Chrome).
- * If multiple arguments are returned from the async function,
- * `console.dir` is called on each argument in order.
- *
- * @name dir
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} function - The function you want to eventually apply
- * all arguments to.
- * @param {...*} arguments... - Any number of arguments to apply to the function.
- * @example
- *
- * // in a module
- * var hello = function(name, callback) {
- * setTimeout(function() {
- * callback(null, {hello: name});
- * }, 1000);
- * };
- *
- * // in the node repl
- * node> async.dir(hello, 'world');
- * {hello: 'world'}
- */
- var dir = consoleFunc('dir');
- /**
- * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
- * the order of operations, the arguments `test` and `fn` are switched.
- *
- * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
- * @name doDuring
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.during]{@link module:ControlFlow.during}
- * @category Control Flow
- * @param {AsyncFunction} fn - An async function which is called each time
- * `test` passes. Invoked with (callback).
- * @param {AsyncFunction} test - asynchronous truth test to perform before each
- * execution of `fn`. Invoked with (...args, callback), where `...args` are the
- * non-error args from the previous callback of `fn`.
- * @param {Function} [callback] - A callback which is called after the test
- * function has failed and repeated execution of `fn` has stopped. `callback`
- * will be passed an error if one occurred, otherwise `null`.
- */
- function doDuring(fn, test, callback) {
- callback = onlyOnce(callback || noop);
- var _fn = wrapAsync(fn);
- var _test = wrapAsync(test);
- function next(err/*, ...args*/) {
- if (err) return callback(err);
- var args = slice(arguments, 1);
- args.push(check);
- _test.apply(this, args);
- }
- function check(err, truth) {
- if (err) return callback(err);
- if (!truth) return callback(null);
- _fn(next);
- }
- check(null, true);
- }
- /**
- * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
- * the order of operations, the arguments `test` and `iteratee` are switched.
- *
- * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
- *
- * @name doWhilst
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.whilst]{@link module:ControlFlow.whilst}
- * @category Control Flow
- * @param {AsyncFunction} iteratee - A function which is called each time `test`
- * passes. Invoked with (callback).
- * @param {Function} test - synchronous truth test to perform after each
- * execution of `iteratee`. Invoked with any non-error callback results of
- * `iteratee`.
- * @param {Function} [callback] - A callback which is called after the test
- * function has failed and repeated execution of `iteratee` has stopped.
- * `callback` will be passed an error and any arguments passed to the final
- * `iteratee`'s callback. Invoked with (err, [results]);
- */
- function doWhilst(iteratee, test, callback) {
- callback = onlyOnce(callback || noop);
- var _iteratee = wrapAsync(iteratee);
- var next = function(err/*, ...args*/) {
- if (err) return callback(err);
- var args = slice(arguments, 1);
- if (test.apply(this, args)) return _iteratee(next);
- callback.apply(null, [null].concat(args));
- };
- _iteratee(next);
- }
- /**
- * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
- * argument ordering differs from `until`.
- *
- * @name doUntil
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
- * @category Control Flow
- * @param {AsyncFunction} iteratee - An async function which is called each time
- * `test` fails. Invoked with (callback).
- * @param {Function} test - synchronous truth test to perform after each
- * execution of `iteratee`. Invoked with any non-error callback results of
- * `iteratee`.
- * @param {Function} [callback] - A callback which is called after the test
- * function has passed and repeated execution of `iteratee` has stopped. `callback`
- * will be passed an error and any arguments passed to the final `iteratee`'s
- * callback. Invoked with (err, [results]);
- */
- function doUntil(iteratee, test, callback) {
- doWhilst(iteratee, function() {
- return !test.apply(this, arguments);
- }, callback);
- }
- /**
- * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
- * is passed a callback in the form of `function (err, truth)`. If error is
- * passed to `test` or `fn`, the main callback is immediately called with the
- * value of the error.
- *
- * @name during
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.whilst]{@link module:ControlFlow.whilst}
- * @category Control Flow
- * @param {AsyncFunction} test - asynchronous truth test to perform before each
- * execution of `fn`. Invoked with (callback).
- * @param {AsyncFunction} fn - An async function which is called each time
- * `test` passes. Invoked with (callback).
- * @param {Function} [callback] - A callback which is called after the test
- * function has failed and repeated execution of `fn` has stopped. `callback`
- * will be passed an error, if one occurred, otherwise `null`.
- * @example
- *
- * var count = 0;
- *
- * async.during(
- * function (callback) {
- * return callback(null, count < 5);
- * },
- * function (callback) {
- * count++;
- * setTimeout(callback, 1000);
- * },
- * function (err) {
- * // 5 seconds have passed
- * }
- * );
- */
- function during(test, fn, callback) {
- callback = onlyOnce(callback || noop);
- var _fn = wrapAsync(fn);
- var _test = wrapAsync(test);
- function next(err) {
- if (err) return callback(err);
- _test(check);
- }
- function check(err, truth) {
- if (err) return callback(err);
- if (!truth) return callback(null);
- _fn(next);
- }
- _test(check);
- }
- function _withoutIndex(iteratee) {
- return function (value, index, callback) {
- return iteratee(value, callback);
- };
- }
- /**
- * Applies the function `iteratee` to each item in `coll`, in parallel.
- * The `iteratee` is called with an item from the list, and a callback for when
- * it has finished. If the `iteratee` passes an error to its `callback`, the
- * main `callback` (for the `each` function) is immediately called with the
- * error.
- *
- * Note, that since this function applies `iteratee` to each item in parallel,
- * there is no guarantee that the iteratee functions will complete in order.
- *
- * @name each
- * @static
- * @memberOf module:Collections
- * @method
- * @alias forEach
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to
- * each item in `coll`. Invoked with (item, callback).
- * The array index is not passed to the iteratee.
- * If you need the index, use `eachOf`.
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- * @example
- *
- * // assuming openFiles is an array of file names and saveFile is a function
- * // to save the modified contents of that file:
- *
- * async.each(openFiles, saveFile, function(err){
- * // if any of the saves produced an error, err would equal that error
- * });
- *
- * // assuming openFiles is an array of file names
- * async.each(openFiles, function(file, callback) {
- *
- * // Perform operation on file here.
- * console.log('Processing file ' + file);
- *
- * if( file.length > 32 ) {
- * console.log('This file name is too long');
- * callback('File name too long');
- * } else {
- * // Do work to process file here
- * console.log('File processed');
- * callback();
- * }
- * }, function(err) {
- * // if any of the file processing produced an error, err would equal that error
- * if( err ) {
- * // One of the iterations produced an error.
- * // All processing will now stop.
- * console.log('A file failed to process');
- * } else {
- * console.log('All files have been processed successfully');
- * }
- * });
- */
- function eachLimit(coll, iteratee, callback) {
- eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback);
- }
- /**
- * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
- *
- * @name eachLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.each]{@link module:Collections.each}
- * @alias forEachLimit
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The array index is not passed to the iteratee.
- * If you need the index, use `eachOfLimit`.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- */
- function eachLimit$1(coll, limit, iteratee, callback) {
- _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
- }
- /**
- * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
- *
- * @name eachSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.each]{@link module:Collections.each}
- * @alias forEachSeries
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each
- * item in `coll`.
- * The array index is not passed to the iteratee.
- * If you need the index, use `eachOfSeries`.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- */
- var eachSeries = doLimit(eachLimit$1, 1);
- /**
- * Wrap an async function and ensure it calls its callback on a later tick of
- * the event loop. If the function already calls its callback on a next tick,
- * no extra deferral is added. This is useful for preventing stack overflows
- * (`RangeError: Maximum call stack size exceeded`) and generally keeping
- * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
- * contained. ES2017 `async` functions are returned as-is -- they are immune
- * to Zalgo's corrupting influences, as they always resolve on a later tick.
- *
- * @name ensureAsync
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} fn - an async function, one that expects a node-style
- * callback as its last argument.
- * @returns {AsyncFunction} Returns a wrapped function with the exact same call
- * signature as the function passed in.
- * @example
- *
- * function sometimesAsync(arg, callback) {
- * if (cache[arg]) {
- * return callback(null, cache[arg]); // this would be synchronous!!
- * } else {
- * doSomeIO(arg, callback); // this IO would be asynchronous
- * }
- * }
- *
- * // this has a risk of stack overflows if many results are cached in a row
- * async.mapSeries(args, sometimesAsync, done);
- *
- * // this will defer sometimesAsync's callback if necessary,
- * // preventing stack overflows
- * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
- */
- function ensureAsync(fn) {
- if (isAsync(fn)) return fn;
- return initialParams(function (args, callback) {
- var sync = true;
- args.push(function () {
- var innerArgs = arguments;
- if (sync) {
- setImmediate$1(function () {
- callback.apply(null, innerArgs);
- });
- } else {
- callback.apply(null, innerArgs);
- }
- });
- fn.apply(this, args);
- sync = false;
- });
- }
- function notId(v) {
- return !v;
- }
- /**
- * Returns `true` if every element in `coll` satisfies an async test. If any
- * iteratee call returns `false`, the main `callback` is immediately called.
- *
- * @name every
- * @static
- * @memberOf module:Collections
- * @method
- * @alias all
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collection in parallel.
- * The iteratee must complete with a boolean result value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result will be either `true` or `false`
- * depending on the values of the async tests. Invoked with (err, result).
- * @example
- *
- * async.every(['file1','file2','file3'], function(filePath, callback) {
- * fs.access(filePath, function(err) {
- * callback(null, !err)
- * });
- * }, function(err, result) {
- * // if result is true then every file exists
- * });
- */
- var every = doParallel(_createTester(notId, notId));
- /**
- * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
- *
- * @name everyLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.every]{@link module:Collections.every}
- * @alias allLimit
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collection in parallel.
- * The iteratee must complete with a boolean result value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result will be either `true` or `false`
- * depending on the values of the async tests. Invoked with (err, result).
- */
- var everyLimit = doParallelLimit(_createTester(notId, notId));
- /**
- * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
- *
- * @name everySeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.every]{@link module:Collections.every}
- * @alias allSeries
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collection in series.
- * The iteratee must complete with a boolean result value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result will be either `true` or `false`
- * depending on the values of the async tests. Invoked with (err, result).
- */
- var everySeries = doLimit(everyLimit, 1);
- /**
- * 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];
- };
- }
- function filterArray(eachfn, arr, iteratee, callback) {
- var truthValues = new Array(arr.length);
- eachfn(arr, function (x, index, callback) {
- iteratee(x, function (err, v) {
- truthValues[index] = !!v;
- callback(err);
- });
- }, function (err) {
- if (err) return callback(err);
- var results = [];
- for (var i = 0; i < arr.length; i++) {
- if (truthValues[i]) results.push(arr[i]);
- }
- callback(null, results);
- });
- }
- function filterGeneric(eachfn, coll, iteratee, callback) {
- var results = [];
- eachfn(coll, function (x, index, callback) {
- iteratee(x, function (err, v) {
- if (err) {
- callback(err);
- } else {
- if (v) {
- results.push({index: index, value: x});
- }
- callback();
- }
- });
- }, function (err) {
- if (err) {
- callback(err);
- } else {
- callback(null, arrayMap(results.sort(function (a, b) {
- return a.index - b.index;
- }), baseProperty('value')));
- }
- });
- }
- function _filter(eachfn, coll, iteratee, callback) {
- var filter = isArrayLike(coll) ? filterArray : filterGeneric;
- filter(eachfn, coll, wrapAsync(iteratee), callback || noop);
- }
- /**
- * Returns a new array of all the values in `coll` which pass an async truth
- * test. This operation is performed in parallel, but the results array will be
- * in the same order as the original.
- *
- * @name filter
- * @static
- * @memberOf module:Collections
- * @method
- * @alias select
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {Function} iteratee - A truth test to apply to each item in `coll`.
- * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
- * with a boolean argument once it has completed. Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results).
- * @example
- *
- * async.filter(['file1','file2','file3'], function(filePath, callback) {
- * fs.access(filePath, function(err) {
- * callback(null, !err)
- * });
- * }, function(err, results) {
- * // results now equals an array of the existing files
- * });
- */
- var filter = doParallel(_filter);
- /**
- * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name filterLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.filter]{@link module:Collections.filter}
- * @alias selectLimit
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {Function} iteratee - A truth test to apply to each item in `coll`.
- * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
- * with a boolean argument once it has completed. Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results).
- */
- var filterLimit = doParallelLimit(_filter);
- /**
- * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
- *
- * @name filterSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.filter]{@link module:Collections.filter}
- * @alias selectSeries
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {Function} iteratee - A truth test to apply to each item in `coll`.
- * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
- * with a boolean argument once it has completed. Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results)
- */
- var filterSeries = doLimit(filterLimit, 1);
- /**
- * Calls the asynchronous function `fn` with a callback parameter that allows it
- * to call itself again, in series, indefinitely.
- * If an error is passed to the callback then `errback` is called with the
- * error, and execution stops, otherwise it will never be called.
- *
- * @name forever
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {AsyncFunction} fn - an async function to call repeatedly.
- * Invoked with (next).
- * @param {Function} [errback] - when `fn` passes an error to it's callback,
- * this function will be called, and execution stops. Invoked with (err).
- * @example
- *
- * async.forever(
- * function(next) {
- * // next is suitable for passing to things that need a callback(err [, whatever]);
- * // it will result in this function being called again.
- * },
- * function(err) {
- * // if next is called with a value in its first parameter, it will appear
- * // in here as 'err', and execution will stop.
- * }
- * );
- */
- function forever(fn, errback) {
- var done = onlyOnce(errback || noop);
- var task = wrapAsync(ensureAsync(fn));
- function next(err) {
- if (err) return done(err);
- task(next);
- }
- next();
- }
- /**
- * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
- *
- * @name groupByLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.groupBy]{@link module:Collections.groupBy}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with a `key` to group the value under.
- * Invoked with (value, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Result is an `Object` whoses
- * properties are arrays of values which returned the corresponding key.
- */
- var groupByLimit = function(coll, limit, iteratee, callback) {
- callback = callback || noop;
- var _iteratee = wrapAsync(iteratee);
- mapLimit(coll, limit, function(val, callback) {
- _iteratee(val, function(err, key) {
- if (err) return callback(err);
- return callback(null, {key: key, val: val});
- });
- }, function(err, mapResults) {
- var result = {};
- // from MDN, handle object having an `hasOwnProperty` prop
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- for (var i = 0; i < mapResults.length; i++) {
- if (mapResults[i]) {
- var key = mapResults[i].key;
- var val = mapResults[i].val;
- if (hasOwnProperty.call(result, key)) {
- result[key].push(val);
- } else {
- result[key] = [val];
- }
- }
- }
- return callback(err, result);
- });
- };
- /**
- * Returns a new object, where each value corresponds to an array of items, from
- * `coll`, that returned the corresponding key. That is, the keys of the object
- * correspond to the values passed to the `iteratee` callback.
- *
- * Note: Since this function applies the `iteratee` to each item in parallel,
- * there is no guarantee that the `iteratee` functions will complete in order.
- * However, the values for each key in the `result` will be in the same order as
- * the original `coll`. For Objects, the values will roughly be in the order of
- * the original Objects' keys (but this can vary across JavaScript engines).
- *
- * @name groupBy
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with a `key` to group the value under.
- * Invoked with (value, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Result is an `Object` whoses
- * properties are arrays of values which returned the corresponding key.
- * @example
- *
- * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
- * db.findById(userId, function(err, user) {
- * if (err) return callback(err);
- * return callback(null, user.age);
- * });
- * }, function(err, result) {
- * // result is object containing the userIds grouped by age
- * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
- * });
- */
- var groupBy = doLimit(groupByLimit, Infinity);
- /**
- * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
- *
- * @name groupBySeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.groupBy]{@link module:Collections.groupBy}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with a `key` to group the value under.
- * Invoked with (value, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Result is an `Object` whoses
- * properties are arrays of values which returned the corresponding key.
- */
- var groupBySeries = doLimit(groupByLimit, 1);
- /**
- * Logs the result of an `async` function to the `console`. Only works in
- * Node.js or in browsers that support `console.log` and `console.error` (such
- * as FF and Chrome). If multiple arguments are returned from the async
- * function, `console.log` is called on each argument in order.
- *
- * @name log
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} function - The function you want to eventually apply
- * all arguments to.
- * @param {...*} arguments... - Any number of arguments to apply to the function.
- * @example
- *
- * // in a module
- * var hello = function(name, callback) {
- * setTimeout(function() {
- * callback(null, 'hello ' + name);
- * }, 1000);
- * };
- *
- * // in the node repl
- * node> async.log(hello, 'world');
- * 'hello world'
- */
- var log = consoleFunc('log');
- /**
- * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name mapValuesLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.mapValues]{@link module:Collections.mapValues}
- * @category Collection
- * @param {Object} obj - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - A function to apply to each value and key
- * in `coll`.
- * The iteratee should complete with the transformed value as its result.
- * Invoked with (value, key, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. `result` is a new object consisting
- * of each key from `obj`, with each transformed value on the right-hand side.
- * Invoked with (err, result).
- */
- function mapValuesLimit(obj, limit, iteratee, callback) {
- callback = once(callback || noop);
- var newObj = {};
- var _iteratee = wrapAsync(iteratee);
- eachOfLimit(obj, limit, function(val, key, next) {
- _iteratee(val, key, function (err, result) {
- if (err) return next(err);
- newObj[key] = result;
- next();
- });
- }, function (err) {
- callback(err, newObj);
- });
- }
- /**
- * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
- *
- * Produces a new Object by mapping each value of `obj` through the `iteratee`
- * function. The `iteratee` is called each `value` and `key` from `obj` and a
- * callback for when it has finished processing. Each of these callbacks takes
- * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
- * passes an error to its callback, the main `callback` (for the `mapValues`
- * function) is immediately called with the error.
- *
- * Note, the order of the keys in the result is not guaranteed. The keys will
- * be roughly in the order they complete, (but this is very engine-specific)
- *
- * @name mapValues
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Object} obj - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each value and key
- * in `coll`.
- * The iteratee should complete with the transformed value as its result.
- * Invoked with (value, key, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. `result` is a new object consisting
- * of each key from `obj`, with each transformed value on the right-hand side.
- * Invoked with (err, result).
- * @example
- *
- * async.mapValues({
- * f1: 'file1',
- * f2: 'file2',
- * f3: 'file3'
- * }, function (file, key, callback) {
- * fs.stat(file, callback);
- * }, function(err, result) {
- * // result is now a map of stats for each file, e.g.
- * // {
- * // f1: [stats for file1],
- * // f2: [stats for file2],
- * // f3: [stats for file3]
- * // }
- * });
- */
- var mapValues = doLimit(mapValuesLimit, Infinity);
- /**
- * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
- *
- * @name mapValuesSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.mapValues]{@link module:Collections.mapValues}
- * @category Collection
- * @param {Object} obj - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each value and key
- * in `coll`.
- * The iteratee should complete with the transformed value as its result.
- * Invoked with (value, key, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. `result` is a new object consisting
- * of each key from `obj`, with each transformed value on the right-hand side.
- * Invoked with (err, result).
- */
- var mapValuesSeries = doLimit(mapValuesLimit, 1);
- function has(obj, key) {
- return key in obj;
- }
- /**
- * Caches the results of an async function. When creating a hash to store
- * function results against, the callback is omitted from the hash and an
- * optional hash function can be used.
- *
- * If no hash function is specified, the first argument is used as a hash key,
- * which may work reasonably if it is a string or a data type that converts to a
- * distinct string. Note that objects and arrays will not behave reasonably.
- * Neither will cases where the other arguments are significant. In such cases,
- * specify your own hash function.
- *
- * The cache of results is exposed as the `memo` property of the function
- * returned by `memoize`.
- *
- * @name memoize
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} fn - The async function to proxy and cache results from.
- * @param {Function} hasher - An optional function for generating a custom hash
- * for storing results. It has all the arguments applied to it apart from the
- * callback, and must be synchronous.
- * @returns {AsyncFunction} a memoized version of `fn`
- * @example
- *
- * var slow_fn = function(name, callback) {
- * // do something
- * callback(null, result);
- * };
- * var fn = async.memoize(slow_fn);
- *
- * // fn can now be used as if it were slow_fn
- * fn('some name', function() {
- * // callback
- * });
- */
- function memoize(fn, hasher) {
- var memo = Object.create(null);
- var queues = Object.create(null);
- hasher = hasher || identity;
- var _fn = wrapAsync(fn);
- var memoized = initialParams(function memoized(args, callback) {
- var key = hasher.apply(null, args);
- if (has(memo, key)) {
- setImmediate$1(function() {
- callback.apply(null, memo[key]);
- });
- } else if (has(queues, key)) {
- queues[key].push(callback);
- } else {
- queues[key] = [callback];
- _fn.apply(null, args.concat(function(/*args*/) {
- var args = slice(arguments);
- memo[key] = args;
- var q = queues[key];
- delete queues[key];
- for (var i = 0, l = q.length; i < l; i++) {
- q[i].apply(null, args);
- }
- }));
- }
- });
- memoized.memo = memo;
- memoized.unmemoized = fn;
- return memoized;
- }
- /**
- * Calls `callback` on a later loop around the event loop. In Node.js this just
- * calls `process.nextTick`. In the browser it will use `setImmediate` if
- * available, otherwise `setTimeout(callback, 0)`, which means other higher
- * priority events may precede the execution of `callback`.
- *
- * This is used internally for browser-compatibility purposes.
- *
- * @name nextTick
- * @static
- * @memberOf module:Utils
- * @method
- * @see [async.setImmediate]{@link module:Utils.setImmediate}
- * @category Util
- * @param {Function} callback - The function to call on a later loop around
- * the event loop. Invoked with (args...).
- * @param {...*} args... - any number of additional arguments to pass to the
- * callback on the next tick.
- * @example
- *
- * var call_order = [];
- * async.nextTick(function() {
- * call_order.push('two');
- * // call_order now equals ['one','two']
- * });
- * call_order.push('one');
- *
- * async.setImmediate(function (a, b, c) {
- * // a, b, and c equal 1, 2, and 3
- * }, 1, 2, 3);
- */
- var _defer$1;
- if (hasNextTick) {
- _defer$1 = process.nextTick;
- } else if (hasSetImmediate) {
- _defer$1 = setImmediate;
- } else {
- _defer$1 = fallback;
- }
- var nextTick = wrap(_defer$1);
- function _parallel(eachfn, tasks, callback) {
- callback = callback || noop;
- var results = isArrayLike(tasks) ? [] : {};
- eachfn(tasks, function (task, key, callback) {
- wrapAsync(task)(function (err, result) {
- if (arguments.length > 2) {
- result = slice(arguments, 1);
- }
- results[key] = result;
- callback(err);
- });
- }, function (err) {
- callback(err, results);
- });
- }
- /**
- * Run the `tasks` collection of functions in parallel, without waiting until
- * the previous function has completed. If any of the functions pass an error to
- * its callback, the main `callback` is immediately called with the value of the
- * error. Once the `tasks` have completed, the results are passed to the final
- * `callback` as an array.
- *
- * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
- * parallel execution of code. If your tasks do not use any timers or perform
- * any I/O, they will actually be executed in series. Any synchronous setup
- * sections for each task will happen one after the other. JavaScript remains
- * single-threaded.
- *
- * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
- * execution of other tasks when a task fails.
- *
- * It is also possible to use an object instead of an array. Each property will
- * be run as a function and the results will be passed to the final `callback`
- * as an object instead of an array. This can be a more readable way of handling
- * results from {@link async.parallel}.
- *
- * @name parallel
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array|Iterable|Object} tasks - A collection of
- * [async functions]{@link AsyncFunction} to run.
- * Each async function can complete with any number of optional `result` values.
- * @param {Function} [callback] - An optional callback to run once all the
- * functions have completed successfully. This function gets a results array
- * (or object) containing all the result arguments passed to the task callbacks.
- * Invoked with (err, results).
- *
- * @example
- * async.parallel([
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'one');
- * }, 200);
- * },
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'two');
- * }, 100);
- * }
- * ],
- * // optional callback
- * function(err, results) {
- * // the results array will equal ['one','two'] even though
- * // the second function had a shorter timeout.
- * });
- *
- * // an example using an object instead of an array
- * async.parallel({
- * one: function(callback) {
- * setTimeout(function() {
- * callback(null, 1);
- * }, 200);
- * },
- * two: function(callback) {
- * setTimeout(function() {
- * callback(null, 2);
- * }, 100);
- * }
- * }, function(err, results) {
- * // results is now equals to: {one: 1, two: 2}
- * });
- */
- function parallelLimit(tasks, callback) {
- _parallel(eachOf, tasks, callback);
- }
- /**
- * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name parallelLimit
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.parallel]{@link module:ControlFlow.parallel}
- * @category Control Flow
- * @param {Array|Iterable|Object} tasks - A collection of
- * [async functions]{@link AsyncFunction} to run.
- * Each async function can complete with any number of optional `result` values.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {Function} [callback] - An optional callback to run once all the
- * functions have completed successfully. This function gets a results array
- * (or object) containing all the result arguments passed to the task callbacks.
- * Invoked with (err, results).
- */
- function parallelLimit$1(tasks, limit, callback) {
- _parallel(_eachOfLimit(limit), tasks, callback);
- }
- /**
- * A queue of tasks for the worker function to complete.
- * @typedef {Object} QueueObject
- * @memberOf module:ControlFlow
- * @property {Function} length - a function returning the number of items
- * waiting to be processed. Invoke with `queue.length()`.
- * @property {boolean} started - a boolean indicating whether or not any
- * items have been pushed and processed by the queue.
- * @property {Function} running - a function returning the number of items
- * currently being processed. Invoke with `queue.running()`.
- * @property {Function} workersList - a function returning the array of items
- * currently being processed. Invoke with `queue.workersList()`.
- * @property {Function} idle - a function returning false if there are items
- * waiting or being processed, or true if not. Invoke with `queue.idle()`.
- * @property {number} concurrency - an integer for determining how many `worker`
- * functions should be run in parallel. This property can be changed after a
- * `queue` is created to alter the concurrency on-the-fly.
- * @property {Function} push - add a new task to the `queue`. Calls `callback`
- * once the `worker` has finished processing the task. Instead of a single task,
- * a `tasks` array can be submitted. The respective callback is used for every
- * task in the list. Invoke with `queue.push(task, [callback])`,
- * @property {Function} unshift - add a new task to the front of the `queue`.
- * Invoke with `queue.unshift(task, [callback])`.
- * @property {Function} remove - remove items from the queue that match a test
- * function. The test function will be passed an object with a `data` property,
- * and a `priority` property, if this is a
- * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
- * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
- * `function ({data, priority}) {}` and returns a Boolean.
- * @property {Function} saturated - a callback that is called when the number of
- * running workers hits the `concurrency` limit, and further tasks will be
- * queued.
- * @property {Function} unsaturated - a callback that is called when the number
- * of running workers is less than the `concurrency` & `buffer` limits, and
- * further tasks will not be queued.
- * @property {number} buffer - A minimum threshold buffer in order to say that
- * the `queue` is `unsaturated`.
- * @property {Function} empty - a callback that is called when the last item
- * from the `queue` is given to a `worker`.
- * @property {Function} drain - a callback that is called when the last item
- * from the `queue` has returned from the `worker`.
- * @property {Function} error - a callback that is called when a task errors.
- * Has the signature `function(error, task)`.
- * @property {boolean} paused - a boolean for determining whether the queue is
- * in a paused state.
- * @property {Function} pause - a function that pauses the processing of tasks
- * until `resume()` is called. Invoke with `queue.pause()`.
- * @property {Function} resume - a function that resumes the processing of
- * queued tasks when the queue is paused. Invoke with `queue.resume()`.
- * @property {Function} kill - a function that removes the `drain` callback and
- * empties remaining tasks from the queue forcing it to go idle. No more tasks
- * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
- */
- /**
- * Creates a `queue` object with the specified `concurrency`. Tasks added to the
- * `queue` are processed in parallel (up to the `concurrency` limit). If all
- * `worker`s are in progress, the task is queued until one becomes available.
- * Once a `worker` completes a `task`, that `task`'s callback is called.
- *
- * @name queue
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {AsyncFunction} worker - An async function for processing a queued task.
- * If you want to handle errors from an individual task, pass a callback to
- * `q.push()`. Invoked with (task, callback).
- * @param {number} [concurrency=1] - An `integer` for determining how many
- * `worker` functions should be run in parallel. If omitted, the concurrency
- * defaults to `1`. If the concurrency is `0`, an error is thrown.
- * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
- * attached as certain properties to listen for specific events during the
- * lifecycle of the queue.
- * @example
- *
- * // create a queue object with concurrency 2
- * var q = async.queue(function(task, callback) {
- * console.log('hello ' + task.name);
- * callback();
- * }, 2);
- *
- * // assign a callback
- * q.drain = function() {
- * console.log('all items have been processed');
- * };
- *
- * // add some items to the queue
- * q.push({name: 'foo'}, function(err) {
- * console.log('finished processing foo');
- * });
- * q.push({name: 'bar'}, function (err) {
- * console.log('finished processing bar');
- * });
- *
- * // add some items to the queue (batch-wise)
- * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
- * console.log('finished processing item');
- * });
- *
- * // add some items to the front of the queue
- * q.unshift({name: 'bar'}, function (err) {
- * console.log('finished processing bar');
- * });
- */
- var queue$1 = function (worker, concurrency) {
- var _worker = wrapAsync(worker);
- return queue(function (items, cb) {
- _worker(items[0], cb);
- }, concurrency, 1);
- };
- /**
- * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
- * completed in ascending priority order.
- *
- * @name priorityQueue
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.queue]{@link module:ControlFlow.queue}
- * @category Control Flow
- * @param {AsyncFunction} worker - An async function for processing a queued task.
- * If you want to handle errors from an individual task, pass a callback to
- * `q.push()`.
- * Invoked with (task, callback).
- * @param {number} concurrency - An `integer` for determining how many `worker`
- * functions should be run in parallel. If omitted, the concurrency defaults to
- * `1`. If the concurrency is `0`, an error is thrown.
- * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
- * differences between `queue` and `priorityQueue` objects:
- * * `push(task, priority, [callback])` - `priority` should be a number. If an
- * array of `tasks` is given, all tasks will be assigned the same priority.
- * * The `unshift` method was removed.
- */
- var priorityQueue = function(worker, concurrency) {
- // Start with a normal queue
- var q = queue$1(worker, concurrency);
- // Override push to accept second parameter representing priority
- q.push = function(data, priority, callback) {
- if (callback == null) callback = noop;
- if (typeof callback !== 'function') {
- throw new Error('task callback must be a function');
- }
- q.started = true;
- if (!isArray(data)) {
- data = [data];
- }
- if (data.length === 0) {
- // call drain immediately if there are no tasks
- return setImmediate$1(function() {
- q.drain();
- });
- }
- priority = priority || 0;
- var nextNode = q._tasks.head;
- while (nextNode && priority >= nextNode.priority) {
- nextNode = nextNode.next;
- }
- for (var i = 0, l = data.length; i < l; i++) {
- var item = {
- data: data[i],
- priority: priority,
- callback: callback
- };
- if (nextNode) {
- q._tasks.insertBefore(nextNode, item);
- } else {
- q._tasks.push(item);
- }
- }
- setImmediate$1(q.process);
- };
- // Remove unshift function
- delete q.unshift;
- return q;
- };
- /**
- * Runs the `tasks` array of functions in parallel, without waiting until the
- * previous function has completed. Once any of the `tasks` complete or pass an
- * error to its callback, the main `callback` is immediately called. It's
- * equivalent to `Promise.race()`.
- *
- * @name race
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
- * to run. Each function can complete with an optional `result` value.
- * @param {Function} callback - A callback to run once any of the functions have
- * completed. This function gets an error or result from the first function that
- * completed. Invoked with (err, result).
- * @returns undefined
- * @example
- *
- * async.race([
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'one');
- * }, 200);
- * },
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'two');
- * }, 100);
- * }
- * ],
- * // main callback
- * function(err, result) {
- * // the result will be equal to 'two' as it finishes earlier
- * });
- */
- function race(tasks, callback) {
- callback = once(callback || noop);
- if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
- if (!tasks.length) return callback();
- for (var i = 0, l = tasks.length; i < l; i++) {
- wrapAsync(tasks[i])(callback);
- }
- }
- /**
- * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
- *
- * @name reduceRight
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.reduce]{@link module:Collections.reduce}
- * @alias foldr
- * @category Collection
- * @param {Array} array - A collection to iterate over.
- * @param {*} memo - The initial state of the reduction.
- * @param {AsyncFunction} iteratee - A function applied to each item in the
- * array to produce the next step in the reduction.
- * The `iteratee` should complete with the next state of the reduction.
- * If the iteratee complete with an error, the reduction is stopped and the
- * main `callback` is immediately called with the error.
- * Invoked with (memo, item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result is the reduced value. Invoked with
- * (err, result).
- */
- function reduceRight (array, memo, iteratee, callback) {
- var reversed = slice(array).reverse();
- reduce(reversed, memo, iteratee, callback);
- }
- /**
- * Wraps the async function in another function that always completes with a
- * result object, even when it errors.
- *
- * The result object has either the property `error` or `value`.
- *
- * @name reflect
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} fn - The async function you want to wrap
- * @returns {Function} - A function that always passes null to it's callback as
- * the error. The second argument to the callback will be an `object` with
- * either an `error` or a `value` property.
- * @example
- *
- * async.parallel([
- * async.reflect(function(callback) {
- * // do some stuff ...
- * callback(null, 'one');
- * }),
- * async.reflect(function(callback) {
- * // do some more stuff but error ...
- * callback('bad stuff happened');
- * }),
- * async.reflect(function(callback) {
- * // do some more stuff ...
- * callback(null, 'two');
- * })
- * ],
- * // optional callback
- * function(err, results) {
- * // values
- * // results[0].value = 'one'
- * // results[1].error = 'bad stuff happened'
- * // results[2].value = 'two'
- * });
- */
- function reflect(fn) {
- var _fn = wrapAsync(fn);
- return initialParams(function reflectOn(args, reflectCallback) {
- args.push(function callback(error, cbArg) {
- if (error) {
- reflectCallback(null, { error: error });
- } else {
- var value;
- if (arguments.length <= 2) {
- value = cbArg;
- } else {
- value = slice(arguments, 1);
- }
- reflectCallback(null, { value: value });
- }
- });
- return _fn.apply(this, args);
- });
- }
- /**
- * A helper function that wraps an array or an object of functions with `reflect`.
- *
- * @name reflectAll
- * @static
- * @memberOf module:Utils
- * @method
- * @see [async.reflect]{@link module:Utils.reflect}
- * @category Util
- * @param {Array|Object|Iterable} tasks - The collection of
- * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
- * @returns {Array} Returns an array of async functions, each wrapped in
- * `async.reflect`
- * @example
- *
- * let tasks = [
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'one');
- * }, 200);
- * },
- * function(callback) {
- * // do some more stuff but error ...
- * callback(new Error('bad stuff happened'));
- * },
- * function(callback) {
- * setTimeout(function() {
- * callback(null, 'two');
- * }, 100);
- * }
- * ];
- *
- * async.parallel(async.reflectAll(tasks),
- * // optional callback
- * function(err, results) {
- * // values
- * // results[0].value = 'one'
- * // results[1].error = Error('bad stuff happened')
- * // results[2].value = 'two'
- * });
- *
- * // an example using an object instead of an array
- * let tasks = {
- * one: function(callback) {
- * setTimeout(function() {
- * callback(null, 'one');
- * }, 200);
- * },
- * two: function(callback) {
- * callback('two');
- * },
- * three: function(callback) {
- * setTimeout(function() {
- * callback(null, 'three');
- * }, 100);
- * }
- * };
- *
- * async.parallel(async.reflectAll(tasks),
- * // optional callback
- * function(err, results) {
- * // values
- * // results.one.value = 'one'
- * // results.two.error = 'two'
- * // results.three.value = 'three'
- * });
- */
- function reflectAll(tasks) {
- var results;
- if (isArray(tasks)) {
- results = arrayMap(tasks, reflect);
- } else {
- results = {};
- baseForOwn(tasks, function(task, key) {
- results[key] = reflect.call(this, task);
- });
- }
- return results;
- }
- function reject$1(eachfn, arr, iteratee, callback) {
- _filter(eachfn, arr, function(value, cb) {
- iteratee(value, function(err, v) {
- cb(err, !v);
- });
- }, callback);
- }
- /**
- * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
- *
- * @name reject
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.filter]{@link module:Collections.filter}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {Function} iteratee - An async truth test to apply to each item in
- * `coll`.
- * The should complete with a boolean value as its `result`.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results).
- * @example
- *
- * async.reject(['file1','file2','file3'], function(filePath, callback) {
- * fs.access(filePath, function(err) {
- * callback(null, !err)
- * });
- * }, function(err, results) {
- * // results now equals an array of missing files
- * createFiles(results);
- * });
- */
- var reject = doParallel(reject$1);
- /**
- * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name rejectLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.reject]{@link module:Collections.reject}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {Function} iteratee - An async truth test to apply to each item in
- * `coll`.
- * The should complete with a boolean value as its `result`.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results).
- */
- var rejectLimit = doParallelLimit(reject$1);
- /**
- * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
- *
- * @name rejectSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.reject]{@link module:Collections.reject}
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {Function} iteratee - An async truth test to apply to each item in
- * `coll`.
- * The should complete with a boolean value as its `result`.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Invoked with (err, results).
- */
- var rejectSeries = doLimit(rejectLimit, 1);
- /**
- * 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$1(value) {
- return function() {
- return value;
- };
- }
- /**
- * Attempts to get a successful response from `task` no more than `times` times
- * before returning an error. If the task is successful, the `callback` will be
- * passed the result of the successful task. If all attempts fail, the callback
- * will be passed the error and result (if any) of the final attempt.
- *
- * @name retry
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @see [async.retryable]{@link module:ControlFlow.retryable}
- * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
- * object with `times` and `interval` or a number.
- * * `times` - The number of attempts to make before giving up. The default
- * is `5`.
- * * `interval` - The time to wait between retries, in milliseconds. The
- * default is `0`. The interval may also be specified as a function of the
- * retry count (see example).
- * * `errorFilter` - An optional synchronous function that is invoked on
- * erroneous result. If it returns `true` the retry attempts will continue;
- * if the function returns `false` the retry flow is aborted with the current
- * attempt's error and result being returned to the final callback.
- * Invoked with (err).
- * * If `opts` is a number, the number specifies the number of times to retry,
- * with the default interval of `0`.
- * @param {AsyncFunction} task - An async function to retry.
- * Invoked with (callback).
- * @param {Function} [callback] - An optional callback which is called when the
- * task has succeeded, or after the final failed attempt. It receives the `err`
- * and `result` arguments of the last attempt at completing the `task`. Invoked
- * with (err, results).
- *
- * @example
- *
- * // The `retry` function can be used as a stand-alone control flow by passing
- * // a callback, as shown below:
- *
- * // try calling apiMethod 3 times
- * async.retry(3, apiMethod, function(err, result) {
- * // do something with the result
- * });
- *
- * // try calling apiMethod 3 times, waiting 200 ms between each retry
- * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
- * // do something with the result
- * });
- *
- * // try calling apiMethod 10 times with exponential backoff
- * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
- * async.retry({
- * times: 10,
- * interval: function(retryCount) {
- * return 50 * Math.pow(2, retryCount);
- * }
- * }, apiMethod, function(err, result) {
- * // do something with the result
- * });
- *
- * // try calling apiMethod the default 5 times no delay between each retry
- * async.retry(apiMethod, function(err, result) {
- * // do something with the result
- * });
- *
- * // try calling apiMethod only when error condition satisfies, all other
- * // errors will abort the retry control flow and return to final callback
- * async.retry({
- * errorFilter: function(err) {
- * return err.message === 'Temporary error'; // only retry on a specific error
- * }
- * }, apiMethod, function(err, result) {
- * // do something with the result
- * });
- *
- * // to retry individual methods that are not as reliable within other
- * // control flow functions, use the `retryable` wrapper:
- * async.auto({
- * users: api.getUsers.bind(api),
- * payments: async.retryable(3, api.getPayments.bind(api))
- * }, function(err, results) {
- * // do something with the results
- * });
- *
- */
- function retry(opts, task, callback) {
- var DEFAULT_TIMES = 5;
- var DEFAULT_INTERVAL = 0;
- var options = {
- times: DEFAULT_TIMES,
- intervalFunc: constant$1(DEFAULT_INTERVAL)
- };
- function parseTimes(acc, t) {
- if (typeof t === 'object') {
- acc.times = +t.times || DEFAULT_TIMES;
- acc.intervalFunc = typeof t.interval === 'function' ?
- t.interval :
- constant$1(+t.interval || DEFAULT_INTERVAL);
- acc.errorFilter = t.errorFilter;
- } else if (typeof t === 'number' || typeof t === 'string') {
- acc.times = +t || DEFAULT_TIMES;
- } else {
- throw new Error("Invalid arguments for async.retry");
- }
- }
- if (arguments.length < 3 && typeof opts === 'function') {
- callback = task || noop;
- task = opts;
- } else {
- parseTimes(options, opts);
- callback = callback || noop;
- }
- if (typeof task !== 'function') {
- throw new Error("Invalid arguments for async.retry");
- }
- var _task = wrapAsync(task);
- var attempt = 1;
- function retryAttempt() {
- _task(function(err) {
- if (err && attempt++ < options.times &&
- (typeof options.errorFilter != 'function' ||
- options.errorFilter(err))) {
- setTimeout(retryAttempt, options.intervalFunc(attempt));
- } else {
- callback.apply(null, arguments);
- }
- });
- }
- retryAttempt();
- }
- /**
- * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
- * wraps a task and makes it retryable, rather than immediately calling it
- * with retries.
- *
- * @name retryable
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.retry]{@link module:ControlFlow.retry}
- * @category Control Flow
- * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
- * options, exactly the same as from `retry`
- * @param {AsyncFunction} task - the asynchronous function to wrap.
- * This function will be passed any arguments passed to the returned wrapper.
- * Invoked with (...args, callback).
- * @returns {AsyncFunction} The wrapped function, which when invoked, will
- * retry on an error, based on the parameters specified in `opts`.
- * This function will accept the same parameters as `task`.
- * @example
- *
- * async.auto({
- * dep1: async.retryable(3, getFromFlakyService),
- * process: ["dep1", async.retryable(3, function (results, cb) {
- * maybeProcessData(results.dep1, cb);
- * })]
- * }, callback);
- */
- var retryable = function (opts, task) {
- if (!task) {
- task = opts;
- opts = null;
- }
- var _task = wrapAsync(task);
- return initialParams(function (args, callback) {
- function taskFn(cb) {
- _task.apply(null, args.concat(cb));
- }
- if (opts) retry(opts, taskFn, callback);
- else retry(taskFn, callback);
- });
- };
- /**
- * Run the functions in the `tasks` collection in series, each one running once
- * the previous function has completed. If any functions in the series pass an
- * error to its callback, no more functions are run, and `callback` is
- * immediately called with the value of the error. Otherwise, `callback`
- * receives an array of results when `tasks` have completed.
- *
- * It is also possible to use an object instead of an array. Each property will
- * be run as a function, and the results will be passed to the final `callback`
- * as an object instead of an array. This can be a more readable way of handling
- * results from {@link async.series}.
- *
- * **Note** that while many implementations preserve the order of object
- * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
- * explicitly states that
- *
- * > The mechanics and order of enumerating the properties is not specified.
- *
- * So if you rely on the order in which your series of functions are executed,
- * and want this to work on all platforms, consider using an array.
- *
- * @name series
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array|Iterable|Object} tasks - A collection containing
- * [async functions]{@link AsyncFunction} to run in series.
- * Each function can complete with any number of optional `result` values.
- * @param {Function} [callback] - An optional callback to run once all the
- * functions have completed. This function gets a results array (or object)
- * containing all the result arguments passed to the `task` callbacks. Invoked
- * with (err, result).
- * @example
- * async.series([
- * function(callback) {
- * // do some stuff ...
- * callback(null, 'one');
- * },
- * function(callback) {
- * // do some more stuff ...
- * callback(null, 'two');
- * }
- * ],
- * // optional callback
- * function(err, results) {
- * // results is now equal to ['one', 'two']
- * });
- *
- * async.series({
- * one: function(callback) {
- * setTimeout(function() {
- * callback(null, 1);
- * }, 200);
- * },
- * two: function(callback){
- * setTimeout(function() {
- * callback(null, 2);
- * }, 100);
- * }
- * }, function(err, results) {
- * // results is now equal to: {one: 1, two: 2}
- * });
- */
- function series(tasks, callback) {
- _parallel(eachOfSeries, tasks, callback);
- }
- /**
- * Returns `true` if at least one element in the `coll` satisfies an async test.
- * If any iteratee call returns `true`, the main `callback` is immediately
- * called.
- *
- * @name some
- * @static
- * @memberOf module:Collections
- * @method
- * @alias any
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collections in parallel.
- * The iteratee should complete with a boolean `result` value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the iteratee functions have finished.
- * Result will be either `true` or `false` depending on the values of the async
- * tests. Invoked with (err, result).
- * @example
- *
- * async.some(['file1','file2','file3'], function(filePath, callback) {
- * fs.access(filePath, function(err) {
- * callback(null, !err)
- * });
- * }, function(err, result) {
- * // if result is true then at least one of the files exists
- * });
- */
- var some = doParallel(_createTester(Boolean, identity));
- /**
- * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
- *
- * @name someLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.some]{@link module:Collections.some}
- * @alias anyLimit
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collections in parallel.
- * The iteratee should complete with a boolean `result` value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the iteratee functions have finished.
- * Result will be either `true` or `false` depending on the values of the async
- * tests. Invoked with (err, result).
- */
- var someLimit = doParallelLimit(_createTester(Boolean, identity));
- /**
- * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
- *
- * @name someSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.some]{@link module:Collections.some}
- * @alias anySeries
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async truth test to apply to each item
- * in the collections in series.
- * The iteratee should complete with a boolean `result` value.
- * Invoked with (item, callback).
- * @param {Function} [callback] - A callback which is called as soon as any
- * iteratee returns `true`, or after all the iteratee functions have finished.
- * Result will be either `true` or `false` depending on the values of the async
- * tests. Invoked with (err, result).
- */
- var someSeries = doLimit(someLimit, 1);
- /**
- * Sorts a list by the results of running each `coll` value through an async
- * `iteratee`.
- *
- * @name sortBy
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * The iteratee should complete with a value to use as the sort criteria as
- * its `result`.
- * Invoked with (item, callback).
- * @param {Function} callback - A callback which is called after all the
- * `iteratee` functions have finished, or an error occurs. Results is the items
- * from the original `coll` sorted by the values returned by the `iteratee`
- * calls. Invoked with (err, results).
- * @example
- *
- * async.sortBy(['file1','file2','file3'], function(file, callback) {
- * fs.stat(file, function(err, stats) {
- * callback(err, stats.mtime);
- * });
- * }, function(err, results) {
- * // results is now the original array of files sorted by
- * // modified date
- * });
- *
- * // By modifying the callback parameter the
- * // sorting order can be influenced:
- *
- * // ascending order
- * async.sortBy([1,9,3,5], function(x, callback) {
- * callback(null, x);
- * }, function(err,result) {
- * // result callback
- * });
- *
- * // descending order
- * async.sortBy([1,9,3,5], function(x, callback) {
- * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
- * }, function(err,result) {
- * // result callback
- * });
- */
- function sortBy (coll, iteratee, callback) {
- var _iteratee = wrapAsync(iteratee);
- map(coll, function (x, callback) {
- _iteratee(x, function (err, criteria) {
- if (err) return callback(err);
- callback(null, {value: x, criteria: criteria});
- });
- }, function (err, results) {
- if (err) return callback(err);
- callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
- });
- function comparator(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }
- }
- /**
- * Sets a time limit on an asynchronous function. If the function does not call
- * its callback within the specified milliseconds, it will be called with a
- * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
- *
- * @name timeout
- * @static
- * @memberOf module:Utils
- * @method
- * @category Util
- * @param {AsyncFunction} asyncFn - The async function to limit in time.
- * @param {number} milliseconds - The specified time limit.
- * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
- * to timeout Error for more information..
- * @returns {AsyncFunction} Returns a wrapped function that can be used with any
- * of the control flow functions.
- * Invoke this function with the same parameters as you would `asyncFunc`.
- * @example
- *
- * function myFunction(foo, callback) {
- * doAsyncTask(foo, function(err, data) {
- * // handle errors
- * if (err) return callback(err);
- *
- * // do some stuff ...
- *
- * // return processed data
- * return callback(null, data);
- * });
- * }
- *
- * var wrapped = async.timeout(myFunction, 1000);
- *
- * // call `wrapped` as you would `myFunction`
- * wrapped({ bar: 'bar' }, function(err, data) {
- * // if `myFunction` takes < 1000 ms to execute, `err`
- * // and `data` will have their expected values
- *
- * // else `err` will be an Error with the code 'ETIMEDOUT'
- * });
- */
- function timeout(asyncFn, milliseconds, info) {
- var fn = wrapAsync(asyncFn);
- return initialParams(function (args, callback) {
- var timedOut = false;
- var timer;
- function timeoutCallback() {
- var name = asyncFn.name || 'anonymous';
- var error = new Error('Callback function "' + name + '" timed out.');
- error.code = 'ETIMEDOUT';
- if (info) {
- error.info = info;
- }
- timedOut = true;
- callback(error);
- }
- args.push(function () {
- if (!timedOut) {
- callback.apply(null, arguments);
- clearTimeout(timer);
- }
- });
- // setup timer and call original function
- timer = setTimeout(timeoutCallback, milliseconds);
- fn.apply(null, args);
- });
- }
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeCeil = Math.ceil;
- var nativeMax = Math.max;
- /**
- * The base implementation of `_.range` and `_.rangeRight` which doesn't
- * coerce arguments.
- *
- * @private
- * @param {number} start The start of the range.
- * @param {number} end The end of the range.
- * @param {number} step The value to increment or decrement by.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Array} Returns the range of numbers.
- */
- function baseRange(start, end, step, fromRight) {
- var index = -1,
- length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
- result = Array(length);
- while (length--) {
- result[fromRight ? length : ++index] = start;
- start += step;
- }
- return result;
- }
- /**
- * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name timesLimit
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.times]{@link module:ControlFlow.times}
- * @category Control Flow
- * @param {number} count - The number of times to run the function.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - The async function to call `n` times.
- * Invoked with the iteration index and a callback: (n, next).
- * @param {Function} callback - see [async.map]{@link module:Collections.map}.
- */
- function timeLimit(count, limit, iteratee, callback) {
- var _iteratee = wrapAsync(iteratee);
- mapLimit(baseRange(0, count, 1), limit, _iteratee, callback);
- }
- /**
- * Calls the `iteratee` function `n` times, and accumulates results in the same
- * manner you would use with [map]{@link module:Collections.map}.
- *
- * @name times
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.map]{@link module:Collections.map}
- * @category Control Flow
- * @param {number} n - The number of times to run the function.
- * @param {AsyncFunction} iteratee - The async function to call `n` times.
- * Invoked with the iteration index and a callback: (n, next).
- * @param {Function} callback - see {@link module:Collections.map}.
- * @example
- *
- * // Pretend this is some complicated async factory
- * var createUser = function(id, callback) {
- * callback(null, {
- * id: 'user' + id
- * });
- * };
- *
- * // generate 5 users
- * async.times(5, function(n, next) {
- * createUser(n, function(err, user) {
- * next(err, user);
- * });
- * }, function(err, users) {
- * // we should now have 5 users
- * });
- */
- var times = doLimit(timeLimit, Infinity);
- /**
- * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
- *
- * @name timesSeries
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.times]{@link module:ControlFlow.times}
- * @category Control Flow
- * @param {number} n - The number of times to run the function.
- * @param {AsyncFunction} iteratee - The async function to call `n` times.
- * Invoked with the iteration index and a callback: (n, next).
- * @param {Function} callback - see {@link module:Collections.map}.
- */
- var timesSeries = doLimit(timeLimit, 1);
- /**
- * A relative of `reduce`. Takes an Object or Array, and iterates over each
- * element in series, each step potentially mutating an `accumulator` value.
- * The type of the accumulator defaults to the type of collection passed in.
- *
- * @name transform
- * @static
- * @memberOf module:Collections
- * @method
- * @category Collection
- * @param {Array|Iterable|Object} coll - A collection to iterate over.
- * @param {*} [accumulator] - The initial state of the transform. If omitted,
- * it will default to an empty Object or Array, depending on the type of `coll`
- * @param {AsyncFunction} iteratee - A function applied to each item in the
- * collection that potentially modifies the accumulator.
- * Invoked with (accumulator, item, key, callback).
- * @param {Function} [callback] - A callback which is called after all the
- * `iteratee` functions have finished. Result is the transformed accumulator.
- * Invoked with (err, result).
- * @example
- *
- * async.transform([1,2,3], function(acc, item, index, callback) {
- * // pointless async:
- * process.nextTick(function() {
- * acc.push(item * 2)
- * callback(null)
- * });
- * }, function(err, result) {
- * // result is now equal to [2, 4, 6]
- * });
- *
- * @example
- *
- * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
- * setImmediate(function () {
- * obj[key] = val * 2;
- * callback();
- * })
- * }, function (err, result) {
- * // result is equal to {a: 2, b: 4, c: 6}
- * })
- */
- function transform (coll, accumulator, iteratee, callback) {
- if (arguments.length <= 3) {
- callback = iteratee;
- iteratee = accumulator;
- accumulator = isArray(coll) ? [] : {};
- }
- callback = once(callback || noop);
- var _iteratee = wrapAsync(iteratee);
- eachOf(coll, function(v, k, cb) {
- _iteratee(accumulator, v, k, cb);
- }, function(err) {
- callback(err, accumulator);
- });
- }
- /**
- * It runs each task in series but stops whenever any of the functions were
- * successful. If one of the tasks were successful, the `callback` will be
- * passed the result of the successful task. If all tasks fail, the callback
- * will be passed the error and result (if any) of the final attempt.
- *
- * @name tryEach
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array|Iterable|Object} tasks - A collection containing functions to
- * run, each function is passed a `callback(err, result)` it must call on
- * completion with an error `err` (which can be `null`) and an optional `result`
- * value.
- * @param {Function} [callback] - An optional callback which is called when one
- * of the tasks has succeeded, or all have failed. It receives the `err` and
- * `result` arguments of the last attempt at completing the `task`. Invoked with
- * (err, results).
- * @example
- * async.tryEach([
- * function getDataFromFirstWebsite(callback) {
- * // Try getting the data from the first website
- * callback(err, data);
- * },
- * function getDataFromSecondWebsite(callback) {
- * // First website failed,
- * // Try getting the data from the backup website
- * callback(err, data);
- * }
- * ],
- * // optional callback
- * function(err, results) {
- * Now do something with the data.
- * });
- *
- */
- function tryEach(tasks, callback) {
- var error = null;
- var result;
- callback = callback || noop;
- eachSeries(tasks, function(task, callback) {
- wrapAsync(task)(function (err, res/*, ...args*/) {
- if (arguments.length > 2) {
- result = slice(arguments, 1);
- } else {
- result = res;
- }
- error = err;
- callback(!err);
- });
- }, function () {
- callback(error, result);
- });
- }
- /**
- * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
- * unmemoized form. Handy for testing.
- *
- * @name unmemoize
- * @static
- * @memberOf module:Utils
- * @method
- * @see [async.memoize]{@link module:Utils.memoize}
- * @category Util
- * @param {AsyncFunction} fn - the memoized function
- * @returns {AsyncFunction} a function that calls the original unmemoized function
- */
- function unmemoize(fn) {
- return function () {
- return (fn.unmemoized || fn).apply(null, arguments);
- };
- }
- /**
- * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
- * stopped, or an error occurs.
- *
- * @name whilst
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Function} test - synchronous truth test to perform before each
- * execution of `iteratee`. Invoked with ().
- * @param {AsyncFunction} iteratee - An async function which is called each time
- * `test` passes. Invoked with (callback).
- * @param {Function} [callback] - A callback which is called after the test
- * function has failed and repeated execution of `iteratee` has stopped. `callback`
- * will be passed an error and any arguments passed to the final `iteratee`'s
- * callback. Invoked with (err, [results]);
- * @returns undefined
- * @example
- *
- * var count = 0;
- * async.whilst(
- * function() { return count < 5; },
- * function(callback) {
- * count++;
- * setTimeout(function() {
- * callback(null, count);
- * }, 1000);
- * },
- * function (err, n) {
- * // 5 seconds have passed, n = 5
- * }
- * );
- */
- function whilst(test, iteratee, callback) {
- callback = onlyOnce(callback || noop);
- var _iteratee = wrapAsync(iteratee);
- if (!test()) return callback(null);
- var next = function(err/*, ...args*/) {
- if (err) return callback(err);
- if (test()) return _iteratee(next);
- var args = slice(arguments, 1);
- callback.apply(null, [null].concat(args));
- };
- _iteratee(next);
- }
- /**
- * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
- * stopped, or an error occurs. `callback` will be passed an error and any
- * arguments passed to the final `iteratee`'s callback.
- *
- * The inverse of [whilst]{@link module:ControlFlow.whilst}.
- *
- * @name until
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @see [async.whilst]{@link module:ControlFlow.whilst}
- * @category Control Flow
- * @param {Function} test - synchronous truth test to perform before each
- * execution of `iteratee`. Invoked with ().
- * @param {AsyncFunction} iteratee - An async function which is called each time
- * `test` fails. Invoked with (callback).
- * @param {Function} [callback] - A callback which is called after the test
- * function has passed and repeated execution of `iteratee` has stopped. `callback`
- * will be passed an error and any arguments passed to the final `iteratee`'s
- * callback. Invoked with (err, [results]);
- */
- function until(test, iteratee, callback) {
- whilst(function() {
- return !test.apply(this, arguments);
- }, iteratee, callback);
- }
- /**
- * Runs the `tasks` array of functions in series, each passing their results to
- * the next in the array. However, if any of the `tasks` pass an error to their
- * own callback, the next function is not executed, and the main `callback` is
- * immediately called with the error.
- *
- * @name waterfall
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
- * to run.
- * Each function should complete with any number of `result` values.
- * The `result` values will be passed as arguments, in order, to the next task.
- * @param {Function} [callback] - An optional callback to run once all the
- * functions have completed. This will be passed the results of the last task's
- * callback. Invoked with (err, [results]).
- * @returns undefined
- * @example
- *
- * async.waterfall([
- * function(callback) {
- * callback(null, 'one', 'two');
- * },
- * function(arg1, arg2, callback) {
- * // arg1 now equals 'one' and arg2 now equals 'two'
- * callback(null, 'three');
- * },
- * function(arg1, callback) {
- * // arg1 now equals 'three'
- * callback(null, 'done');
- * }
- * ], function (err, result) {
- * // result now equals 'done'
- * });
- *
- * // Or, with named functions:
- * async.waterfall([
- * myFirstFunction,
- * mySecondFunction,
- * myLastFunction,
- * ], function (err, result) {
- * // result now equals 'done'
- * });
- * function myFirstFunction(callback) {
- * callback(null, 'one', 'two');
- * }
- * function mySecondFunction(arg1, arg2, callback) {
- * // arg1 now equals 'one' and arg2 now equals 'two'
- * callback(null, 'three');
- * }
- * function myLastFunction(arg1, callback) {
- * // arg1 now equals 'three'
- * callback(null, 'done');
- * }
- */
- var waterfall = function(tasks, callback) {
- callback = once(callback || noop);
- if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
- if (!tasks.length) return callback();
- var taskIndex = 0;
- function nextTask(args) {
- var task = wrapAsync(tasks[taskIndex++]);
- args.push(onlyOnce(next));
- task.apply(null, args);
- }
- function next(err/*, ...args*/) {
- if (err || taskIndex === tasks.length) {
- return callback.apply(null, arguments);
- }
- nextTask(slice(arguments, 1));
- }
- nextTask([]);
- };
- /**
- * An "async function" in the context of Async is an asynchronous function with
- * a variable number of parameters, with the final parameter being a callback.
- * (`function (arg1, arg2, ..., callback) {}`)
- * The final callback is of the form `callback(err, results...)`, which must be
- * called once the function is completed. The callback should be called with a
- * Error as its first argument to signal that an error occurred.
- * Otherwise, if no error occurred, it should be called with `null` as the first
- * argument, and any additional `result` arguments that may apply, to signal
- * successful completion.
- * The callback must be called exactly once, ideally on a later tick of the
- * JavaScript event loop.
- *
- * This type of function is also referred to as a "Node-style async function",
- * or a "continuation passing-style function" (CPS). Most of the methods of this
- * library are themselves CPS/Node-style async functions, or functions that
- * return CPS/Node-style async functions.
- *
- * Wherever we accept a Node-style async function, we also directly accept an
- * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
- * In this case, the `async` function will not be passed a final callback
- * argument, and any thrown error will be used as the `err` argument of the
- * implicit callback, and the return value will be used as the `result` value.
- * (i.e. a `rejected` of the returned Promise becomes the `err` callback
- * argument, and a `resolved` value becomes the `result`.)
- *
- * Note, due to JavaScript limitations, we can only detect native `async`
- * functions and not transpilied implementations.
- * Your environment must have `async`/`await` support for this to work.
- * (e.g. Node > v7.6, or a recent version of a modern browser).
- * If you are using `async` functions through a transpiler (e.g. Babel), you
- * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
- * because the `async function` will be compiled to an ordinary function that
- * returns a promise.
- *
- * @typedef {Function} AsyncFunction
- * @static
- */
- /**
- * Async is a utility module which provides straight-forward, powerful functions
- * for working with asynchronous JavaScript. Although originally designed for
- * use with [Node.js](http://nodejs.org) and installable via
- * `npm install --save async`, it can also be used directly in the browser.
- * @module async
- * @see AsyncFunction
- */
- /**
- * A collection of `async` functions for manipulating collections, such as
- * arrays and objects.
- * @module Collections
- */
- /**
- * A collection of `async` functions for controlling the flow through a script.
- * @module ControlFlow
- */
- /**
- * A collection of `async` utility functions.
- * @module Utils
- */
- var index = {
- apply: apply,
- applyEach: applyEach,
- applyEachSeries: applyEachSeries,
- asyncify: asyncify,
- auto: auto,
- autoInject: autoInject,
- cargo: cargo,
- compose: compose,
- concat: concat,
- concatLimit: concatLimit,
- concatSeries: concatSeries,
- constant: constant,
- detect: detect,
- detectLimit: detectLimit,
- detectSeries: detectSeries,
- dir: dir,
- doDuring: doDuring,
- doUntil: doUntil,
- doWhilst: doWhilst,
- during: during,
- each: eachLimit,
- eachLimit: eachLimit$1,
- eachOf: eachOf,
- eachOfLimit: eachOfLimit,
- eachOfSeries: eachOfSeries,
- eachSeries: eachSeries,
- ensureAsync: ensureAsync,
- every: every,
- everyLimit: everyLimit,
- everySeries: everySeries,
- filter: filter,
- filterLimit: filterLimit,
- filterSeries: filterSeries,
- forever: forever,
- groupBy: groupBy,
- groupByLimit: groupByLimit,
- groupBySeries: groupBySeries,
- log: log,
- map: map,
- mapLimit: mapLimit,
- mapSeries: mapSeries,
- mapValues: mapValues,
- mapValuesLimit: mapValuesLimit,
- mapValuesSeries: mapValuesSeries,
- memoize: memoize,
- nextTick: nextTick,
- parallel: parallelLimit,
- parallelLimit: parallelLimit$1,
- priorityQueue: priorityQueue,
- queue: queue$1,
- race: race,
- reduce: reduce,
- reduceRight: reduceRight,
- reflect: reflect,
- reflectAll: reflectAll,
- reject: reject,
- rejectLimit: rejectLimit,
- rejectSeries: rejectSeries,
- retry: retry,
- retryable: retryable,
- seq: seq,
- series: series,
- setImmediate: setImmediate$1,
- some: some,
- someLimit: someLimit,
- someSeries: someSeries,
- sortBy: sortBy,
- timeout: timeout,
- times: times,
- timesLimit: timeLimit,
- timesSeries: timesSeries,
- transform: transform,
- tryEach: tryEach,
- unmemoize: unmemoize,
- until: until,
- waterfall: waterfall,
- whilst: whilst,
- // aliases
- all: every,
- allLimit: everyLimit,
- allSeries: everySeries,
- any: some,
- anyLimit: someLimit,
- anySeries: someSeries,
- find: detect,
- findLimit: detectLimit,
- findSeries: detectSeries,
- forEach: eachLimit,
- forEachSeries: eachSeries,
- forEachLimit: eachLimit$1,
- forEachOf: eachOf,
- forEachOfSeries: eachOfSeries,
- forEachOfLimit: eachOfLimit,
- inject: reduce,
- foldl: reduce,
- foldr: reduceRight,
- select: filter,
- selectLimit: filterLimit,
- selectSeries: filterSeries,
- wrapSync: asyncify
- };
- exports['default'] = index;
- exports.apply = apply;
- exports.applyEach = applyEach;
- exports.applyEachSeries = applyEachSeries;
- exports.asyncify = asyncify;
- exports.auto = auto;
- exports.autoInject = autoInject;
- exports.cargo = cargo;
- exports.compose = compose;
- exports.concat = concat;
- exports.concatLimit = concatLimit;
- exports.concatSeries = concatSeries;
- exports.constant = constant;
- exports.detect = detect;
- exports.detectLimit = detectLimit;
- exports.detectSeries = detectSeries;
- exports.dir = dir;
- exports.doDuring = doDuring;
- exports.doUntil = doUntil;
- exports.doWhilst = doWhilst;
- exports.during = during;
- exports.each = eachLimit;
- exports.eachLimit = eachLimit$1;
- exports.eachOf = eachOf;
- exports.eachOfLimit = eachOfLimit;
- exports.eachOfSeries = eachOfSeries;
- exports.eachSeries = eachSeries;
- exports.ensureAsync = ensureAsync;
- exports.every = every;
- exports.everyLimit = everyLimit;
- exports.everySeries = everySeries;
- exports.filter = filter;
- exports.filterLimit = filterLimit;
- exports.filterSeries = filterSeries;
- exports.forever = forever;
- exports.groupBy = groupBy;
- exports.groupByLimit = groupByLimit;
- exports.groupBySeries = groupBySeries;
- exports.log = log;
- exports.map = map;
- exports.mapLimit = mapLimit;
- exports.mapSeries = mapSeries;
- exports.mapValues = mapValues;
- exports.mapValuesLimit = mapValuesLimit;
- exports.mapValuesSeries = mapValuesSeries;
- exports.memoize = memoize;
- exports.nextTick = nextTick;
- exports.parallel = parallelLimit;
- exports.parallelLimit = parallelLimit$1;
- exports.priorityQueue = priorityQueue;
- exports.queue = queue$1;
- exports.race = race;
- exports.reduce = reduce;
- exports.reduceRight = reduceRight;
- exports.reflect = reflect;
- exports.reflectAll = reflectAll;
- exports.reject = reject;
- exports.rejectLimit = rejectLimit;
- exports.rejectSeries = rejectSeries;
- exports.retry = retry;
- exports.retryable = retryable;
- exports.seq = seq;
- exports.series = series;
- exports.setImmediate = setImmediate$1;
- exports.some = some;
- exports.someLimit = someLimit;
- exports.someSeries = someSeries;
- exports.sortBy = sortBy;
- exports.timeout = timeout;
- exports.times = times;
- exports.timesLimit = timeLimit;
- exports.timesSeries = timesSeries;
- exports.transform = transform;
- exports.tryEach = tryEach;
- exports.unmemoize = unmemoize;
- exports.until = until;
- exports.waterfall = waterfall;
- exports.whilst = whilst;
- exports.all = every;
- exports.allLimit = everyLimit;
- exports.allSeries = everySeries;
- exports.any = some;
- exports.anyLimit = someLimit;
- exports.anySeries = someSeries;
- exports.find = detect;
- exports.findLimit = detectLimit;
- exports.findSeries = detectSeries;
- exports.forEach = eachLimit;
- exports.forEachSeries = eachSeries;
- exports.forEachLimit = eachLimit$1;
- exports.forEachOf = eachOf;
- exports.forEachOfSeries = eachOfSeries;
- exports.forEachOfLimit = eachOfLimit;
- exports.inject = reduce;
- exports.foldl = reduce;
- exports.foldr = reduceRight;
- exports.select = filter;
- exports.selectLimit = filterLimit;
- exports.selectSeries = filterSeries;
- exports.wrapSync = asyncify;
- Object.defineProperty(exports, '__esModule', { value: true });
- })));
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
- },{"_process":202,"timers":206}],20:[function(require,module,exports){
- 'use strict'
- var GeoJSONBounds = require('geojson-bounds')
- /* global L:false */
- function BoundingBox (bounds) {
- var k
- if (bounds === null || typeof bounds === 'undefined') {
- this.minlat = -90
- this.minlon = -180
- this.maxlat = +90
- this.maxlon = +180
- return
- }
- // Leaflet.latLngBounds detected!
- if (typeof bounds.getSouthWest === 'function') {
- var sw = bounds.getSouthWest()
- var ne = bounds.getNorthEast()
- bounds = {
- minlat: sw.lat,
- minlon: sw.lng,
- maxlat: ne.lat,
- maxlon: ne.lng
- }
- }
- // GeoJSON detected
- if (bounds.type === 'Feature') {
- var b = GeoJSONBounds.extent(bounds)
- bounds = {
- minlat: b[1],
- minlon: b[0],
- maxlat: b[3],
- maxlon: b[2]
- }
- }
- if ('bounds' in bounds) {
- bounds = bounds.bounds
- }
- if (bounds.lat) {
- this.minlat = bounds.lat
- this.maxlat = bounds.lat
- }
- if (bounds.lon) {
- this.minlon = bounds.lon
- this.maxlon = bounds.lon
- }
- if (Array.isArray(bounds)) {
- this.minlat = bounds[0]
- this.maxlat = bounds[0]
- this.minlon = bounds[1]
- this.maxlon = bounds[1]
- }
- // e.g. L.latLng object
- if (bounds.lng) {
- this.minlon = bounds.lng
- this.maxlon = bounds.lng
- }
- var props = ['minlon', 'minlat', 'maxlon', 'maxlat']
- for (var i = 0; i < props.length; i++) {
- k = props[i]
- if (k in bounds) {
- this[k] = bounds[k]
- }
- }
- }
- BoundingBox.prototype.intersects = function (other) {
- other = new BoundingBox(other)
- if (other.maxlat < this.minlat) {
- return false
- }
- if (other.minlat > this.maxlat) {
- return false
- }
- if (other.maxlon < this.minlon) {
- return false
- }
- if (other.minlon > this.maxlon) {
- return false
- }
- return true
- }
- BoundingBox.prototype.toTile = function () {
- return new BoundingBox({
- minlat: Math.floor(this.minlat * 10) / 10,
- minlon: Math.floor(this.minlon * 10) / 10,
- maxlat: Math.ceil(this.maxlat * 10) / 10,
- maxlon: Math.ceil(this.maxlon * 10) / 10
- })
- }
- BoundingBox.prototype.toLonLatString = function () {
- return this.minlon + ',' +
- this.minlat + ',' +
- this.maxlon + ',' +
- this.maxlat
- }
- BoundingBox.prototype.toBBoxString = BoundingBox.prototype.toLonLatString
- BoundingBox.prototype.toLatLonString = function () {
- return this.minlat + ',' +
- this.minlon + ',' +
- this.maxlat + ',' +
- this.maxlon
- }
- BoundingBox.prototype.diagonalLength = function () {
- var dlat = this.maxlat - this.minlat
- var dlon = this.maxlon - this.minlon
- return Math.sqrt(dlat * dlat + dlon * dlon)
- }
- BoundingBox.prototype.getCenter = function () {
- var dlat = this.maxlat - this.minlat
- var dlon = this.maxlon - this.minlon
- return {
- lat: this.minlat + dlat / 2,
- lon: this.minlon + dlon / 2
- }
- }
- BoundingBox.prototype.getNorth = function () {
- return this.maxlat
- }
- BoundingBox.prototype.getSouth = function () {
- return this.minlat
- }
- BoundingBox.prototype.getEast = function () {
- return this.maxlon
- }
- BoundingBox.prototype.getWest = function () {
- return this.minlon
- }
- BoundingBox.prototype.extend = function (other) {
- other = new BoundingBox(other)
- if (other.minlon < this.minlon) {
- this.minlon = other.minlon
- }
- if (other.minlat < this.minlat) {
- this.minlat = other.minlat
- }
- if (other.maxlon > this.maxlon) {
- this.maxlon = other.maxlon
- }
- if (other.maxlat > this.maxlat) {
- this.maxlat = other.maxlat
- }
- }
- BoundingBox.prototype.toGeoJSON = function () {
- return {
- type: 'Feature',
- properties: {},
- geometry: {
- 'type': 'Polygon',
- 'coordinates': [[
- [ this.minlon, this.minlat ],
- [ this.maxlon, this.minlat ],
- [ this.maxlon, this.maxlat ],
- [ this.minlon, this.maxlat ],
- [ this.minlon, this.minlat ]
- ]]
- }
- }
- }
- BoundingBox.prototype.toLeaflet = function () {
- return L.latLngBounds(
- L.latLng(this.minlat, this.minlon),
- L.latLng(this.maxlat, this.maxlon)
- )
- }
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = BoundingBox
- }
- if (typeof window !== 'undefined') {
- window.BoundingBox = BoundingBox
- }
- },{"geojson-bounds":43}],21:[function(require,module,exports){
- },{}],22:[function(require,module,exports){
- 'use strict';
- // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
- var styleElementsInsertedAtTop = [];
- var insertStyleElement = function(styleElement, options) {
- var head = document.head || document.getElementsByTagName('head')[0];
- var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
- options = options || {};
- options.insertAt = options.insertAt || 'bottom';
- if (options.insertAt === 'top') {
- if (!lastStyleElementInsertedAtTop) {
- head.insertBefore(styleElement, head.firstChild);
- } else if (lastStyleElementInsertedAtTop.nextSibling) {
- head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
- } else {
- head.appendChild(styleElement);
- }
- styleElementsInsertedAtTop.push(styleElement);
- } else if (options.insertAt === 'bottom') {
- head.appendChild(styleElement);
- } else {
- throw new Error('Invalid value for parameter \'insertAt\'. Must be \'top\' or \'bottom\'.');
- }
- };
- module.exports = {
- // Create a <link> tag with optional data attributes
- createLink: function(href, attributes) {
- var head = document.head || document.getElementsByTagName('head')[0];
- var link = document.createElement('link');
- link.href = href;
- link.rel = 'stylesheet';
- for (var key in attributes) {
- if ( ! attributes.hasOwnProperty(key)) {
- continue;
- }
- var value = attributes[key];
- link.setAttribute('data-' + key, value);
- }
- head.appendChild(link);
- },
- // Create a <style> tag with optional data attributes
- createStyle: function(cssText, attributes, extraOptions) {
- extraOptions = extraOptions || {};
- var style = document.createElement('style');
- style.type = 'text/css';
- for (var key in attributes) {
- if ( ! attributes.hasOwnProperty(key)) {
- continue;
- }
- var value = attributes[key];
- style.setAttribute('data-' + key, value);
- }
- if (style.sheet) { // for jsdom and IE9+
- style.innerHTML = cssText;
- style.sheet.cssText = cssText;
- insertStyleElement(style, { insertAt: extraOptions.insertAt });
- } else if (style.styleSheet) { // for IE8 and below
- insertStyleElement(style, { insertAt: extraOptions.insertAt });
- style.styleSheet.cssText = cssText;
- } else { // for Chrome, Firefox, and Safari
- style.appendChild(document.createTextNode(cssText));
- insertStyleElement(style, { insertAt: extraOptions.insertAt });
- }
- }
- };
- },{}],23:[function(require,module,exports){
- arguments[4][21][0].apply(exports,arguments)
- },{"dup":21}],24:[function(require,module,exports){
- /*
- bzip2.js - a small bzip2 decompression implementation
- Copyright 2011 by antimatter15 (antimatter15@gmail.com)
- Based on micro-bunzip by Rob Landley (rob@landley.net).
- Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
- which also acknowledges contributions by Mike Burrows, David Wheeler,
- Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
- Robert Sedgewick, and Jon L. Bentley.
- I hereby release this code under the GNU Library General Public License
- (LGPL) version 2, available at http://www.gnu.org/copyleft/lgpl.html
- */
- var bzip2 = {};
- bzip2.array = function (bytes) {
- var bit = 0,
- byte = 0;
- var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
- return function (n) {
- var result = 0;
- while (n > 0) {
- var left = 8 - bit;
- if (n >= left) {
- result <<= left;
- result |= (BITMASK[left] & bytes[byte++]);
- bit = 0;
- n -= left;
- } else {
- result <<= n;
- result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
- bit += n;
- n = 0;
- }
- }
- return result
- }
- }
- bzip2.simple = function (bits) {
- var size = bzip2.header(bits);
- var all, chunk, chunks = [];
- var index = 0;
- do {
- //all += chunk;
- chunk = bzip2.decompress(bits, size);
- //all.set(chunk, index);
- if (chunk != -1) {
- chunks.push(chunk);
- index += chunk.byteLength;
- }
- } while (chunk != -1);
- all = new Uint8Array(index);
- index = 0;
- for (var i = 0; i < chunks.length; ++i) {
- chunk = chunks[i];
- all.set(chunk, index);
- index += chunk.byteLength;
- }
- return all;
- }
- bzip2.header = function (bits) {
- if (bits(8 * 3) != 4348520)
- throw "No magic number found";
- var i = bits(8) - 48;
- if (i < 1 || i > 9)
- throw "Not a BZIP archive";
- return i;
- };
- //takes a function for reading the block data (starting with 0x314159265359)
- //a block size (0-9) (optional, defaults to 9)
- //a length at which to stop decompressing and return the output
- bzip2.decompress = function (bits, size, len) {
- var MAX_HUFCODE_BITS = 20;
- var MAX_SYMBOLS = 258;
- var SYMBOL_RUNA = 0;
- var SYMBOL_RUNB = 1;
- var GROUP_SIZE = 50;
- var bufsize = 100000 * 9;
- for (var h = '', i = 0; i < 6; i++)
- h += bits(8).toString(16);
- if (h == "177245385090")
- return -1; //last block
- if (h != "314159265359")
- throw "eek not valid bzip data";
- bits(32); //ignore CRC codes
- if (bits(1))
- throw "unsupported obsolete version";
- var origPtr = bits(24);
- if (origPtr > bufsize)
- throw "Initial position larger than buffer size";
- var t = bits(16);
- var symToByte = new Uint8Array(256),
- symTotal = 0;
- for (i = 0; i < 16; i++) {
- if (t & (1 << (15 - i))) {
- var k = bits(16);
- for (j = 0; j < 16; j++) {
- if (k & (1 << (15 - j))) {
- symToByte[symTotal++] = (16 * i) + j;
- }
- }
- }
- }
- var groupCount = bits(3);
- if (groupCount < 2 || groupCount > 6)
- throw "another error";
- var nSelectors = bits(15);
- if (nSelectors == 0)
- throw "meh";
- var mtfSymbol = []; //TODO: possibly replace JS array with typed arrays
- for (var i = 0; i < groupCount; i++)
- mtfSymbol[i] = i;
- var selectors = new Uint8Array(32768);
- for (var i = 0; i < nSelectors; i++) {
- for (var j = 0; bits(1); j++)
- if (j >= groupCount)
- throw "whoops another error";
- var uc = mtfSymbol[j];
- mtfSymbol.splice(j, 1); //this is a probably inefficient MTF transform
- mtfSymbol.splice(0, 0, uc);
- selectors[i] = uc;
- }
- var symCount = symTotal + 2;
- var groups = [];
- for (var j = 0; j < groupCount; j++) {
- var length = new Uint8Array(MAX_SYMBOLS),
- temp = new Uint8Array(MAX_HUFCODE_BITS + 1);
- t = bits(5); //lengths
- for (var i = 0; i < symCount; i++) {
- while (true) {
- if (t < 1 || t > MAX_HUFCODE_BITS)
- throw "I gave up a while ago on writing error messages";
- if (!bits(1))
- break;
- if (!bits(1))
- t++;
- else
- t--;
- }
- length[i] = t;
- }
- var minLen, maxLen;
- minLen = maxLen = length[0];
- for (var i = 1; i < symCount; i++) {
- if (length[i] > maxLen)
- maxLen = length[i];
- else if (length[i] < minLen)
- minLen = length[i];
- }
- var hufGroup;
- hufGroup = groups[j] = {};
- hufGroup.permute = new Uint32Array(MAX_SYMBOLS);
- hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 1);
- hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
- hufGroup.minLen = minLen;
- hufGroup.maxLen = maxLen;
- var base = hufGroup.base.subarray(1);
- var limit = hufGroup.limit.subarray(1);
- var pp = 0;
- for (var i = minLen; i <= maxLen; i++)
- for (var t = 0; t < symCount; t++)
- if (length[t] == i)
- hufGroup.permute[pp++] = t;
- for (i = minLen; i <= maxLen; i++)
- temp[i] = limit[i] = 0;
- for (i = 0; i < symCount; i++)
- temp[length[i]]++;
- pp = t = 0;
- for (i = minLen; i < maxLen; i++) {
- pp += temp[i];
- limit[i] = pp - 1;
- pp <<= 1;
- base[i + 1] = pp - (t += temp[i]);
- }
- limit[maxLen] = pp + temp[maxLen] - 1;
- base[minLen] = 0;
- }
- var byteCount = new Uint32Array(256);
- for (var i = 0; i < 256; i++)
- mtfSymbol[i] = i;
- var runPos, count, symCount, selector;
- runPos = count = symCount = selector = 0;
- var buf = new Uint32Array(bufsize);
- while (true) {
- if (!(symCount--)) {
- symCount = GROUP_SIZE - 1;
- if (selector >= nSelectors)
- throw "meow i'm a kitty, that's an error";
- hufGroup = groups[selectors[selector++]];
- base = hufGroup.base.subarray(1);
- limit = hufGroup.limit.subarray(1);
- }
- i = hufGroup.minLen;
- j = bits(i);
- while (true) {
- if (i > hufGroup.maxLen)
- throw "rawr i'm a dinosaur";
- if (j <= limit[i])
- break;
- i++;
- j = (j << 1) | bits(1);
- }
- j -= base[i];
- if (j < 0 || j >= MAX_SYMBOLS)
- throw "moo i'm a cow";
- var nextSym = hufGroup.permute[j];
- if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {
- if (!runPos) {
- runPos = 1;
- t = 0;
- }
- if (nextSym == SYMBOL_RUNA)
- t += runPos;
- else
- t += 2 * runPos;
- runPos <<= 1;
- continue;
- }
- if (runPos) {
- runPos = 0;
- if (count + t >= bufsize)
- throw "Boom.";
- uc = symToByte[mtfSymbol[0]];
- byteCount[uc] += t;
- while (t--)
- buf[count++] = uc;
- }
- if (nextSym > symTotal)
- break;
- if (count >= bufsize)
- throw "I can't think of anything. Error";
- i = nextSym - 1;
- uc = mtfSymbol[i];
- mtfSymbol.splice(i, 1);
- mtfSymbol.splice(0, 0, uc);
- uc = symToByte[uc];
- byteCount[uc]++;
- buf[count++] = uc;
- }
- if (origPtr < 0 || origPtr >= count)
- throw "I'm a monkey and I'm throwing something at someone, namely you";
- var j = 0;
- for (var i = 0; i < 256; i++) {
- k = j + byteCount[i];
- byteCount[i] = j;
- j = k;
- }
- for (var i = 0; i < count; i++) {
- uc = buf[i] & 0xff;
- buf[byteCount[uc]] |= (i << 8);
- byteCount[uc]++;
- }
- var pos = 0,
- current = 0,
- run = 0;
- if (count) {
- pos = buf[origPtr];
- current = (pos & 0xff);
- pos >>= 8;
- run = -1;
- }
- count = count;
- var output = new Uint8Array(bufsize);
- var copies, previous, outbyte;
- var index = 0;
- if (!len)
- len = Infinity;
- while (count) {
- count--;
- previous = current;
- pos = buf[pos];
- current = pos & 0xff;
- pos >>= 8;
- if (run++ == 3) {
- copies = current;
- outbyte = previous;
- current = -1;
- } else {
- copies = 1;
- outbyte = current;
- }
- while (copies--) {
- //output += (String.fromCharCode(outbyte));
- output[index++] = outbyte;
- //index++;
- if (!--len)
- return output;
- }
- if (current != previous)
- run = 0;
- }
- //return output;
- //return output.subarray(0,index-1);
- return output.subarray(0, index);
- }
- module.exports = bzip2;
- },{}],25:[function(require,module,exports){
- 'use strict';
- var assign = require('es5-ext/object/assign')
- , normalizeOpts = require('es5-ext/object/normalize-options')
- , isCallable = require('es5-ext/object/is-callable')
- , contains = require('es5-ext/string/#/contains')
- , d;
- d = module.exports = function (dscr, value/*, options*/) {
- var c, e, w, options, desc;
- if ((arguments.length < 2) || (typeof dscr !== 'string')) {
- options = value;
- value = dscr;
- dscr = null;
- } else {
- options = arguments[2];
- }
- if (dscr == null) {
- c = w = true;
- e = false;
- } else {
- c = contains.call(dscr, 'c');
- e = contains.call(dscr, 'e');
- w = contains.call(dscr, 'w');
- }
- desc = { value: value, configurable: c, enumerable: e, writable: w };
- return !options ? desc : assign(normalizeOpts(options), desc);
- };
- d.gs = function (dscr, get, set/*, options*/) {
- var c, e, options, desc;
- if (typeof dscr !== 'string') {
- options = set;
- set = get;
- get = dscr;
- dscr = null;
- } else {
- options = arguments[3];
- }
- if (get == null) {
- get = undefined;
- } else if (!isCallable(get)) {
- options = get;
- get = set = undefined;
- } else if (set == null) {
- set = undefined;
- } else if (!isCallable(set)) {
- options = set;
- set = undefined;
- }
- if (dscr == null) {
- c = true;
- e = false;
- } else {
- c = contains.call(dscr, 'c');
- e = contains.call(dscr, 'e');
- }
- desc = { get: get, set: set, configurable: c, enumerable: e };
- return !options ? desc : assign(normalizeOpts(options), desc);
- };
- },{"es5-ext/object/assign":27,"es5-ext/object/is-callable":30,"es5-ext/object/normalize-options":35,"es5-ext/string/#/contains":38}],26:[function(require,module,exports){
- "use strict";
- // eslint-disable-next-line no-empty-function
- module.exports = function () {};
- },{}],27:[function(require,module,exports){
- "use strict";
- module.exports = require("./is-implemented")()
- ? Object.assign
- : require("./shim");
- },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){
- "use strict";
- module.exports = function () {
- var assign = Object.assign, obj;
- if (typeof assign !== "function") return false;
- obj = { foo: "raz" };
- assign(obj, { bar: "dwa" }, { trzy: "trzy" });
- return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
- };
- },{}],29:[function(require,module,exports){
- "use strict";
- var keys = require("../keys")
- , value = require("../valid-value")
- , max = Math.max;
- module.exports = function (dest, src /*, …srcn*/) {
- var error, i, length = max(arguments.length, 2), assign;
- dest = Object(value(dest));
- assign = function (key) {
- try {
- dest[key] = src[key];
- } catch (e) {
- if (!error) error = e;
- }
- };
- for (i = 1; i < length; ++i) {
- src = arguments[i];
- keys(src).forEach(assign);
- }
- if (error !== undefined) throw error;
- return dest;
- };
- },{"../keys":32,"../valid-value":37}],30:[function(require,module,exports){
- // Deprecated
- "use strict";
- module.exports = function (obj) {
- return typeof obj === "function";
- };
- },{}],31:[function(require,module,exports){
- "use strict";
- var _undefined = require("../function/noop")(); // Support ES3 engines
- module.exports = function (val) {
- return (val !== _undefined) && (val !== null);
- };
- },{"../function/noop":26}],32:[function(require,module,exports){
- "use strict";
- module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
- },{"./is-implemented":33,"./shim":34}],33:[function(require,module,exports){
- "use strict";
- module.exports = function () {
- try {
- Object.keys("primitive");
- return true;
- } catch (e) {
- return false;
- }
- };
- },{}],34:[function(require,module,exports){
- "use strict";
- var isValue = require("../is-value");
- var keys = Object.keys;
- module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
- },{"../is-value":31}],35:[function(require,module,exports){
- "use strict";
- var isValue = require("./is-value");
- var forEach = Array.prototype.forEach, create = Object.create;
- var process = function (src, obj) {
- var key;
- for (key in src) obj[key] = src[key];
- };
- // eslint-disable-next-line no-unused-vars
- module.exports = function (opts1 /*, …options*/) {
- var result = create(null);
- forEach.call(arguments, function (options) {
- if (!isValue(options)) return;
- process(Object(options), result);
- });
- return result;
- };
- },{"./is-value":31}],36:[function(require,module,exports){
- "use strict";
- module.exports = function (fn) {
- if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
- return fn;
- };
- },{}],37:[function(require,module,exports){
- "use strict";
- var isValue = require("./is-value");
- module.exports = function (value) {
- if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
- return value;
- };
- },{"./is-value":31}],38:[function(require,module,exports){
- "use strict";
- module.exports = require("./is-implemented")()
- ? String.prototype.contains
- : require("./shim");
- },{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){
- "use strict";
- var str = "razdwatrzy";
- module.exports = function () {
- if (typeof str.contains !== "function") return false;
- return (str.contains("dwa") === true) && (str.contains("foo") === false);
- };
- },{}],40:[function(require,module,exports){
- "use strict";
- var indexOf = String.prototype.indexOf;
- module.exports = function (searchString/*, position*/) {
- return indexOf.call(this, searchString, arguments[1]) > -1;
- };
- },{}],41:[function(require,module,exports){
- 'use strict';
- var d = require('d')
- , callable = require('es5-ext/object/valid-callable')
- , apply = Function.prototype.apply, call = Function.prototype.call
- , create = Object.create, defineProperty = Object.defineProperty
- , defineProperties = Object.defineProperties
- , hasOwnProperty = Object.prototype.hasOwnProperty
- , descriptor = { configurable: true, enumerable: false, writable: true }
- , on, once, off, emit, methods, descriptors, base;
- on = function (type, listener) {
- var data;
- callable(listener);
- if (!hasOwnProperty.call(this, '__ee__')) {
- data = descriptor.value = create(null);
- defineProperty(this, '__ee__', descriptor);
- descriptor.value = null;
- } else {
- data = this.__ee__;
- }
- if (!data[type]) data[type] = listener;
- else if (typeof data[type] === 'object') data[type].push(listener);
- else data[type] = [data[type], listener];
- return this;
- };
- once = function (type, listener) {
- var once, self;
- callable(listener);
- self = this;
- on.call(this, type, once = function () {
- off.call(self, type, once);
- apply.call(listener, this, arguments);
- });
- once.__eeOnceListener__ = listener;
- return this;
- };
- off = function (type, listener) {
- var data, listeners, candidate, i;
- callable(listener);
- if (!hasOwnProperty.call(this, '__ee__')) return this;
- data = this.__ee__;
- if (!data[type]) return this;
- listeners = data[type];
- if (typeof listeners === 'object') {
- for (i = 0; (candidate = listeners[i]); ++i) {
- if ((candidate === listener) ||
- (candidate.__eeOnceListener__ === listener)) {
- if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
- else listeners.splice(i, 1);
- }
- }
- } else {
- if ((listeners === listener) ||
- (listeners.__eeOnceListener__ === listener)) {
- delete data[type];
- }
- }
- return this;
- };
- emit = function (type) {
- var i, l, listener, listeners, args;
- if (!hasOwnProperty.call(this, '__ee__')) return;
- listeners = this.__ee__[type];
- if (!listeners) return;
- if (typeof listeners === 'object') {
- l = arguments.length;
- args = new Array(l - 1);
- for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
- listeners = listeners.slice();
- for (i = 0; (listener = listeners[i]); ++i) {
- apply.call(listener, this, args);
- }
- } else {
- switch (arguments.length) {
- case 1:
- call.call(listeners, this);
- break;
- case 2:
- call.call(listeners, this, arguments[1]);
- break;
- case 3:
- call.call(listeners, this, arguments[1], arguments[2]);
- break;
- default:
- l = arguments.length;
- args = new Array(l - 1);
- for (i = 1; i < l; ++i) {
- args[i - 1] = arguments[i];
- }
- apply.call(listeners, this, args);
- }
- }
- };
- methods = {
- on: on,
- once: once,
- off: off,
- emit: emit
- };
- descriptors = {
- on: d(on),
- once: d(once),
- off: d(off),
- emit: d(emit)
- };
- base = defineProperties({}, descriptors);
- module.exports = exports = function (o) {
- return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
- };
- exports.methods = methods;
- },{"d":25,"es5-ext/object/valid-callable":36}],42:[function(require,module,exports){
- var wgs84 = require('wgs84');
- module.exports.geometry = geometry;
- module.exports.ring = ringArea;
- function geometry(_) {
- if (_.type === 'Polygon') return polygonArea(_.coordinates);
- else if (_.type === 'MultiPolygon') {
- var area = 0;
- for (var i = 0; i < _.coordinates.length; i++) {
- area += polygonArea(_.coordinates[i]);
- }
- return area;
- } else {
- return null;
- }
- }
- function polygonArea(coords) {
- var area = 0;
- if (coords && coords.length > 0) {
- area += Math.abs(ringArea(coords[0]));
- for (var i = 1; i < coords.length; i++) {
- area -= Math.abs(ringArea(coords[i]));
- }
- }
- return area;
- }
- /**
- * Calculate the approximate area of the polygon were it projected onto
- * the earth. Note that this area will be positive if ring is oriented
- * clockwise, otherwise it will be negative.
- *
- * Reference:
- * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
- * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
- * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
- *
- * Returns:
- * {float} The approximate signed geodesic area of the polygon in square
- * meters.
- */
- function ringArea(coords) {
- var area = 0;
- if (coords.length > 2) {
- var p1, p2;
- for (var i = 0; i < coords.length - 1; i++) {
- p1 = coords[i];
- p2 = coords[i + 1];
- area += rad(p2[0] - p1[0]) * (2 + Math.sin(rad(p1[1])) + Math.sin(rad(p2[1])));
- }
- area = area * wgs84.RADIUS * wgs84.RADIUS / 2;
- }
- return area;
- }
- function rad(_) {
- return _ * Math.PI / 180;
- }
- },{"wgs84":209}],43:[function(require,module,exports){
- (function() {
- /*
- Modified version of underscore.js's flatten function
- https://github.com/jashkenas/underscore/blob/master/underscore.js#L501
- */
- function flatten(input, output) {
- output = output || [];
- var idx = output.length;
- for (var i = 0; i < input.length; i++) {
- if (Array.isArray(input[i]) && Array.isArray(input[i][0])) {
- flatten(input[i], output);
- idx = output.length;
- } else {
- output[idx++] = input[i];
- }
- }
- return (Array.isArray(output[0])) ? output : [output];
- };
- function maxLat(coords) {
- return Math.max.apply(null, coords.map(function(d) { return d[1]; }));
- }
- function maxLng(coords) {
- return Math.max.apply(null, coords.map(function(d) { return d[0]; }));
- }
- function minLat(coords) {
- return Math.min.apply(null, coords.map(function(d) { return d[1]; }));
- }
- function minLng(coords) {
- return Math.min.apply(null, coords.map(function(d) { return d[0]; }));
- }
- function fetchEnvelope(coords) {
- var mmc = {
- "minLng": minLng(coords),
- "minLat": minLat(coords),
- "maxLng": maxLng(coords),
- "maxLat": maxLat(coords)
- }
- return {
- "type": "Feature",
- "properties": {},
- "geometry": {
- "type": "Polygon",
- "coordinates": [[
- [mmc.minLng, mmc.minLat],
- [mmc.minLng, mmc.maxLat],
- [mmc.maxLng, mmc.maxLat],
- [mmc.maxLng, mmc.minLat],
- [mmc.minLng, mmc.minLat]
- ]]
- }
- }
- }
- function fetchExtent(coords) {
- return [
- minLng(coords),
- minLat(coords),
- maxLng(coords),
- maxLat(coords)
- ]
- }
- // Adapted from http://stackoverflow.com/questions/2792443/finding-the-centroid-of-a-polygon
- function fetchCentroid(vertices) {
- var centroid = {
- x: 0,
- y: 0
- }
-
- var signedArea = 0;
- var x0 = 0;
- var y0 = 0;
- var x1 = 0;
- var y1 = 0;
- var a = 0;
- for (var i = 0; i < vertices.length - 1; i++) {
- x0 = vertices[i][0];
- y0 = vertices[i][1];
- x1 = vertices[i + 1][0];
- y1 = vertices[i + 1][1];
- a = (x0 * y1) - (x1 * y0);
- signedArea += a;
- centroid.x += (x0 + x1) * a;
- centroid.y += (y0 + y1) * a;
- }
- x0 = vertices[vertices.length - 1][0];
- y0 = vertices[vertices.length - 1][1];
- x1 = vertices[0][0];
- y1 = vertices[0][1];
- a = (x0 * y1) - (x1 * y0);
- signedArea += a;
- centroid.x += (x0 + x1) * a;
- centroid.y += (y0 + y1) * a;
- signedArea = signedArea * 0.5;
- centroid.x = centroid.x / (6.0*signedArea);
- centroid.y = centroid.y / (6.0*signedArea);
- return [centroid.x, centroid.y];
- }
- function feature(obj) {
- return flatten(obj.geometry.coordinates);
- }
- function featureCollection(f) {
- return flatten(f.features.map(feature));
- }
- function geometryCollection(g) {
- return flatten(g.geometries.map(process));
- }
- function process(t) {
- if (!t) {
- return [];
- }
- switch (t.type) {
- case "Feature":
- return feature(t);
- case "GeometryCollection":
- return geometryCollection(t);
- case "FeatureCollection":
- return featureCollection(t);
- case "Point":
- case "LineString":
- case "Polygon":
- case "MultiPoint":
- case "MultiPolygon":
- case "MultiLineString":
- return flatten(t.coordinates);
- default:
- return [];
- }
- }
- function envelope(t) {
- return fetchEnvelope(process(t));
- }
- function extent(t) {
- return fetchExtent(process(t));
- }
- function centroid(t) {
- return fetchCentroid(process(t));
- }
- function xMin(t) {
- return minLng(process(t));
- }
- function xMax(t) {
- return maxLng(process(t));
- }
- function yMin(t) {
- return minLat(process(t));
- }
- function yMax(t) {
- return maxLat(process(t));
- }
- module.exports = {
- "envelope": envelope,
- "extent": extent,
- "centroid": centroid,
- "xMin": xMin,
- "xMax": xMax,
- "yMin": yMin,
- "yMax": yMax
- }
- }());
- },{}],44:[function(require,module,exports){
- var rbush = require('rbush');
- var helpers = require('@turf/helpers');
- var meta = require('@turf/meta');
- var turfBBox = require('@turf/bbox').default;
- var featureEach = meta.featureEach;
- var coordEach = meta.coordEach;
- var polygon = helpers.polygon;
- var featureCollection = helpers.featureCollection;
- /**
- * GeoJSON implementation of [RBush](https://github.com/mourner/rbush#rbush) spatial index.
- *
- * @name rbush
- * @param {number} [maxEntries=9] defines the maximum number of entries in a tree node. 9 (used by default) is a
- * reasonable choice for most applications. Higher value means faster insertion and slower search, and vice versa.
- * @returns {RBush} GeoJSON RBush
- * @example
- * var geojsonRbush = require('geojson-rbush').default;
- * var tree = geojsonRbush();
- */
- function geojsonRbush(maxEntries) {
- var tree = rbush(maxEntries);
- /**
- * [insert](https://github.com/mourner/rbush#data-format)
- *
- * @param {Feature} feature insert single GeoJSON Feature
- * @returns {RBush} GeoJSON RBush
- * @example
- * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
- * tree.insert(poly)
- */
- tree.insert = function (feature) {
- if (feature.type !== 'Feature') throw new Error('invalid feature');
- feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
- return rbush.prototype.insert.call(this, feature);
- };
- /**
- * [load](https://github.com/mourner/rbush#bulk-inserting-data)
- *
- * @param {FeatureCollection|Array<Feature>} features load entire GeoJSON FeatureCollection
- * @returns {RBush} GeoJSON RBush
- * @example
- * var polys = turf.polygons([
- * [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]],
- * [[[-93, 32], [-83, 32], [-83, 39], [-93, 39], [-93, 32]]]
- * ]);
- * tree.load(polys);
- */
- tree.load = function (features) {
- var load = [];
- // Load an Array of Features
- if (Array.isArray(features)) {
- features.forEach(function (feature) {
- if (feature.type !== 'Feature') throw new Error('invalid features');
- feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
- load.push(feature);
- });
- } else {
- // Load a FeatureCollection
- featureEach(features, function (feature) {
- if (feature.type !== 'Feature') throw new Error('invalid features');
- feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
- load.push(feature);
- });
- }
- return rbush.prototype.load.call(this, load);
- };
- /**
- * [remove](https://github.com/mourner/rbush#removing-data)
- *
- * @param {Feature} feature remove single GeoJSON Feature
- * @param {Function} equals Pass a custom equals function to compare by value for removal.
- * @returns {RBush} GeoJSON RBush
- * @example
- * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
- *
- * tree.remove(poly);
- */
- tree.remove = function (feature, equals) {
- if (feature.type !== 'Feature') throw new Error('invalid feature');
- feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature);
- return rbush.prototype.remove.call(this, feature, equals);
- };
- /**
- * [clear](https://github.com/mourner/rbush#removing-data)
- *
- * @returns {RBush} GeoJSON Rbush
- * @example
- * tree.clear()
- */
- tree.clear = function () {
- return rbush.prototype.clear.call(this);
- };
- /**
- * [search](https://github.com/mourner/rbush#search)
- *
- * @param {BBox|FeatureCollection|Feature} geojson search with GeoJSON
- * @returns {FeatureCollection} all features that intersects with the given GeoJSON.
- * @example
- * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
- *
- * tree.search(poly);
- */
- tree.search = function (geojson) {
- var features = rbush.prototype.search.call(this, this.toBBox(geojson));
- return featureCollection(features);
- };
- /**
- * [collides](https://github.com/mourner/rbush#collisions)
- *
- * @param {BBox|FeatureCollection|Feature} geojson collides with GeoJSON
- * @returns {boolean} true if there are any items intersecting the given GeoJSON, otherwise false.
- * @example
- * var poly = turf.polygon([[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]]);
- *
- * tree.collides(poly);
- */
- tree.collides = function (geojson) {
- return rbush.prototype.collides.call(this, this.toBBox(geojson));
- };
- /**
- * [all](https://github.com/mourner/rbush#search)
- *
- * @returns {FeatureCollection} all the features in RBush
- * @example
- * tree.all()
- */
- tree.all = function () {
- var features = rbush.prototype.all.call(this);
- return featureCollection(features);
- };
- /**
- * [toJSON](https://github.com/mourner/rbush#export-and-import)
- *
- * @returns {any} export data as JSON object
- * @example
- * var exported = tree.toJSON()
- */
- tree.toJSON = function () {
- return rbush.prototype.toJSON.call(this);
- };
- /**
- * [fromJSON](https://github.com/mourner/rbush#export-and-import)
- *
- * @param {any} json import previously exported data
- * @returns {RBush} GeoJSON RBush
- * @example
- * var exported = {
- * "children": [
- * {
- * "type": "Feature",
- * "geometry": {
- * "type": "Point",
- * "coordinates": [110, 50]
- * },
- * "properties": {},
- * "bbox": [110, 50, 110, 50]
- * }
- * ],
- * "height": 1,
- * "leaf": true,
- * "minX": 110,
- * "minY": 50,
- * "maxX": 110,
- * "maxY": 50
- * }
- * tree.fromJSON(exported)
- */
- tree.fromJSON = function (json) {
- return rbush.prototype.fromJSON.call(this, json);
- };
- /**
- * Converts GeoJSON to {minX, minY, maxX, maxY} schema
- *
- * @private
- * @param {BBox|FeatureCollection|Feature} geojson feature(s) to retrieve BBox from
- * @returns {Object} converted to {minX, minY, maxX, maxY}
- */
- tree.toBBox = function (geojson) {
- var bbox;
- if (geojson.bbox) bbox = geojson.bbox;
- else if (Array.isArray(geojson) && geojson.length === 4) bbox = geojson;
- else if (Array.isArray(geojson) && geojson.length === 6) bbox = [geojson[0], geojson[1], geojson[3], geojson[4]];
- else if (geojson.type === 'Feature') bbox = turfBBox(geojson);
- else if (geojson.type === 'FeatureCollection') bbox = turfBBox(geojson);
- else throw new Error('invalid geojson')
- return {
- minX: bbox[0],
- minY: bbox[1],
- maxX: bbox[2],
- maxY: bbox[3]
- };
- };
- return tree;
- }
- module.exports = geojsonRbush;
- module.exports.default = geojsonRbush;
- },{"@turf/bbox":5,"@turf/helpers":11,"@turf/meta":16,"rbush":204}],45:[function(require,module,exports){
- var geojsonArea = require('geojson-area');
- module.exports = rewind;
- function rewind(gj, outer) {
- switch ((gj && gj.type) || null) {
- case 'FeatureCollection':
- gj.features = gj.features.map(curryOuter(rewind, outer));
- return gj;
- case 'Feature':
- gj.geometry = rewind(gj.geometry, outer);
- return gj;
- case 'Polygon':
- case 'MultiPolygon':
- return correct(gj, outer);
- default:
- return gj;
- }
- }
- function curryOuter(a, b) {
- return function(_) { return a(_, b); };
- }
- function correct(_, outer) {
- if (_.type === 'Polygon') {
- _.coordinates = correctRings(_.coordinates, outer);
- } else if (_.type === 'MultiPolygon') {
- _.coordinates = _.coordinates.map(curryOuter(correctRings, outer));
- }
- return _;
- }
- function correctRings(_, outer) {
- outer = !!outer;
- _[0] = wind(_[0], outer);
- for (var i = 1; i < _.length; i++) {
- _[i] = wind(_[i], !outer);
- }
- return _;
- }
- function wind(_, dir) {
- return cw(_) === dir ? _ : _.reverse();
- }
- function cw(_) {
- return geojsonArea.ring(_) >= 0;
- }
- },{"geojson-area":42}],46:[function(require,module,exports){
- "use strict";
- // Implementation originally from Twitter's Hogan.js:
- // https://github.com/twitter/hogan.js/blob/master/lib/template.js#L325-L335
- var rAmp = /&/g;
- var rLt = /</g;
- var rApos =/\'/g;
- var rQuot = /\"/g;
- var hChars =/[&<>\"\']/;
- module.exports = function(str) {
- if (str == null) {
- return str;
- }
- if (typeof str !== "string") {
- str = String(str);
- }
- if (hChars.test(String(str))) {
- return str
- .replace(rAmp,'&')
- .replace(rLt,'<')
- .replace(rApos,''')
- .replace(rQuot, '"');
- }
- else {
- return str;
- }
- };
- },{}],47:[function(require,module,exports){
- var getNative = require('./_getNative'),
- root = require('./_root');
- /* Built-in method references that are verified to be native. */
- var DataView = getNative(root, 'DataView');
- module.exports = DataView;
- },{"./_getNative":102,"./_root":137}],48:[function(require,module,exports){
- var hashClear = require('./_hashClear'),
- hashDelete = require('./_hashDelete'),
- hashGet = require('./_hashGet'),
- hashHas = require('./_hashHas'),
- hashSet = require('./_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;
- module.exports = Hash;
- },{"./_hashClear":108,"./_hashDelete":109,"./_hashGet":110,"./_hashHas":111,"./_hashSet":112}],49:[function(require,module,exports){
- var listCacheClear = require('./_listCacheClear'),
- listCacheDelete = require('./_listCacheDelete'),
- listCacheGet = require('./_listCacheGet'),
- listCacheHas = require('./_listCacheHas'),
- listCacheSet = require('./_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;
- module.exports = ListCache;
- },{"./_listCacheClear":119,"./_listCacheDelete":120,"./_listCacheGet":121,"./_listCacheHas":122,"./_listCacheSet":123}],50:[function(require,module,exports){
- var getNative = require('./_getNative'),
- root = require('./_root');
- /* Built-in method references that are verified to be native. */
- var Map = getNative(root, 'Map');
- module.exports = Map;
- },{"./_getNative":102,"./_root":137}],51:[function(require,module,exports){
- var mapCacheClear = require('./_mapCacheClear'),
- mapCacheDelete = require('./_mapCacheDelete'),
- mapCacheGet = require('./_mapCacheGet'),
- mapCacheHas = require('./_mapCacheHas'),
- mapCacheSet = require('./_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;
- module.exports = MapCache;
- },{"./_mapCacheClear":124,"./_mapCacheDelete":125,"./_mapCacheGet":126,"./_mapCacheHas":127,"./_mapCacheSet":128}],52:[function(require,module,exports){
- var getNative = require('./_getNative'),
- root = require('./_root');
- /* Built-in method references that are verified to be native. */
- var Promise = getNative(root, 'Promise');
- module.exports = Promise;
- },{"./_getNative":102,"./_root":137}],53:[function(require,module,exports){
- var getNative = require('./_getNative'),
- root = require('./_root');
- /* Built-in method references that are verified to be native. */
- var Set = getNative(root, 'Set');
- module.exports = Set;
- },{"./_getNative":102,"./_root":137}],54:[function(require,module,exports){
- var MapCache = require('./_MapCache'),
- setCacheAdd = require('./_setCacheAdd'),
- setCacheHas = require('./_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;
- module.exports = SetCache;
- },{"./_MapCache":51,"./_setCacheAdd":138,"./_setCacheHas":139}],55:[function(require,module,exports){
- var ListCache = require('./_ListCache'),
- stackClear = require('./_stackClear'),
- stackDelete = require('./_stackDelete'),
- stackGet = require('./_stackGet'),
- stackHas = require('./_stackHas'),
- stackSet = require('./_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;
- module.exports = Stack;
- },{"./_ListCache":49,"./_stackClear":141,"./_stackDelete":142,"./_stackGet":143,"./_stackHas":144,"./_stackSet":145}],56:[function(require,module,exports){
- var root = require('./_root');
- /** Built-in value references. */
- var Symbol = root.Symbol;
- module.exports = Symbol;
- },{"./_root":137}],57:[function(require,module,exports){
- var root = require('./_root');
- /** Built-in value references. */
- var Uint8Array = root.Uint8Array;
- module.exports = Uint8Array;
- },{"./_root":137}],58:[function(require,module,exports){
- var getNative = require('./_getNative'),
- root = require('./_root');
- /* Built-in method references that are verified to be native. */
- var WeakMap = getNative(root, 'WeakMap');
- module.exports = WeakMap;
- },{"./_getNative":102,"./_root":137}],59:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = arrayEach;
- },{}],60:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = arrayFilter;
- },{}],61:[function(require,module,exports){
- var baseTimes = require('./_baseTimes'),
- isArguments = require('./isArguments'),
- isArray = require('./isArray'),
- isBuffer = require('./isBuffer'),
- isIndex = require('./_isIndex'),
- isTypedArray = require('./isTypedArray');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.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(value),
- isArg = !isArr && isArguments(value),
- isBuff = !isArr && !isArg && isBuffer(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? baseTimes(value.length, String) : [],
- length = result.length;
- for (var key in value) {
- if ((inherited || hasOwnProperty.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;
- }
- module.exports = arrayLikeKeys;
- },{"./_baseTimes":86,"./_isIndex":113,"./isArguments":154,"./isArray":155,"./isBuffer":157,"./isTypedArray":163}],62:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = arrayMap;
- },{}],63:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = arrayPush;
- },{}],64:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = arraySome;
- },{}],65:[function(require,module,exports){
- var eq = require('./eq');
- /**
- * 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(array[length][0], key)) {
- return length;
- }
- }
- return -1;
- }
- module.exports = assocIndexOf;
- },{"./eq":149}],66:[function(require,module,exports){
- var baseForOwn = require('./_baseForOwn'),
- createBaseEach = require('./_createBaseEach');
- /**
- * The base implementation of `_.forEach` without support for iteratee shorthands.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- */
- var baseEach = createBaseEach(baseForOwn);
- module.exports = baseEach;
- },{"./_baseForOwn":68,"./_createBaseEach":93}],67:[function(require,module,exports){
- var createBaseFor = require('./_createBaseFor');
- /**
- * The base implementation of `baseForOwn` which iterates over `object`
- * properties returned by `keysFunc` and invokes `iteratee` for each property.
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
- var baseFor = createBaseFor();
- module.exports = baseFor;
- },{"./_createBaseFor":94}],68:[function(require,module,exports){
- var baseFor = require('./_baseFor'),
- keys = require('./keys');
- /**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
- function baseForOwn(object, iteratee) {
- return object && baseFor(object, iteratee, keys);
- }
- module.exports = baseForOwn;
- },{"./_baseFor":67,"./keys":164}],69:[function(require,module,exports){
- var castPath = require('./_castPath'),
- toKey = require('./_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;
- }
- module.exports = baseGet;
- },{"./_castPath":91,"./_toKey":147}],70:[function(require,module,exports){
- var arrayPush = require('./_arrayPush'),
- isArray = require('./isArray');
- /**
- * 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(object) ? result : arrayPush(result, symbolsFunc(object));
- }
- module.exports = baseGetAllKeys;
- },{"./_arrayPush":63,"./isArray":155}],71:[function(require,module,exports){
- var Symbol = require('./_Symbol'),
- getRawTag = require('./_getRawTag'),
- objectToString = require('./_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);
- }
- module.exports = baseGetTag;
- },{"./_Symbol":56,"./_getRawTag":103,"./_objectToString":135}],72:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = baseHasIn;
- },{}],73:[function(require,module,exports){
- var baseGetTag = require('./_baseGetTag'),
- isObjectLike = require('./isObjectLike');
- /** `Object#toString` result references. */
- var argsTag = '[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(value) && baseGetTag(value) == argsTag;
- }
- module.exports = baseIsArguments;
- },{"./_baseGetTag":71,"./isObjectLike":161}],74:[function(require,module,exports){
- var baseIsEqualDeep = require('./_baseIsEqualDeep'),
- isObjectLike = require('./isObjectLike');
- /**
- * 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(value) && !isObjectLike(other))) {
- return value !== value && other !== other;
- }
- return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
- }
- module.exports = baseIsEqual;
- },{"./_baseIsEqualDeep":75,"./isObjectLike":161}],75:[function(require,module,exports){
- var Stack = require('./_Stack'),
- equalArrays = require('./_equalArrays'),
- equalByTag = require('./_equalByTag'),
- equalObjects = require('./_equalObjects'),
- getTag = require('./_getTag'),
- isArray = require('./isArray'),
- isBuffer = require('./isBuffer'),
- isTypedArray = require('./isTypedArray');
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 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(object),
- othIsArr = isArray(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(object)) {
- if (!isBuffer(other)) {
- return false;
- }
- objIsArr = true;
- objIsObj = false;
- }
- if (isSameTag && !objIsObj) {
- stack || (stack = new Stack);
- return (objIsArr || isTypedArray(object))
- ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
- : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
- 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);
- }
- module.exports = baseIsEqualDeep;
- },{"./_Stack":55,"./_equalArrays":95,"./_equalByTag":96,"./_equalObjects":97,"./_getTag":105,"./isArray":155,"./isBuffer":157,"./isTypedArray":163}],76:[function(require,module,exports){
- var Stack = require('./_Stack'),
- baseIsEqual = require('./_baseIsEqual');
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 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 | COMPARE_UNORDERED_FLAG, customizer, stack)
- : result
- )) {
- return false;
- }
- }
- }
- return true;
- }
- module.exports = baseIsMatch;
- },{"./_Stack":55,"./_baseIsEqual":74}],77:[function(require,module,exports){
- var isFunction = require('./isFunction'),
- isMasked = require('./_isMasked'),
- isObject = require('./isObject'),
- toSource = require('./_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 = Function.prototype,
- objectProto = Object.prototype;
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' +
- funcToString.call(hasOwnProperty).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(value) || isMasked(value)) {
- return false;
- }
- var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
- return pattern.test(toSource(value));
- }
- module.exports = baseIsNative;
- },{"./_isMasked":116,"./_toSource":148,"./isFunction":158,"./isObject":160}],78:[function(require,module,exports){
- var baseGetTag = require('./_baseGetTag'),
- isLength = require('./isLength'),
- isObjectLike = require('./isObjectLike');
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]',
- arrayTag = '[object Array]',
- boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- funcTag = '[object Function]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- objectTag = '[object Object]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- weakMapTag = '[object WeakMap]';
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[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 of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
- typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
- typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
- typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
- typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
- typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
- typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
- typedArrayTags[errorTag] = typedArrayTags[funcTag] =
- typedArrayTags[mapTag] = typedArrayTags[numberTag] =
- typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
- typedArrayTags[setTag] = typedArrayTags[stringTag] =
- typedArrayTags[weakMapTag] = 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(value) &&
- isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
- }
- module.exports = baseIsTypedArray;
- },{"./_baseGetTag":71,"./isLength":159,"./isObjectLike":161}],79:[function(require,module,exports){
- var baseMatches = require('./_baseMatches'),
- baseMatchesProperty = require('./_baseMatchesProperty'),
- identity = require('./identity'),
- isArray = require('./isArray'),
- property = require('./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;
- }
- if (typeof value == 'object') {
- return isArray(value)
- ? baseMatchesProperty(value[0], value[1])
- : baseMatches(value);
- }
- return property(value);
- }
- module.exports = baseIteratee;
- },{"./_baseMatches":82,"./_baseMatchesProperty":83,"./identity":153,"./isArray":155,"./property":167}],80:[function(require,module,exports){
- var isPrototype = require('./_isPrototype'),
- nativeKeys = require('./_nativeKeys');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.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.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
- module.exports = baseKeys;
- },{"./_isPrototype":117,"./_nativeKeys":133}],81:[function(require,module,exports){
- var baseEach = require('./_baseEach'),
- isArrayLike = require('./isArrayLike');
- /**
- * The base implementation of `_.map` without support for iteratee shorthands.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- */
- function baseMap(collection, iteratee) {
- var index = -1,
- result = isArrayLike(collection) ? Array(collection.length) : [];
- baseEach(collection, function(value, key, collection) {
- result[++index] = iteratee(value, key, collection);
- });
- return result;
- }
- module.exports = baseMap;
- },{"./_baseEach":66,"./isArrayLike":156}],82:[function(require,module,exports){
- var baseIsMatch = require('./_baseIsMatch'),
- getMatchData = require('./_getMatchData'),
- matchesStrictComparable = require('./_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);
- };
- }
- module.exports = baseMatches;
- },{"./_baseIsMatch":76,"./_getMatchData":101,"./_matchesStrictComparable":130}],83:[function(require,module,exports){
- var baseIsEqual = require('./_baseIsEqual'),
- get = require('./get'),
- hasIn = require('./hasIn'),
- isKey = require('./_isKey'),
- isStrictComparable = require('./_isStrictComparable'),
- matchesStrictComparable = require('./_matchesStrictComparable'),
- toKey = require('./_toKey');
- /** 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(object, path);
- return (objValue === undefined && objValue === srcValue)
- ? hasIn(object, path)
- : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
- };
- }
- module.exports = baseMatchesProperty;
- },{"./_baseIsEqual":74,"./_isKey":114,"./_isStrictComparable":118,"./_matchesStrictComparable":130,"./_toKey":147,"./get":151,"./hasIn":152}],84:[function(require,module,exports){
- /**
- * 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];
- };
- }
- module.exports = baseProperty;
- },{}],85:[function(require,module,exports){
- var baseGet = require('./_baseGet');
- /**
- * 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);
- };
- }
- module.exports = basePropertyDeep;
- },{"./_baseGet":69}],86:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = baseTimes;
- },{}],87:[function(require,module,exports){
- var Symbol = require('./_Symbol'),
- arrayMap = require('./_arrayMap'),
- isArray = require('./isArray'),
- isSymbol = require('./isSymbol');
- /** Used as references for various `Number` constants. */
- var INFINITY = 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(value)) {
- // Recursively convert values (susceptible to call stack limits).
- return arrayMap(value, baseToString) + '';
- }
- if (isSymbol(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
- module.exports = baseToString;
- },{"./_Symbol":56,"./_arrayMap":62,"./isArray":155,"./isSymbol":162}],88:[function(require,module,exports){
- /**
- * 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);
- };
- }
- module.exports = baseUnary;
- },{}],89:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = cacheHas;
- },{}],90:[function(require,module,exports){
- var identity = require('./identity');
- /**
- * Casts `value` to `identity` if it's not a function.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {Function} Returns cast function.
- */
- function castFunction(value) {
- return typeof value == 'function' ? value : identity;
- }
- module.exports = castFunction;
- },{"./identity":153}],91:[function(require,module,exports){
- var isArray = require('./isArray'),
- isKey = require('./_isKey'),
- stringToPath = require('./_stringToPath'),
- toString = require('./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(value)) {
- return value;
- }
- return isKey(value, object) ? [value] : stringToPath(toString(value));
- }
- module.exports = castPath;
- },{"./_isKey":114,"./_stringToPath":146,"./isArray":155,"./toString":170}],92:[function(require,module,exports){
- var root = require('./_root');
- /** Used to detect overreaching core-js shims. */
- var coreJsData = root['__core-js_shared__'];
- module.exports = coreJsData;
- },{"./_root":137}],93:[function(require,module,exports){
- var isArrayLike = require('./isArrayLike');
- /**
- * Creates a `baseEach` or `baseEachRight` function.
- *
- * @private
- * @param {Function} eachFunc The function to iterate over a collection.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseEach(eachFunc, fromRight) {
- return function(collection, iteratee) {
- if (collection == null) {
- return collection;
- }
- if (!isArrayLike(collection)) {
- return eachFunc(collection, iteratee);
- }
- var length = collection.length,
- index = fromRight ? length : -1,
- iterable = Object(collection);
- while ((fromRight ? index-- : ++index < length)) {
- if (iteratee(iterable[index], index, iterable) === false) {
- break;
- }
- }
- return collection;
- };
- }
- module.exports = createBaseEach;
- },{"./isArrayLike":156}],94:[function(require,module,exports){
- /**
- * Creates a base function for methods like `_.forIn` and `_.forOwn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseFor(fromRight) {
- return function(object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
- }
- module.exports = createBaseFor;
- },{}],95:[function(require,module,exports){
- var SetCache = require('./_SetCache'),
- arraySome = require('./_arraySome'),
- cacheHas = require('./_cacheHas');
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 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,
- arrLength = array.length,
- othLength = other.length;
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(array);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- var index = -1,
- result = true,
- seen = (bitmask & COMPARE_UNORDERED_FLAG) ? 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;
- }
- module.exports = equalArrays;
- },{"./_SetCache":54,"./_arraySome":64,"./_cacheHas":89}],96:[function(require,module,exports){
- var Symbol = require('./_Symbol'),
- Uint8Array = require('./_Uint8Array'),
- eq = require('./eq'),
- equalArrays = require('./_equalArrays'),
- mapToArray = require('./_mapToArray'),
- setToArray = require('./_setToArray');
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 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 = Symbol ? Symbol.prototype : undefined,
- symbolValueOf = symbolProto ? symbolProto.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(+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;
- 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;
- // 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;
- }
- module.exports = equalByTag;
- },{"./_Symbol":56,"./_Uint8Array":57,"./_equalArrays":95,"./_mapToArray":129,"./_setToArray":140,"./eq":149}],97:[function(require,module,exports){
- var getAllKeys = require('./_getAllKeys');
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1;
- /** 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 `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,
- 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.call(other, key))) {
- return false;
- }
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- 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;
- }
- module.exports = equalObjects;
- },{"./_getAllKeys":99}],98:[function(require,module,exports){
- (function (global){
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
- module.exports = freeGlobal;
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],99:[function(require,module,exports){
- var baseGetAllKeys = require('./_baseGetAllKeys'),
- getSymbols = require('./_getSymbols'),
- keys = require('./keys');
- /**
- * 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, getSymbols);
- }
- module.exports = getAllKeys;
- },{"./_baseGetAllKeys":70,"./_getSymbols":104,"./keys":164}],100:[function(require,module,exports){
- var isKeyable = require('./_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;
- }
- module.exports = getMapData;
- },{"./_isKeyable":115}],101:[function(require,module,exports){
- var isStrictComparable = require('./_isStrictComparable'),
- keys = require('./keys');
- /**
- * 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(object),
- length = result.length;
- while (length--) {
- var key = result[length],
- value = object[key];
- result[length] = [key, value, isStrictComparable(value)];
- }
- return result;
- }
- module.exports = getMatchData;
- },{"./_isStrictComparable":118,"./keys":164}],102:[function(require,module,exports){
- var baseIsNative = require('./_baseIsNative'),
- getValue = require('./_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;
- }
- module.exports = getNative;
- },{"./_baseIsNative":77,"./_getValue":106}],103:[function(require,module,exports){
- var Symbol = require('./_Symbol');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto.toString;
- /** Built-in value references. */
- var symToStringTag = 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.call(value, symToStringTag),
- tag = value[symToStringTag];
- try {
- value[symToStringTag] = undefined;
- var unmasked = true;
- } catch (e) {}
- var result = nativeObjectToString.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag] = tag;
- } else {
- delete value[symToStringTag];
- }
- }
- return result;
- }
- module.exports = getRawTag;
- },{"./_Symbol":56}],104:[function(require,module,exports){
- var arrayFilter = require('./_arrayFilter'),
- stubArray = require('./stubArray');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Built-in value references. */
- var propertyIsEnumerable = objectProto.propertyIsEnumerable;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols = 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 ? stubArray : function(object) {
- if (object == null) {
- return [];
- }
- object = Object(object);
- return arrayFilter(nativeGetSymbols(object), function(symbol) {
- return propertyIsEnumerable.call(object, symbol);
- });
- };
- module.exports = getSymbols;
- },{"./_arrayFilter":60,"./stubArray":168}],105:[function(require,module,exports){
- var DataView = require('./_DataView'),
- Map = require('./_Map'),
- Promise = require('./_Promise'),
- Set = require('./_Set'),
- WeakMap = require('./_WeakMap'),
- baseGetTag = require('./_baseGetTag'),
- toSource = require('./_toSource');
- /** `Object#toString` result references. */
- var mapTag = '[object Map]',
- objectTag = '[object Object]',
- promiseTag = '[object Promise]',
- setTag = '[object Set]',
- weakMapTag = '[object WeakMap]';
- var dataViewTag = '[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) ||
- (Map && getTag(new Map) != mapTag) ||
- (Promise && getTag(Promise.resolve()) != promiseTag) ||
- (Set && getTag(new Set) != setTag) ||
- (WeakMap && getTag(new WeakMap) != weakMapTag)) {
- getTag = function(value) {
- var result = baseGetTag(value),
- Ctor = result == objectTag ? value.constructor : undefined,
- ctorString = Ctor ? toSource(Ctor) : '';
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString: return dataViewTag;
- case mapCtorString: return mapTag;
- case promiseCtorString: return promiseTag;
- case setCtorString: return setTag;
- case weakMapCtorString: return weakMapTag;
- }
- }
- return result;
- };
- }
- module.exports = getTag;
- },{"./_DataView":47,"./_Map":50,"./_Promise":52,"./_Set":53,"./_WeakMap":58,"./_baseGetTag":71,"./_toSource":148}],106:[function(require,module,exports){
- /**
- * 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];
- }
- module.exports = getValue;
- },{}],107:[function(require,module,exports){
- var castPath = require('./_castPath'),
- isArguments = require('./isArguments'),
- isArray = require('./isArray'),
- isIndex = require('./_isIndex'),
- isLength = require('./isLength'),
- toKey = require('./_toKey');
- /**
- * 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(length) && isIndex(key, length) &&
- (isArray(object) || isArguments(object));
- }
- module.exports = hasPath;
- },{"./_castPath":91,"./_isIndex":113,"./_toKey":147,"./isArguments":154,"./isArray":155,"./isLength":159}],108:[function(require,module,exports){
- var nativeCreate = require('./_nativeCreate');
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
- this.size = 0;
- }
- module.exports = hashClear;
- },{"./_nativeCreate":132}],109:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = hashDelete;
- },{}],110:[function(require,module,exports){
- var nativeCreate = require('./_nativeCreate');
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.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 ? undefined : result;
- }
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
- }
- module.exports = hashGet;
- },{"./_nativeCreate":132}],111:[function(require,module,exports){
- var nativeCreate = require('./_nativeCreate');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.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.call(data, key);
- }
- module.exports = hashHas;
- },{"./_nativeCreate":132}],112:[function(require,module,exports){
- var nativeCreate = require('./_nativeCreate');
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__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 : value;
- return this;
- }
- module.exports = hashSet;
- },{"./_nativeCreate":132}],113:[function(require,module,exports){
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER = 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 : length;
- return !!length &&
- (type == 'number' ||
- (type != 'symbol' && reIsUint.test(value))) &&
- (value > -1 && value % 1 == 0 && value < length);
- }
- module.exports = isIndex;
- },{}],114:[function(require,module,exports){
- var isArray = require('./isArray'),
- isSymbol = require('./isSymbol');
- /** 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(value)) {
- return false;
- }
- var type = typeof value;
- if (type == 'number' || type == 'symbol' || type == 'boolean' ||
- value == null || isSymbol(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
- (object != null && value in Object(object));
- }
- module.exports = isKey;
- },{"./isArray":155,"./isSymbol":162}],115:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = isKeyable;
- },{}],116:[function(require,module,exports){
- var coreJsData = require('./_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);
- }
- module.exports = isMasked;
- },{"./_coreJsData":92}],117:[function(require,module,exports){
- /** Used for built-in method references. */
- var objectProto = 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;
- return value === proto;
- }
- module.exports = isPrototype;
- },{}],118:[function(require,module,exports){
- var isObject = require('./isObject');
- /**
- * 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(value);
- }
- module.exports = isStrictComparable;
- },{"./isObject":160}],119:[function(require,module,exports){
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
- }
- module.exports = listCacheClear;
- },{}],120:[function(require,module,exports){
- var assocIndexOf = require('./_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;
- }
- module.exports = listCacheDelete;
- },{"./_assocIndexOf":65}],121:[function(require,module,exports){
- var assocIndexOf = require('./_assocIndexOf');
- /**
- * 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];
- }
- module.exports = listCacheGet;
- },{"./_assocIndexOf":65}],122:[function(require,module,exports){
- var assocIndexOf = require('./_assocIndexOf');
- /**
- * 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;
- }
- module.exports = listCacheHas;
- },{"./_assocIndexOf":65}],123:[function(require,module,exports){
- var assocIndexOf = require('./_assocIndexOf');
- /**
- * 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;
- }
- module.exports = listCacheSet;
- },{"./_assocIndexOf":65}],124:[function(require,module,exports){
- var Hash = require('./_Hash'),
- ListCache = require('./_ListCache'),
- Map = require('./_Map');
- /**
- * 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
- };
- }
- module.exports = mapCacheClear;
- },{"./_Hash":48,"./_ListCache":49,"./_Map":50}],125:[function(require,module,exports){
- var getMapData = require('./_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;
- }
- module.exports = mapCacheDelete;
- },{"./_getMapData":100}],126:[function(require,module,exports){
- var getMapData = require('./_getMapData');
- /**
- * 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);
- }
- module.exports = mapCacheGet;
- },{"./_getMapData":100}],127:[function(require,module,exports){
- var getMapData = require('./_getMapData');
- /**
- * 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);
- }
- module.exports = mapCacheHas;
- },{"./_getMapData":100}],128:[function(require,module,exports){
- var getMapData = require('./_getMapData');
- /**
- * 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;
- }
- module.exports = mapCacheSet;
- },{"./_getMapData":100}],129:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = mapToArray;
- },{}],130:[function(require,module,exports){
- /**
- * 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)));
- };
- }
- module.exports = matchesStrictComparable;
- },{}],131:[function(require,module,exports){
- var memoize = require('./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(func, function(key) {
- if (cache.size === MAX_MEMOIZE_SIZE) {
- cache.clear();
- }
- return key;
- });
- var cache = result.cache;
- return result;
- }
- module.exports = memoizeCapped;
- },{"./memoize":166}],132:[function(require,module,exports){
- var getNative = require('./_getNative');
- /* Built-in method references that are verified to be native. */
- var nativeCreate = getNative(Object, 'create');
- module.exports = nativeCreate;
- },{"./_getNative":102}],133:[function(require,module,exports){
- var overArg = require('./_overArg');
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeKeys = overArg(Object.keys, Object);
- module.exports = nativeKeys;
- },{"./_overArg":136}],134:[function(require,module,exports){
- var freeGlobal = require('./_freeGlobal');
- /** Detect free variable `exports`. */
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && typeof module == '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;
- },{"./_freeGlobal":98}],135:[function(require,module,exports){
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto.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);
- }
- module.exports = objectToString;
- },{}],136:[function(require,module,exports){
- /**
- * 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));
- };
- }
- module.exports = overArg;
- },{}],137:[function(require,module,exports){
- var freeGlobal = require('./_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')();
- module.exports = root;
- },{"./_freeGlobal":98}],138:[function(require,module,exports){
- /** 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;
- }
- module.exports = setCacheAdd;
- },{}],139:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = setCacheHas;
- },{}],140:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = setToArray;
- },{}],141:[function(require,module,exports){
- var ListCache = require('./_ListCache');
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new ListCache;
- this.size = 0;
- }
- module.exports = stackClear;
- },{"./_ListCache":49}],142:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = stackDelete;
- },{}],143:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = stackGet;
- },{}],144:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = stackHas;
- },{}],145:[function(require,module,exports){
- var ListCache = require('./_ListCache'),
- Map = require('./_Map'),
- MapCache = require('./_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;
- }
- module.exports = stackSet;
- },{"./_ListCache":49,"./_Map":50,"./_MapCache":51}],146:[function(require,module,exports){
- var memoizeCapped = require('./_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;
- });
- module.exports = stringToPath;
- },{"./_memoizeCapped":131}],147:[function(require,module,exports){
- var isSymbol = require('./isSymbol');
- /** 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(value)) {
- return value;
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
- module.exports = toKey;
- },{"./isSymbol":162}],148:[function(require,module,exports){
- /** Used for built-in method references. */
- var funcProto = Function.prototype;
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.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.call(func);
- } catch (e) {}
- try {
- return (func + '');
- } catch (e) {}
- }
- return '';
- }
- module.exports = toSource;
- },{}],149:[function(require,module,exports){
- /**
- * 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);
- }
- module.exports = eq;
- },{}],150:[function(require,module,exports){
- var arrayEach = require('./_arrayEach'),
- baseEach = require('./_baseEach'),
- castFunction = require('./_castFunction'),
- isArray = require('./isArray');
- /**
- * Iterates over elements of `collection` and invokes `iteratee` for each element.
- * The iteratee is invoked with three arguments: (value, index|key, collection).
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * **Note:** As with other "Collections" methods, objects with a "length"
- * property are iterated like arrays. To avoid this behavior use `_.forIn`
- * or `_.forOwn` for object iteration.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @alias each
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- * @see _.forEachRight
- * @example
- *
- * _.forEach([1, 2], function(value) {
- * console.log(value);
- * });
- * // => Logs `1` then `2`.
- *
- * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'a' then 'b' (iteration order is not guaranteed).
- */
- function forEach(collection, iteratee) {
- var func = isArray(collection) ? arrayEach : baseEach;
- return func(collection, castFunction(iteratee));
- }
- module.exports = forEach;
- },{"./_arrayEach":59,"./_baseEach":66,"./_castFunction":90,"./isArray":155}],151:[function(require,module,exports){
- var baseGet = require('./_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(object, path, defaultValue) {
- var result = object == null ? undefined : baseGet(object, path);
- return result === undefined ? defaultValue : result;
- }
- module.exports = get;
- },{"./_baseGet":69}],152:[function(require,module,exports){
- var baseHasIn = require('./_baseHasIn'),
- hasPath = require('./_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);
- }
- module.exports = hasIn;
- },{"./_baseHasIn":72,"./_hasPath":107}],153:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = identity;
- },{}],154:[function(require,module,exports){
- var baseIsArguments = require('./_baseIsArguments'),
- isObjectLike = require('./isObjectLike');
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /** Built-in value references. */
- var propertyIsEnumerable = objectProto.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(value) && hasOwnProperty.call(value, 'callee') &&
- !propertyIsEnumerable.call(value, 'callee');
- };
- module.exports = isArguments;
- },{"./_baseIsArguments":73,"./isObjectLike":161}],155:[function(require,module,exports){
- /**
- * 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 = Array.isArray;
- module.exports = isArray;
- },{}],156:[function(require,module,exports){
- var isFunction = require('./isFunction'),
- isLength = require('./isLength');
- /**
- * 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(value.length) && !isFunction(value);
- }
- module.exports = isArrayLike;
- },{"./isFunction":158,"./isLength":159}],157:[function(require,module,exports){
- var root = require('./_root'),
- stubFalse = require('./stubFalse');
- /** Detect free variable `exports`. */
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && typeof module == '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;
- module.exports = isBuffer;
- },{"./_root":137,"./stubFalse":169}],158:[function(require,module,exports){
- var baseGetTag = require('./_baseGetTag'),
- isObject = require('./isObject');
- /** `Object#toString` result references. */
- var asyncTag = '[object AsyncFunction]',
- funcTag = '[object Function]',
- genTag = '[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(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 || tag == genTag || tag == asyncTag || tag == proxyTag;
- }
- module.exports = isFunction;
- },{"./_baseGetTag":71,"./isObject":160}],159:[function(require,module,exports){
- /** 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;
- }
- module.exports = isLength;
- },{}],160:[function(require,module,exports){
- /**
- * 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(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
- }
- module.exports = isObject;
- },{}],161:[function(require,module,exports){
- /**
- * 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';
- }
- module.exports = isObjectLike;
- },{}],162:[function(require,module,exports){
- var baseGetTag = require('./_baseGetTag'),
- isObjectLike = require('./isObjectLike');
- /** `Object#toString` result references. */
- var symbolTag = '[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(value) && baseGetTag(value) == symbolTag);
- }
- module.exports = isSymbol;
- },{"./_baseGetTag":71,"./isObjectLike":161}],163:[function(require,module,exports){
- var baseIsTypedArray = require('./_baseIsTypedArray'),
- baseUnary = require('./_baseUnary'),
- nodeUtil = require('./_nodeUtil');
- /* 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;
- module.exports = isTypedArray;
- },{"./_baseIsTypedArray":78,"./_baseUnary":88,"./_nodeUtil":134}],164:[function(require,module,exports){
- var arrayLikeKeys = require('./_arrayLikeKeys'),
- baseKeys = require('./_baseKeys'),
- isArrayLike = require('./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(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
- module.exports = keys;
- },{"./_arrayLikeKeys":61,"./_baseKeys":80,"./isArrayLike":156}],165:[function(require,module,exports){
- var arrayMap = require('./_arrayMap'),
- baseIteratee = require('./_baseIteratee'),
- baseMap = require('./_baseMap'),
- isArray = require('./isArray');
- /**
- * Creates an array of values by running each element in `collection` thru
- * `iteratee`. The iteratee is invoked with three arguments:
- * (value, index|key, collection).
- *
- * Many lodash methods are guarded to work as iteratees for methods like
- * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
- *
- * The guarded methods are:
- * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
- * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
- * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
- * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- * @example
- *
- * function square(n) {
- * return n * n;
- * }
- *
- * _.map([4, 8], square);
- * // => [16, 64]
- *
- * _.map({ 'a': 4, 'b': 8 }, square);
- * // => [16, 64] (iteration order is not guaranteed)
- *
- * var users = [
- * { 'user': 'barney' },
- * { 'user': 'fred' }
- * ];
- *
- * // The `_.property` iteratee shorthand.
- * _.map(users, 'user');
- * // => ['barney', 'fred']
- */
- function map(collection, iteratee) {
- var func = isArray(collection) ? arrayMap : baseMap;
- return func(collection, baseIteratee(iteratee, 3));
- }
- module.exports = map;
- },{"./_arrayMap":62,"./_baseIteratee":79,"./_baseMap":81,"./isArray":155}],166:[function(require,module,exports){
- var MapCache = require('./_MapCache');
- /** 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;
- module.exports = memoize;
- },{"./_MapCache":51}],167:[function(require,module,exports){
- var baseProperty = require('./_baseProperty'),
- basePropertyDeep = require('./_basePropertyDeep'),
- isKey = require('./_isKey'),
- toKey = require('./_toKey');
- /**
- * 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);
- }
- module.exports = property;
- },{"./_baseProperty":84,"./_basePropertyDeep":85,"./_isKey":114,"./_toKey":147}],168:[function(require,module,exports){
- /**
- * 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 [];
- }
- module.exports = stubArray;
- },{}],169:[function(require,module,exports){
- /**
- * 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;
- }
- module.exports = stubFalse;
- },{}],170:[function(require,module,exports){
- var baseToString = require('./_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);
- }
- module.exports = toString;
- },{"./_baseToString":87}],171:[function(require,module,exports){
- /*
- Loki IndexedDb Adapter (need to include this script to use it)
- Console Usage can be used for management/diagnostic, here are a few examples :
- adapter.getDatabaseList(); // with no callback passed, this method will log results to console
- adapter.saveDatabase('UserDatabase', JSON.stringify(myDb));
- adapter.loadDatabase('UserDatabase'); // will log the serialized db to console
- adapter.deleteDatabase('UserDatabase');
- */
- (function (root, factory) {
- if (typeof define === 'function' && define.amd) {
- // AMD
- define([], factory);
- } else if (typeof exports === 'object') {
- // Node, CommonJS-like
- module.exports = factory();
- } else {
- // Browser globals (root is window)
- root.LokiIndexedAdapter = factory();
- }
- }(this, function () {
- return (function() {
- /**
- * Loki persistence adapter class for indexedDb.
- * This class fulfills abstract adapter interface which can be applied to other storage methods.
- * Utilizes the included LokiCatalog app/key/value database for actual database persistence.
- * Indexeddb is highly async, but this adapter has been made 'console-friendly' as well.
- * Anywhere a callback is omitted, it should return results (if applicable) to console.
- * IndexedDb storage is provided per-domain, so we implement app/key/value database to
- * allow separate contexts for separate apps within a domain.
- *
- * @example
- * var idbAdapter = new LokiIndexedAdapter('finance');
- *
- * @constructor LokiIndexedAdapter
- *
- * @param {string} appname - (Optional) Application name context can be used to distinguish subdomains, 'loki' by default
- * @param {object=} options Configuration options for the adapter
- * @param {boolean} options.closeAfterSave Whether the indexedDB database should be closed after saving.
- */
- function LokiIndexedAdapter(appname, options)
- {
- this.app = 'loki';
- this.options = options || {};
- if (typeof (appname) !== 'undefined')
- {
- this.app = appname;
- }
- // keep reference to catalog class for base AKV operations
- this.catalog = null;
- if (!this.checkAvailability()) {
- throw new Error('indexedDB does not seem to be supported for your environment');
- }
- }
- /**
- * Used for closing the indexeddb database.
- */
- LokiIndexedAdapter.prototype.closeDatabase = function ()
- {
- if (this.catalog && this.catalog.db) {
- this.catalog.db.close();
- this.catalog.db = null;
- }
- };
- /**
- * Used to check if adapter is available
- *
- * @returns {boolean} true if indexeddb is available, false if not.
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.checkAvailability = function()
- {
- if (typeof indexedDB !== 'undefined' && indexedDB) return true;
- return false;
- };
- /**
- * Retrieves a serialized db string from the catalog.
- *
- * @example
- * // LOAD
- * var idbAdapter = new LokiIndexedAdapter('finance');
- * var db = new loki('test', { adapter: idbAdapter });
- * db.loadDatabase(function(result) {
- * console.log('done');
- * });
- *
- * @param {string} dbname - the name of the database to retrieve.
- * @param {function} callback - callback should accept string param containing serialized db string.
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.loadDatabase = function(dbname, callback)
- {
- var appName = this.app;
- var adapter = this;
- // lazy open/create db reference so dont -need- callback in constructor
- if (this.catalog === null || this.catalog.db === null) {
- this.catalog = new LokiCatalog(function(cat) {
- adapter.catalog = cat;
- adapter.loadDatabase(dbname, callback);
- });
- return;
- }
- // lookup up db string in AKV db
- this.catalog.getAppKey(appName, dbname, function(result) {
- if (typeof (callback) === 'function') {
- if (result.id === 0) {
- callback(null);
- return;
- }
- callback(result.val);
- }
- else {
- // support console use of api
- console.log(result.val);
- }
- });
- };
- // alias
- LokiIndexedAdapter.prototype.loadKey = LokiIndexedAdapter.prototype.loadDatabase;
- /**
- * Saves a serialized db to the catalog.
- *
- * @example
- * // SAVE : will save App/Key/Val as 'finance'/'test'/{serializedDb}
- * var idbAdapter = new LokiIndexedAdapter('finance');
- * var db = new loki('test', { adapter: idbAdapter });
- * var coll = db.addCollection('testColl');
- * coll.insert({test: 'val'});
- * db.saveDatabase(); // could pass callback if needed for async complete
- *
- * @param {string} dbname - the name to give the serialized database within the catalog.
- * @param {string} dbstring - the serialized db string to save.
- * @param {function} callback - (Optional) callback passed obj.success with true or false
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.saveDatabase = function(dbname, dbstring, callback)
- {
- var appName = this.app;
- var adapter = this;
- function saveCallback(result) {
- if (result && result.success === true) {
- callback(null);
- }
- else {
- callback(new Error("Error saving database"));
- }
- if (adapter.options.closeAfterSave) {
- adapter.closeDatabase();
- }
- }
- // lazy open/create db reference so dont -need- callback in constructor
- if (this.catalog === null || this.catalog.db === null) {
- this.catalog = new LokiCatalog(function(cat) {
- adapter.saveDatabase(dbname, dbstring, saveCallback);
- });
- return;
- }
- // set (add/update) entry to AKV database
- this.catalog.setAppKey(appName, dbname, dbstring, saveCallback);
- };
- // alias
- LokiIndexedAdapter.prototype.saveKey = LokiIndexedAdapter.prototype.saveDatabase;
- /**
- * Deletes a serialized db from the catalog.
- *
- * @example
- * // DELETE DATABASE
- * // delete 'finance'/'test' value from catalog
- * idbAdapter.deleteDatabase('test', function {
- * // database deleted
- * });
- *
- * @param {string} dbname - the name of the database to delete from the catalog.
- * @param {function=} callback - (Optional) executed on database delete
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.deleteDatabase = function(dbname, callback)
- {
- var appName = this.app;
- var adapter = this;
- // lazy open/create db reference and pass callback ahead
- if (this.catalog === null || this.catalog.db === null) {
- this.catalog = new LokiCatalog(function(cat) {
- adapter.catalog = cat;
- adapter.deleteDatabase(dbname, callback);
- });
- return;
- }
- // catalog was already initialized, so just lookup object and delete by id
- this.catalog.getAppKey(appName, dbname, function(result) {
- var id = result.id;
- if (id !== 0) {
- adapter.catalog.deleteAppKey(id, callback);
- } else if (typeof (callback) === 'function') {
- callback({ success: true });
- }
- });
- };
- // alias
- LokiIndexedAdapter.prototype.deleteKey = LokiIndexedAdapter.prototype.deleteDatabase;
- /**
- * Removes all database partitions and pages with the base filename passed in.
- * This utility method does not (yet) guarantee async deletions will be completed before returning
- *
- * @param {string} dbname - the base filename which container, partitions, or pages are derived
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.deleteDatabasePartitions = function(dbname) {
- var self=this;
- this.getDatabaseList(function(result) {
- result.forEach(function(str) {
- if (str.startsWith(dbname)) {
- self.deleteDatabase(str);
- }
- });
- });
- };
- /**
- * Retrieves object array of catalog entries for current app.
- *
- * @example
- * idbAdapter.getDatabaseList(function(result) {
- * // result is array of string names for that appcontext ('finance')
- * result.forEach(function(str) {
- * console.log(str);
- * });
- * });
- *
- * @param {function} callback - should accept array of database names in the catalog for current app.
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.getDatabaseList = function(callback)
- {
- var appName = this.app;
- var adapter = this;
- // lazy open/create db reference so dont -need- callback in constructor
- if (this.catalog === null || this.catalog.db === null) {
- this.catalog = new LokiCatalog(function(cat) {
- adapter.catalog = cat;
- adapter.getDatabaseList(callback);
- });
- return;
- }
- // catalog already initialized
- // get all keys for current appName, and transpose results so just string array
- this.catalog.getAppKeys(appName, function(results) {
- var names = [];
- for(var idx = 0; idx < results.length; idx++) {
- names.push(results[idx].key);
- }
- if (typeof (callback) === 'function') {
- callback(names);
- }
- else {
- names.forEach(function(obj) {
- console.log(obj);
- });
- }
- });
- };
- // alias
- LokiIndexedAdapter.prototype.getKeyList = LokiIndexedAdapter.prototype.getDatabaseList;
- /**
- * Allows retrieval of list of all keys in catalog along with size
- *
- * @param {function} callback - (Optional) callback to accept result array.
- * @memberof LokiIndexedAdapter
- */
- LokiIndexedAdapter.prototype.getCatalogSummary = function(callback)
- {
- var appName = this.app;
- var adapter = this;
- // lazy open/create db reference
- if (this.catalog === null || this.catalog.db === null) {
- this.catalog = new LokiCatalog(function(cat) {
- adapter.catalog = cat;
- adapter.getCatalogSummary(callback);
- });
- return;
- }
- // catalog already initialized
- // get all keys for current appName, and transpose results so just string array
- this.catalog.getAllKeys(function(results) {
- var entries = [];
- var obj,
- size,
- oapp,
- okey,
- oval;
- for(var idx = 0; idx < results.length; idx++) {
- obj = results[idx];
- oapp = obj.app || '';
- okey = obj.key || '';
- oval = obj.val || '';
- // app and key are composited into an appkey column so we will mult by 2
- size = oapp.length * 2 + okey.length * 2 + oval.length + 1;
- entries.push({ "app": obj.app, "key": obj.key, "size": size });
- }
- if (typeof (callback) === 'function') {
- callback(entries);
- }
- else {
- entries.forEach(function(obj) {
- console.log(obj);
- });
- }
- });
- };
- /**
- * LokiCatalog - underlying App/Key/Value catalog persistence
- * This non-interface class implements the actual persistence.
- * Used by the IndexedAdapter class.
- */
- function LokiCatalog(callback)
- {
- this.db = null;
- this.initializeLokiCatalog(callback);
- }
- LokiCatalog.prototype.initializeLokiCatalog = function(callback) {
- var openRequest = indexedDB.open('LokiCatalog', 1);
- var cat = this;
- // If database doesn't exist yet or its version is lower than our version specified above (2nd param in line above)
- openRequest.onupgradeneeded = function(e) {
- var thisDB = e.target.result;
- if (thisDB.objectStoreNames.contains('LokiAKV')) {
- thisDB.deleteObjectStore('LokiAKV');
- }
- if(!thisDB.objectStoreNames.contains('LokiAKV')) {
- var objectStore = thisDB.createObjectStore('LokiAKV', { keyPath: 'id', autoIncrement:true });
- objectStore.createIndex('app', 'app', {unique:false});
- objectStore.createIndex('key', 'key', {unique:false});
- // hack to simulate composite key since overhead is low (main size should be in val field)
- // user (me) required to duplicate the app and key into comma delimited appkey field off object
- // This will allow retrieving single record with that composite key as well as
- // still supporting opening cursors on app or key alone
- objectStore.createIndex('appkey', 'appkey', {unique:true});
- }
- };
- openRequest.onsuccess = function(e) {
- cat.db = e.target.result;
- if (typeof (callback) === 'function') callback(cat);
- };
- openRequest.onerror = function(e) {
- throw e;
- };
- };
- LokiCatalog.prototype.getAppKey = function(app, key, callback) {
- var transaction = this.db.transaction(['LokiAKV'], 'readonly');
- var store = transaction.objectStore('LokiAKV');
- var index = store.index('appkey');
- var appkey = app + "," + key;
- var request = index.get(appkey);
- request.onsuccess = (function(usercallback) {
- return function(e) {
- var lres = e.target.result;
- if (lres === null || typeof(lres) === 'undefined') {
- lres = {
- id: 0,
- success: false
- };
- }
- if (typeof(usercallback) === 'function') {
- usercallback(lres);
- }
- else {
- console.log(lres);
- }
- };
- })(callback);
- request.onerror = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback({ id: 0, success: false });
- }
- else {
- throw e;
- }
- };
- })(callback);
- };
- LokiCatalog.prototype.getAppKeyById = function (id, callback, data) {
- var transaction = this.db.transaction(['LokiAKV'], 'readonly');
- var store = transaction.objectStore('LokiAKV');
- var request = store.get(id);
- request.onsuccess = (function(data, usercallback){
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback(e.target.result, data);
- }
- else {
- console.log(e.target.result);
- }
- };
- })(data, callback);
- };
- LokiCatalog.prototype.setAppKey = function (app, key, val, callback) {
- var transaction = this.db.transaction(['LokiAKV'], 'readwrite');
- var store = transaction.objectStore('LokiAKV');
- var index = store.index('appkey');
- var appkey = app + "," + key;
- var request = index.get(appkey);
- // first try to retrieve an existing object by that key
- // need to do this because to update an object you need to have id in object, otherwise it will append id with new autocounter and clash the unique index appkey
- request.onsuccess = function(e) {
- var res = e.target.result;
- if (res === null || res === undefined) {
- res = {
- app:app,
- key:key,
- appkey: app + ',' + key,
- val:val
- };
- }
- else {
- res.val = val;
- }
- var requestPut = store.put(res);
- requestPut.onerror = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback({ success: false });
- }
- else {
- console.error('LokiCatalog.setAppKey (set) onerror');
- console.error(request.error);
- }
- };
- })(callback);
- requestPut.onsuccess = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback({ success: true });
- }
- };
- })(callback);
- };
- request.onerror = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback({ success: false });
- }
- else {
- console.error('LokiCatalog.setAppKey (get) onerror');
- console.error(request.error);
- }
- };
- })(callback);
- };
- LokiCatalog.prototype.deleteAppKey = function (id, callback) {
- var transaction = this.db.transaction(['LokiAKV'], 'readwrite');
- var store = transaction.objectStore('LokiAKV');
- var request = store.delete(id);
- request.onsuccess = (function(usercallback) {
- return function(evt) {
- if (typeof(usercallback) === 'function') usercallback({ success: true });
- };
- })(callback);
- request.onerror = (function(usercallback) {
- return function(evt) {
- if (typeof(usercallback) === 'function') {
- usercallback({ success: false });
- }
- else {
- console.error('LokiCatalog.deleteAppKey raised onerror');
- console.error(request.error);
- }
- };
- })(callback);
- };
- LokiCatalog.prototype.getAppKeys = function(app, callback) {
- var transaction = this.db.transaction(['LokiAKV'], 'readonly');
- var store = transaction.objectStore('LokiAKV');
- var index = store.index('app');
- // We want cursor to all values matching our (single) app param
- var singleKeyRange = IDBKeyRange.only(app);
- // To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor()
- var cursor = index.openCursor(singleKeyRange);
- // cursor internally, pushing results into this.data[] and return
- // this.data[] when done (similar to service)
- var localdata = [];
- cursor.onsuccess = (function(data, callback) {
- return function(e) {
- var cursor = e.target.result;
- if (cursor) {
- var currObject = cursor.value;
- data.push(currObject);
- cursor.continue();
- }
- else {
- if (typeof(callback) === 'function') {
- callback(data);
- }
- else {
- console.log(data);
- }
- }
- };
- })(localdata, callback);
- cursor.onerror = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') {
- usercallback(null);
- }
- else {
- console.error('LokiCatalog.getAppKeys raised onerror');
- console.error(e);
- }
- };
- })(callback);
- };
- // Hide 'cursoring' and return array of { id: id, key: key }
- LokiCatalog.prototype.getAllKeys = function (callback) {
- var transaction = this.db.transaction(['LokiAKV'], 'readonly');
- var store = transaction.objectStore('LokiAKV');
- var cursor = store.openCursor();
- var localdata = [];
- cursor.onsuccess = (function(data, callback) {
- return function(e) {
- var cursor = e.target.result;
- if (cursor) {
- var currObject = cursor.value;
- data.push(currObject);
- cursor.continue();
- }
- else {
- if (typeof(callback) === 'function') {
- callback(data);
- }
- else {
- console.log(data);
- }
- }
- };
- })(localdata, callback);
- cursor.onerror = (function(usercallback) {
- return function(e) {
- if (typeof(usercallback) === 'function') usercallback(null);
- };
- })(callback);
- };
- return LokiIndexedAdapter;
- }());
- }));
- },{}],172:[function(require,module,exports){
- (function (process,global){
- /**
- * LokiJS
- * @author Joe Minichino <joe.minichino@gmail.com>
- *
- * A lightweight document oriented javascript database
- */
- (function (root, factory) {
- if (typeof define === 'function' && define.amd) {
- // AMD
- define([], factory);
- } else if (typeof exports === 'object') {
- // CommonJS
- module.exports = factory();
- } else {
- // Browser globals
- root.loki = factory();
- }
- }(this, function () {
- return (function () {
- 'use strict';
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var Utils = {
- copyProperties: function (src, dest) {
- var prop;
- for (prop in src) {
- dest[prop] = src[prop];
- }
- },
- // used to recursively scan hierarchical transform step object for param substitution
- resolveTransformObject: function (subObj, params, depth) {
- var prop,
- pname;
- if (typeof depth !== 'number') {
- depth = 0;
- }
- if (++depth >= 10) return subObj;
- for (prop in subObj) {
- if (typeof subObj[prop] === 'string' && subObj[prop].indexOf("[%lktxp]") === 0) {
- pname = subObj[prop].substring(8);
- if (params.hasOwnProperty(pname)) {
- subObj[prop] = params[pname];
- }
- } else if (typeof subObj[prop] === "object") {
- subObj[prop] = Utils.resolveTransformObject(subObj[prop], params, depth);
- }
- }
- return subObj;
- },
- // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution
- resolveTransformParams: function (transform, params) {
- var idx,
- clonedStep,
- resolvedTransform = [];
- if (typeof params === 'undefined') return transform;
- // iterate all steps in the transform array
- for (idx = 0; idx < transform.length; idx++) {
- // clone transform so our scan/replace can operate directly on cloned transform
- clonedStep = clone(transform[idx], "shallow-recurse-objects");
- resolvedTransform.push(Utils.resolveTransformObject(clonedStep, params));
- }
- return resolvedTransform;
- },
- // By default (if usingDotNotation is false), looks up path in
- // object via `object[path]`
- //
- // If `usingDotNotation` is true, then the path is assumed to
- // represent a nested path. It can be in the form of an array of
- // field names, or a period delimited string. The function will
- // look up the value of object[path[0]], and then call
- // result[path[1]] on the result, etc etc.
- //
- // If `usingDotNotation` is true, this function still supports
- // non nested fields.
- //
- // `usingDotNotation` is a performance optimization. The caller
- // may know that a path is *not* nested. In which case, this
- // function avoids a costly string.split('.')
- //
- // examples:
- // getIn({a: 1}, "a") => 1
- // getIn({a: 1}, "a", true) => 1
- // getIn({a: {b: 1}}, ["a", "b"], true) => 1
- // getIn({a: {b: 1}}, "a.b", true) => 1
- getIn: function (object, path, usingDotNotation) {
- if (object == null) {
- return undefined;
- }
- if (!usingDotNotation) {
- return object[path];
- }
- if (typeof(path) === "string") {
- path = path.split(".");
- }
- if (!Array.isArray(path)) {
- throw new Error("path must be a string or array. Found " + typeof(path));
- }
- var index = 0,
- length = path.length;
- while (object != null && index < length) {
- object = object[path[index++]];
- }
- return (index && index == length) ? object : undefined;
- }
- };
- // wrapping in object to expose to default export for potential user override.
- // warning: overriding these methods will override behavior for all loki db instances in memory.
- // warning: if you use binary indices these comparators should be the same for all inserts/updates/removes.
- var Comparators = {
- aeq: aeqHelper,
- lt: ltHelper,
- gt: gtHelper
- };
- /** Helper function for determining 'loki' abstract equality which is a little more abstract than ==
- * aeqHelper(5, '5') === true
- * aeqHelper(5.0, '5') === true
- * aeqHelper(new Date("1/1/2011"), new Date("1/1/2011")) === true
- * aeqHelper({a:1}, {z:4}) === true (all objects sorted equally)
- * aeqHelper([1, 2, 3], [1, 3]) === false
- * aeqHelper([1, 2, 3], [1, 2, 3]) === true
- * aeqHelper(undefined, null) === true
- */
- function aeqHelper(prop1, prop2) {
- var cv1, cv2, t1, t2;
- if (prop1 === prop2) return true;
- // 'falsy' and Boolean handling
- if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
- // dates and NaN conditions (typed dates before serialization)
- switch (prop1) {
- case undefined: t1 = 1; break;
- case null: t1 = 1; break;
- case false: t1 = 3; break;
- case true: t1 = 4; break;
- case "": t1 = 5; break;
- default: t1 = (prop1 === prop1)?9:0; break;
- }
- switch (prop2) {
- case undefined: t2 = 1; break;
- case null: t2 = 1; break;
- case false: t2 = 3; break;
- case true: t2 = 4; break;
- case "": t2 = 5; break;
- default: t2 = (prop2 === prop2)?9:0; break;
- }
- // one or both is edge case
- if (t1 !== 9 || t2 !== 9) {
- return (t1===t2);
- }
- }
- // Handle 'Number-like' comparisons
- cv1 = Number(prop1);
- cv2 = Number(prop2);
- // if one or both are 'number-like'...
- if (cv1 === cv1 || cv2 === cv2) {
- return (cv1 === cv2);
- }
- // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
- cv1 = prop1.toString();
- cv2 = prop2.toString();
- return (cv1 == cv2);
- }
- /** Helper function for determining 'less-than' conditions for ops, sorting, and binary indices.
- * In the future we might want $lt and $gt ops to use their own functionality/helper.
- * Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we
- * need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another.
- */
- function ltHelper(prop1, prop2, equal) {
- var cv1, cv2, t1, t2;
- // if one of the params is falsy or strictly true or not equal to itself
- // 0, 0.0, "", NaN, null, undefined, not defined, false, true
- if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
- switch (prop1) {
- case undefined: t1 = 1; break;
- case null: t1 = 1; break;
- case false: t1 = 3; break;
- case true: t1 = 4; break;
- case "": t1 = 5; break;
- // if strict equal probably 0 so sort higher, otherwise probably NaN so sort lower than even null
- default: t1 = (prop1 === prop1)?9:0; break;
- }
- switch (prop2) {
- case undefined: t2 = 1; break;
- case null: t2 = 1; break;
- case false: t2 = 3; break;
- case true: t2 = 4; break;
- case "": t2 = 5; break;
- default: t2 = (prop2 === prop2)?9:0; break;
- }
- // one or both is edge case
- if (t1 !== 9 || t2 !== 9) {
- return (t1===t2)?equal:(t1<t2);
- }
- }
- // if both are numbers (string encoded or not), compare as numbers
- cv1 = Number(prop1);
- cv2 = Number(prop2);
- if (cv1 === cv1 && cv2 === cv2) {
- if (cv1 < cv2) return true;
- if (cv1 > cv2) return false;
- return equal;
- }
- if (cv1 === cv1 && cv2 !== cv2) {
- return true;
- }
- if (cv2 === cv2 && cv1 !== cv1) {
- return false;
- }
- if (prop1 < prop2) return true;
- if (prop1 > prop2) return false;
- if (prop1 == prop2) return equal;
- // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
- cv1 = prop1.toString();
- cv2 = prop2.toString();
- if (cv1 < cv2) {
- return true;
- }
- if (cv1 == cv2) {
- return equal;
- }
- return false;
- }
- function gtHelper(prop1, prop2, equal) {
- var cv1, cv2, t1, t2;
- // 'falsy' and Boolean handling
- if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
- switch (prop1) {
- case undefined: t1 = 1; break;
- case null: t1 = 1; break;
- case false: t1 = 3; break;
- case true: t1 = 4; break;
- case "": t1 = 5; break;
- // NaN 0
- default: t1 = (prop1 === prop1)?9:0; break;
- }
- switch (prop2) {
- case undefined: t2 = 1; break;
- case null: t2 = 1; break;
- case false: t2 = 3; break;
- case true: t2 = 4; break;
- case "": t2 = 5; break;
- default: t2 = (prop2 === prop2)?9:0; break;
- }
- // one or both is edge case
- if (t1 !== 9 || t2 !== 9) {
- return (t1===t2)?equal:(t1>t2);
- }
- }
- // if both are numbers (string encoded or not), compare as numbers
- cv1 = Number(prop1);
- cv2 = Number(prop2);
- if (cv1 === cv1 && cv2 === cv2) {
- if (cv1 > cv2) return true;
- if (cv1 < cv2) return false;
- return equal;
- }
- if (cv1 === cv1 && cv2 !== cv2) {
- return false;
- }
- if (cv2 === cv2 && cv1 !== cv1) {
- return true;
- }
- if (prop1 > prop2) return true;
- if (prop1 < prop2) return false;
- if (prop1 == prop2) return equal;
- // not strict equal nor less than nor gt so must be dates or mixed types
- // convert to string and use that to compare
- cv1 = prop1.toString();
- cv2 = prop2.toString();
- if (cv1 > cv2) {
- return true;
- }
- if (cv1 == cv2) {
- return equal;
- }
- return false;
- }
- function sortHelper(prop1, prop2, desc) {
- if (Comparators.aeq(prop1, prop2)) return 0;
- if (Comparators.lt(prop1, prop2, false)) {
- return (desc) ? (1) : (-1);
- }
- if (Comparators.gt(prop1, prop2, false)) {
- return (desc) ? (-1) : (1);
- }
- // not lt, not gt so implied equality-- date compatible
- return 0;
- }
- /**
- * compoundeval() - helper function for compoundsort(), performing individual object comparisons
- *
- * @param {array} properties - array of property names, in order, by which to evaluate sort order
- * @param {object} obj1 - first object to compare
- * @param {object} obj2 - second object to compare
- * @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first
- */
- function compoundeval(properties, obj1, obj2) {
- var res = 0;
- var prop, field, val1, val2, arr, path;
- for (var i = 0, len = properties.length; i < len; i++) {
- prop = properties[i];
- field = prop[0];
- if (~field.indexOf('.')) {
- arr = field.split('.');
- val1 = Utils.getIn(obj1, arr, true);
- val2 = Utils.getIn(obj2, arr, true);
- } else {
- val1 = obj1[field];
- val2 = obj2[field];
- }
- res = sortHelper(val1, val2, prop[1]);
- if (res !== 0) {
- return res;
- }
- }
- return 0;
- }
- /**
- * dotSubScan - helper function used for dot notation queries.
- *
- * @param {object} root - object to traverse
- * @param {array} paths - array of properties to drill into
- * @param {function} fun - evaluation function to test with
- * @param {any} value - comparative value to also pass to (compare) fun
- * @param {number} poffset - index of the item in 'paths' to start the sub-scan from
- */
- function dotSubScan(root, paths, fun, value, poffset) {
- var pathOffset = poffset || 0;
- var path = paths[pathOffset];
- var valueFound = false;
- var element;
- if (typeof root === 'object' && path in root) {
- element = root[path];
- }
- if (pathOffset + 1 >= paths.length) {
- // if we have already expanded out the dot notation,
- // then just evaluate the test function and value on the element
- valueFound = fun(element, value);
- } else if (Array.isArray(element)) {
- for (var index = 0, len = element.length; index < len; index += 1) {
- valueFound = dotSubScan(element[index], paths, fun, value, pathOffset + 1);
- if (valueFound === true) {
- break;
- }
- }
- } else {
- valueFound = dotSubScan(element, paths, fun, value, pathOffset + 1);
- }
- return valueFound;
- }
- function containsCheckFn(a) {
- if (typeof a === 'string' || Array.isArray(a)) {
- return function (b) {
- return a.indexOf(b) !== -1;
- };
- } else if (typeof a === 'object' && a !== null) {
- return function (b) {
- return hasOwnProperty.call(a, b);
- };
- }
- return null;
- }
- function doQueryOp(val, op) {
- for (var p in op) {
- if (hasOwnProperty.call(op, p)) {
- return LokiOps[p](val, op[p]);
- }
- }
- return false;
- }
- var LokiOps = {
- // comparison operators
- // a is the value in the collection
- // b is the query value
- $eq: function (a, b) {
- return a === b;
- },
- // abstract/loose equality
- $aeq: function (a, b) {
- return a == b;
- },
- $ne: function (a, b) {
- // ecma 5 safe test for NaN
- if (b !== b) {
- // ecma 5 test value is not NaN
- return (a === a);
- }
- return a !== b;
- },
- // date equality / loki abstract equality test
- $dteq: function (a, b) {
- return Comparators.aeq(a, b);
- },
- // loki comparisons: return identical unindexed results as indexed comparisons
- $gt: function (a, b) {
- return Comparators.gt(a, b, false);
- },
- $gte: function (a, b) {
- return Comparators.gt(a, b, true);
- },
- $lt: function (a, b) {
- return Comparators.lt(a, b, false);
- },
- $lte: function (a, b) {
- return Comparators.lt(a, b, true);
- },
- // lightweight javascript comparisons
- $jgt: function (a, b) {
- return a > b;
- },
- $jgte: function (a, b) {
- return a >= b;
- },
- $jlt: function (a, b) {
- return a < b;
- },
- $jlte: function (a, b) {
- return a <= b;
- },
- // ex : coll.find({'orderCount': {$between: [10, 50]}});
- $between: function (a, vals) {
- if (a === undefined || a === null) return false;
- return (Comparators.gt(a, vals[0], true) && Comparators.lt(a, vals[1], true));
- },
- $jbetween: function (a, vals) {
- if (a === undefined || a === null) return false;
- return (a >= vals[0] && a <= vals[1]);
- },
- $in: function (a, b) {
- return b.indexOf(a) !== -1;
- },
- $nin: function (a, b) {
- return b.indexOf(a) === -1;
- },
- $keyin: function (a, b) {
- return a in b;
- },
- $nkeyin: function (a, b) {
- return !(a in b);
- },
- $definedin: function (a, b) {
- return b[a] !== undefined;
- },
- $undefinedin: function (a, b) {
- return b[a] === undefined;
- },
- $regex: function (a, b) {
- return b.test(a);
- },
- $containsString: function (a, b) {
- return (typeof a === 'string') && (a.indexOf(b) !== -1);
- },
- $containsNone: function (a, b) {
- return !LokiOps.$containsAny(a, b);
- },
- $containsAny: function (a, b) {
- var checkFn = containsCheckFn(a);
- if (checkFn !== null) {
- return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b));
- }
- return false;
- },
- $contains: function (a, b) {
- var checkFn = containsCheckFn(a);
- if (checkFn !== null) {
- return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b));
- }
- return false;
- },
- $type: function (a, b) {
- var type = typeof a;
- if (type === 'object') {
- if (Array.isArray(a)) {
- type = 'array';
- } else if (a instanceof Date) {
- type = 'date';
- }
- }
- return (typeof b !== 'object') ? (type === b) : doQueryOp(type, b);
- },
- $finite: function(a, b) {
- return (b === isFinite(a));
- },
- $size: function (a, b) {
- if (Array.isArray(a)) {
- return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
- }
- return false;
- },
- $len: function (a, b) {
- if (typeof a === 'string') {
- return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
- }
- return false;
- },
- $where: function (a, b) {
- return b(a) === true;
- },
- // field-level logical operators
- // a is the value in the collection
- // b is the nested query operation (for '$not')
- // or an array of nested query operations (for '$and' and '$or')
- $not: function (a, b) {
- return !doQueryOp(a, b);
- },
- $and: function (a, b) {
- for (var idx = 0, len = b.length; idx < len; idx += 1) {
- if (!doQueryOp(a, b[idx])) {
- return false;
- }
- }
- return true;
- },
- $or: function (a, b) {
- for (var idx = 0, len = b.length; idx < len; idx += 1) {
- if (doQueryOp(a, b[idx])) {
- return true;
- }
- }
- return false;
- },
- $exists: function (a, b) {
- if (b) {
- return a !== undefined;
- } else {
- return a === undefined;
- }
- }
- };
- // if an op is registered in this object, our 'calculateRange' can use it with our binary indices.
- // if the op is registered to a function, we will run that function/op as a 2nd pass filter on results.
- // those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare.
- var indexedOps = {
- $eq: LokiOps.$eq,
- $aeq: true,
- $dteq: true,
- $gt: true,
- $gte: true,
- $lt: true,
- $lte: true,
- $in: true,
- $between: true
- };
- function clone(data, method) {
- if (data === null || data === undefined) {
- return null;
- }
- var cloneMethod = method || 'parse-stringify',
- cloned;
- switch (cloneMethod) {
- case "parse-stringify":
- cloned = JSON.parse(JSON.stringify(data));
- break;
- case "jquery-extend-deep":
- cloned = jQuery.extend(true, {}, data);
- break;
- case "shallow":
- // more compatible method for older browsers
- cloned = Object.create(data.constructor.prototype);
- Object.keys(data).map(function (i) {
- cloned[i] = data[i];
- });
- break;
- case "shallow-assign":
- // should be supported by newer environments/browsers
- cloned = Object.create(data.constructor.prototype);
- Object.assign(cloned, data);
- break;
- case "shallow-recurse-objects":
- // shallow clone top level properties
- cloned = clone(data, "shallow");
- var keys = Object.keys(data);
- // for each of the top level properties which are object literals, recursively shallow copy
- keys.forEach(function(key) {
- if (typeof data[key] === "object" && data[key].constructor.name === "Object") {
- cloned[key] = clone(data[key], "shallow-recurse-objects");
- }else if(Array.isArray(data[key])){
- cloned[key] = cloneObjectArray(data[key], "shallow-recurse-objects");
- }
- });
- break;
- default:
- break;
- }
- return cloned;
- }
- function cloneObjectArray(objarray, method) {
- if (method == "parse-stringify") {
- return clone(objarray, method);
- }
- var result = [];
- for (var i = 0, len = objarray.length; i < len; i++) {
- result[i] = clone(objarray[i], method);
- }
- return result;
- }
- function localStorageAvailable() {
- try {
- return (window && window.localStorage !== undefined && window.localStorage !== null);
- } catch (e) {
- return false;
- }
- }
- /**
- * LokiEventEmitter is a minimalist version of EventEmitter. It enables any
- * constructor that inherits EventEmitter to emit events and trigger
- * listeners that have been added to the event through the on(event, callback) method
- *
- * @constructor LokiEventEmitter
- */
- function LokiEventEmitter() {}
- /**
- * @prop {hashmap} events - a hashmap, with each property being an array of callbacks
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.events = {};
- /**
- * @prop {boolean} asyncListeners - boolean determines whether or not the callbacks associated with each event
- * should happen in an async fashion or not
- * Default is false, which means events are synchronous
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.asyncListeners = false;
- /**
- * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event
- * @param {string|string[]} eventName - the name(s) of the event(s) to listen to
- * @param {function} listener - callback function of listener to attach
- * @returns {int} the index of the callback in the array of listeners for a particular event
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.on = function (eventName, listener) {
- var event;
- var self = this;
- if (Array.isArray(eventName)) {
- eventName.forEach(function(currentEventName) {
- self.on(currentEventName, listener);
- });
- return listener;
- }
- event = this.events[eventName];
- if (!event) {
- event = this.events[eventName] = [];
- }
- event.push(listener);
- return listener;
- };
- /**
- * emit(eventName, data) - emits a particular event
- * with the option of passing optional parameters which are going to be processed by the callback
- * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters)
- * @param {string} eventName - the name of the event
- * @param {object=} data - optional object passed with the event
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.emit = function (eventName) {
- var self = this;
- var selfArgs = Array.prototype.slice.call(arguments, 1);
- if (eventName && this.events[eventName]) {
- this.events[eventName].forEach(function (listener) {
- if (self.asyncListeners) {
- setTimeout(function () {
- listener.apply(self, selfArgs);
- }, 1);
- } else {
- listener.apply(self, selfArgs);
- }
- });
- } else {
- throw new Error('No event ' + eventName + ' defined');
- }
- };
- /**
- * Alias of LokiEventEmitter.prototype.on
- * addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event
- * @param {string|string[]} eventName - the name(s) of the event(s) to listen to
- * @param {function} listener - callback function of listener to attach
- * @returns {int} the index of the callback in the array of listeners for a particular event
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.addListener = LokiEventEmitter.prototype.on;
- /**
- * removeListener() - removes the listener at position 'index' from the event 'eventName'
- * @param {string|string[]} eventName - the name(s) of the event(s) which the listener is attached to
- * @param {function} listener - the listener callback function to remove from emitter
- * @memberof LokiEventEmitter
- */
- LokiEventEmitter.prototype.removeListener = function (eventName, listener) {
- var self = this;
- if (Array.isArray(eventName)) {
- eventName.forEach(function(currentEventName) {
- self.removeListener(currentEventName, listener);
- });
- return;
- }
- if (this.events[eventName]) {
- var listeners = this.events[eventName];
- listeners.splice(listeners.indexOf(listener), 1);
- }
- };
- /**
- * Loki: The main database class
- * @constructor Loki
- * @implements LokiEventEmitter
- * @param {string} filename - name of the file to be saved to
- * @param {object=} options - (Optional) config options object
- * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
- * @param {boolean} [options.verbose=false] - enable console output
- * @param {boolean} [options.autosave=false] - enables autosave
- * @param {int} [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty)
- * @param {boolean} [options.autoload=false] - enables autoload on loki instantiation
- * @param {function} options.autoloadCallback - user callback called after database load
- * @param {adapter} options.adapter - an instance of a loki persistence adapter
- * @param {string} [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured']
- * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization
- * @param {boolean} [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations
- and guaranteeing proper serialization of the calls.
- */
- function Loki(filename, options) {
- this.filename = filename || 'loki.db';
- this.collections = [];
- // persist version of code which created the database to the database.
- // could use for upgrade scenarios
- this.databaseVersion = 1.5;
- this.engineVersion = 1.5;
- // autosave support (disabled by default)
- // pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave
- this.autosave = false;
- this.autosaveInterval = 5000;
- this.autosaveHandle = null;
- this.throttledSaves = true;
- this.options = {};
- // currently keeping persistenceMethod and persistenceAdapter as loki level properties that
- // will not or cannot be deserialized. You are required to configure persistence every time
- // you instantiate a loki object (or use default environment detection) in order to load the database anyways.
- // persistenceMethod could be 'fs', 'localStorage', or 'adapter'
- // this is optional option param, otherwise environment detection will be used
- // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option.
- this.persistenceMethod = null;
- // retain reference to optional (non-serializable) persistenceAdapter 'instance'
- this.persistenceAdapter = null;
- // flags used to throttle saves
- this.throttledSavePending = false;
- this.throttledCallbacks = [];
- // enable console output if verbose flag is set (disabled by default)
- this.verbose = options && options.hasOwnProperty('verbose') ? options.verbose : false;
- this.events = {
- 'init': [],
- 'loaded': [],
- 'flushChanges': [],
- 'close': [],
- 'changes': [],
- 'warning': []
- };
- var getENV = function () {
- if (typeof global !== 'undefined' && (global.android || global.NSObject)) {
- // If no adapter assume nativescript which needs adapter to be passed manually
- return 'NATIVESCRIPT'; //nativescript
- }
- if (typeof window === 'undefined') {
- return 'NODEJS';
- }
- if (typeof global !== 'undefined' && global.window && typeof process !== 'undefined') {
- return 'NODEJS'; //node-webkit
- }
- if (typeof document !== 'undefined') {
- if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) {
- return 'CORDOVA';
- }
- return 'BROWSER';
- }
- return 'CORDOVA';
- };
- // refactored environment detection due to invalid detection for browser environments.
- // if they do not specify an options.env we want to detect env rather than default to nodejs.
- // currently keeping two properties for similar thing (options.env and options.persistenceMethod)
- // might want to review whether we can consolidate.
- if (options && options.hasOwnProperty('env')) {
- this.ENV = options.env;
- } else {
- this.ENV = getENV();
- }
- // not sure if this is necessary now that i have refactored the line above
- if (this.ENV === 'undefined') {
- this.ENV = 'NODEJS';
- }
- this.configureOptions(options, true);
- this.on('init', this.clearChanges);
- }
- // db class is an EventEmitter
- Loki.prototype = new LokiEventEmitter();
- Loki.prototype.constructor = Loki;
- // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter.
- // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference.
- Loki.prototype.getIndexedAdapter = function () {
- var adapter;
- if (typeof require === 'function') {
- adapter = require("./loki-indexed-adapter.js");
- }
- return adapter;
- };
- /**
- * Allows reconfiguring database options
- *
- * @param {object} options - configuration options to apply to loki db object
- * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
- * @param {boolean} options.verbose - enable console output (default is 'false')
- * @param {boolean} options.autosave - enables autosave
- * @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty)
- * @param {boolean} options.autoload - enables autoload on loki instantiation
- * @param {function} options.autoloadCallback - user callback called after database load
- * @param {adapter} options.adapter - an instance of a loki persistence adapter
- * @param {string} options.serializationMethod - ['normal', 'pretty', 'destructured']
- * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization
- * @param {boolean} initialConfig - (internal) true is passed when loki ctor is invoking
- * @memberof Loki
- */
- Loki.prototype.configureOptions = function (options, initialConfig) {
- var defaultPersistence = {
- 'NODEJS': 'fs',
- 'BROWSER': 'localStorage',
- 'CORDOVA': 'localStorage',
- 'MEMORY': 'memory'
- },
- persistenceMethods = {
- 'fs': LokiFsAdapter,
- 'localStorage': LokiLocalStorageAdapter,
- 'memory': LokiMemoryAdapter
- };
- this.options = {};
- this.persistenceMethod = null;
- // retain reference to optional persistence adapter 'instance'
- // currently keeping outside options because it can't be serialized
- this.persistenceAdapter = null;
- // process the options
- if (typeof (options) !== 'undefined') {
- this.options = options;
- if (this.options.hasOwnProperty('persistenceMethod')) {
- // check if the specified persistence method is known
- if (typeof (persistenceMethods[options.persistenceMethod]) == 'function') {
- this.persistenceMethod = options.persistenceMethod;
- this.persistenceAdapter = new persistenceMethods[options.persistenceMethod]();
- }
- // should be throw an error here, or just fall back to defaults ??
- }
- // if user passes adapter, set persistence mode to adapter and retain persistence adapter instance
- if (this.options.hasOwnProperty('adapter')) {
- this.persistenceMethod = 'adapter';
- this.persistenceAdapter = options.adapter;
- this.options.adapter = null;
- }
- // if they want to load database on loki instantiation, now is a good time to load... after adapter set and before possible autosave initiation
- if (options.autoload && initialConfig) {
- // for autoload, let the constructor complete before firing callback
- var self = this;
- setTimeout(function () {
- self.loadDatabase(options, options.autoloadCallback);
- }, 1);
- }
- if (this.options.hasOwnProperty('autosaveInterval')) {
- this.autosaveDisable();
- this.autosaveInterval = parseInt(this.options.autosaveInterval, 10);
- }
- if (this.options.hasOwnProperty('autosave') && this.options.autosave) {
- this.autosaveDisable();
- this.autosave = true;
- if (this.options.hasOwnProperty('autosaveCallback')) {
- this.autosaveEnable(options, options.autosaveCallback);
- } else {
- this.autosaveEnable();
- }
- }
- if (this.options.hasOwnProperty('throttledSaves')) {
- this.throttledSaves = this.options.throttledSaves;
- }
- } // end of options processing
- // ensure defaults exists for options which were not set
- if (!this.options.hasOwnProperty('serializationMethod')) {
- this.options.serializationMethod = 'normal';
- }
- // ensure passed or default option exists
- if (!this.options.hasOwnProperty('destructureDelimiter')) {
- this.options.destructureDelimiter = '$<\n';
- }
- // if by now there is no adapter specified by user nor derived from persistenceMethod: use sensible defaults
- if (this.persistenceAdapter === null) {
- this.persistenceMethod = defaultPersistence[this.ENV];
- if (this.persistenceMethod) {
- this.persistenceAdapter = new persistenceMethods[this.persistenceMethod]();
- }
- }
- };
- /**
- * Copies 'this' database into a new Loki instance. Object references are shared to make lightweight.
- *
- * @param {object} options - apply or override collection level settings
- * @param {bool} options.removeNonSerializable - nulls properties not safe for serialization.
- * @memberof Loki
- */
- Loki.prototype.copy = function(options) {
- // in case running in an environment without accurate environment detection, pass 'NA'
- var databaseCopy = new Loki(this.filename, { env: "NA" });
- var clen, idx;
- options = options || {};
- // currently inverting and letting loadJSONObject do most of the work
- databaseCopy.loadJSONObject(this, { retainDirtyFlags: true });
- // since our JSON serializeReplacer is not invoked for reference database adapters, this will let us mimic
- if(options.hasOwnProperty("removeNonSerializable") && options.removeNonSerializable === true) {
- databaseCopy.autosaveHandle = null;
- databaseCopy.persistenceAdapter = null;
- clen = databaseCopy.collections.length;
- for (idx=0; idx<clen; idx++) {
- databaseCopy.collections[idx].constraints = null;
- databaseCopy.collections[idx].ttl = null;
- }
- }
- return databaseCopy;
- };
- /**
- * Adds a collection to the database.
- * @param {string} name - name of collection to add
- * @param {object=} options - (optional) options to configure collection with.
- * @param {array=} [options.unique=[]] - array of property names to define unique constraints for
- * @param {array=} [options.exact=[]] - array of property names to define exact constraints for
- * @param {array=} [options.indices=[]] - array property names to define binary indexes for
- * @param {boolean} [options.asyncListeners=false] - whether listeners are called asynchronously
- * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
- * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes Api
- * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
- * @param {boolean} [options.autoupdate=false] - use Object.observe to update objects automatically
- * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
- * @param {string} [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow, 'shallow-assign'
- * @param {int=} options.ttl - age of document (in ms.) before document is considered aged/stale.
- * @param {int=} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
- * @returns {Collection} a reference to the collection which was just added
- * @memberof Loki
- */
- Loki.prototype.addCollection = function (name, options) {
- var i,
- len = this.collections.length;
- if (options && options.disableMeta === true) {
- if (options.disableChangesApi === false) {
- throw new Error("disableMeta option cannot be passed as true when disableChangesApi is passed as false");
- }
- if (options.disableDeltaChangesApi === false) {
- throw new Error("disableMeta option cannot be passed as true when disableDeltaChangesApi is passed as false");
- }
- if (typeof options.ttl === "number" && options.ttl > 0) {
- throw new Error("disableMeta option cannot be passed as true when ttl is enabled");
- }
- }
- for (i = 0; i < len; i += 1) {
- if (this.collections[i].name === name) {
- return this.collections[i];
- }
- }
- var collection = new Collection(name, options);
- this.collections.push(collection);
- if (this.verbose)
- collection.console = console;
- return collection;
- };
- Loki.prototype.loadCollection = function (collection) {
- if (!collection.name) {
- throw new Error('Collection must have a name property to be loaded');
- }
- this.collections.push(collection);
- };
- /**
- * Retrieves reference to a collection by name.
- * @param {string} collectionName - name of collection to look up
- * @returns {Collection} Reference to collection in database by that name, or null if not found
- * @memberof Loki
- */
- Loki.prototype.getCollection = function (collectionName) {
- var i,
- len = this.collections.length;
- for (i = 0; i < len; i += 1) {
- if (this.collections[i].name === collectionName) {
- return this.collections[i];
- }
- }
- // no such collection
- this.emit('warning', 'collection ' + collectionName + ' not found');
- return null;
- };
- /**
- * Renames an existing loki collection
- * @param {string} oldName - name of collection to rename
- * @param {string} newName - new name of collection
- * @returns {Collection} reference to the newly renamed collection
- * @memberof Loki
- */
- Loki.prototype.renameCollection = function (oldName, newName) {
- var c = this.getCollection(oldName);
- if (c) {
- c.name = newName;
- }
- return c;
- };
- /**
- * Returns a list of collections in the database.
- * @returns {object[]} array of objects containing 'name', 'type', and 'count' properties.
- * @memberof Loki
- */
- Loki.prototype.listCollections = function () {
- var i = this.collections.length,
- colls = [];
- while (i--) {
- colls.push({
- name: this.collections[i].name,
- type: this.collections[i].objType,
- count: this.collections[i].data.length
- });
- }
- return colls;
- };
- /**
- * Removes a collection from the database.
- * @param {string} collectionName - name of collection to remove
- * @memberof Loki
- */
- Loki.prototype.removeCollection = function (collectionName) {
- var i,
- len = this.collections.length;
- for (i = 0; i < len; i += 1) {
- if (this.collections[i].name === collectionName) {
- var tmpcol = new Collection(collectionName, {});
- var curcol = this.collections[i];
- for (var prop in curcol) {
- if (curcol.hasOwnProperty(prop) && tmpcol.hasOwnProperty(prop)) {
- curcol[prop] = tmpcol[prop];
- }
- }
- this.collections.splice(i, 1);
- return;
- }
- }
- };
- Loki.prototype.getName = function () {
- return this.name;
- };
- /**
- * serializeReplacer - used to prevent certain properties from being serialized
- *
- */
- Loki.prototype.serializeReplacer = function (key, value) {
- switch (key) {
- case 'autosaveHandle':
- case 'persistenceAdapter':
- case 'constraints':
- case 'ttl':
- return null;
- case 'throttledSavePending':
- case 'throttledCallbacks':
- return undefined;
- default:
- return value;
- }
- };
- /**
- * Serialize database to a string which can be loaded via {@link Loki#loadJSON}
- *
- * @returns {string} Stringified representation of the loki database.
- * @memberof Loki
- */
- Loki.prototype.serialize = function (options) {
- options = options || {};
- if (!options.hasOwnProperty("serializationMethod")) {
- options.serializationMethod = this.options.serializationMethod;
- }
- switch(options.serializationMethod) {
- case "normal": return JSON.stringify(this, this.serializeReplacer);
- case "pretty": return JSON.stringify(this, this.serializeReplacer, 2);
- case "destructured": return this.serializeDestructured(); // use default options
- default: return JSON.stringify(this, this.serializeReplacer);
- }
- };
- // alias of serialize
- Loki.prototype.toJson = Loki.prototype.serialize;
- /**
- * Database level destructured JSON serialization routine to allow alternate serialization methods.
- * Internally, Loki supports destructuring via loki "serializationMethod' option and
- * the optional LokiPartitioningAdapter class. It is also available if you wish to do
- * your own structured persistence or data exchange.
- *
- * @param {object=} options - output format options for use externally to loki
- * @param {bool=} options.partitioned - (default: false) whether db and each collection are separate
- * @param {int=} options.partition - can be used to only output an individual collection or db (-1)
- * @param {bool=} options.delimited - (default: true) whether subitems are delimited or subarrays
- * @param {string=} options.delimiter - override default delimiter
- *
- * @returns {string|array} A custom, restructured aggregation of independent serializations.
- * @memberof Loki
- */
- Loki.prototype.serializeDestructured = function(options) {
- var idx, sidx, result, resultlen;
- var reconstruct = [];
- var dbcopy;
- options = options || {};
- if (!options.hasOwnProperty("partitioned")) {
- options.partitioned = false;
- }
- if (!options.hasOwnProperty("delimited")) {
- options.delimited = true;
- }
- if (!options.hasOwnProperty("delimiter")) {
- options.delimiter = this.options.destructureDelimiter;
- }
- // 'partitioned' along with 'partition' of 0 or greater is a request for single collection serialization
- if (options.partitioned === true && options.hasOwnProperty("partition") && options.partition >= 0) {
- return this.serializeCollection({
- delimited: options.delimited,
- delimiter: options.delimiter,
- collectionIndex: options.partition
- });
- }
- // not just an individual collection, so we will need to serialize db container via shallow copy
- dbcopy = new Loki(this.filename);
- dbcopy.loadJSONObject(this);
- for(idx=0; idx < dbcopy.collections.length; idx++) {
- dbcopy.collections[idx].data = [];
- }
- // if we -only- wanted the db container portion, return it now
- if (options.partitioned === true && options.partition === -1) {
- // since we are deconstructing, override serializationMethod to normal for here
- return dbcopy.serialize({
- serializationMethod: "normal"
- });
- }
- // at this point we must be deconstructing the entire database
- // start by pushing db serialization into first array element
- reconstruct.push(dbcopy.serialize({
- serializationMethod: "normal"
- }));
- dbcopy = null;
- // push collection data into subsequent elements
- for(idx=0; idx < this.collections.length; idx++) {
- result = this.serializeCollection({
- delimited: options.delimited,
- delimiter: options.delimiter,
- collectionIndex: idx
- });
- // NDA : Non-Delimited Array : one iterable concatenated array with empty string collection partitions
- if (options.partitioned === false && options.delimited === false) {
- if (!Array.isArray(result)) {
- throw new Error("a nondelimited, non partitioned collection serialization did not return an expected array");
- }
- // Array.concat would probably duplicate memory overhead for copying strings.
- // Instead copy each individually, and clear old value after each copy.
- // Hopefully this will allow g.c. to reduce memory pressure, if needed.
- resultlen = result.length;
- for (sidx=0; sidx < resultlen; sidx++) {
- reconstruct.push(result[sidx]);
- result[sidx] = null;
- }
- reconstruct.push("");
- }
- else {
- reconstruct.push(result);
- }
- }
- // Reconstruct / present results according to four combinations : D, DA, NDA, NDAA
- if (options.partitioned) {
- // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true }
- // useful for simple future adaptations of existing persistence adapters to save collections separately
- if (options.delimited) {
- return reconstruct;
- }
- // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false }
- // This format might be the most versatile for 'rolling your own' partitioned sync or save.
- // Memory overhead can be reduced by specifying a specific partition, but at this code path they did not, so its all.
- else {
- return reconstruct;
- }
- }
- else {
- // D : one big Delimited string { partitioned: false, delimited : true }
- // This is the method Loki will use internally if 'destructured'.
- // Little memory overhead improvements but does not require multiple asynchronous adapter call scheduling
- if (options.delimited) {
- // indicate no more collections
- reconstruct.push("");
- return reconstruct.join(options.delimiter);
- }
- // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false }
- // This format might be best candidate for custom synchronous syncs or saves
- else {
- // indicate no more collections
- reconstruct.push("");
- return reconstruct;
- }
- }
- reconstruct.push("");
- return reconstruct.join(delim);
- };
- /**
- * Collection level utility method to serialize a collection in a 'destructured' format
- *
- * @param {object=} options - used to determine output of method
- * @param {int} options.delimited - whether to return single delimited string or an array
- * @param {string} options.delimiter - (optional) if delimited, this is delimiter to use
- * @param {int} options.collectionIndex - specify which collection to serialize data for
- *
- * @returns {string|array} A custom, restructured aggregation of independent serializations for a single collection.
- * @memberof Loki
- */
- Loki.prototype.serializeCollection = function(options) {
- var doccount,
- docidx,
- resultlines = [];
- options = options || {};
- if (!options.hasOwnProperty("delimited")) {
- options.delimited = true;
- }
- if (!options.hasOwnProperty("collectionIndex")) {
- throw new Error("serializeCollection called without 'collectionIndex' option");
- }
- doccount = this.collections[options.collectionIndex].data.length;
- resultlines = [];
- for(docidx=0; docidx<doccount; docidx++) {
- resultlines.push(JSON.stringify(this.collections[options.collectionIndex].data[docidx]));
- }
- // D and DA
- if (options.delimited) {
- // indicate no more documents in collection (via empty delimited string)
- resultlines.push("");
- return resultlines.join(options.delimiter);
- }
- else {
- // NDAA and NDA
- return resultlines;
- }
- };
- /**
- * Database level destructured JSON deserialization routine to minimize memory overhead.
- * Internally, Loki supports destructuring via loki "serializationMethod' option and
- * the optional LokiPartitioningAdapter class. It is also available if you wish to do
- * your own structured persistence or data exchange.
- *
- * @param {string|array} destructuredSource - destructured json or array to deserialize from
- * @param {object=} options - source format options
- * @param {bool=} [options.partitioned=false] - whether db and each collection are separate
- * @param {int=} options.partition - can be used to deserialize only a single partition
- * @param {bool=} [options.delimited=true] - whether subitems are delimited or subarrays
- * @param {string=} options.delimiter - override default delimiter
- *
- * @returns {object|array} An object representation of the deserialized database, not yet applied to 'this' db or document array
- * @memberof Loki
- */
- Loki.prototype.deserializeDestructured = function(destructuredSource, options) {
- var workarray=[];
- var len, cdb;
- var idx, collIndex=0, collCount, lineIndex=1, done=false;
- var currLine, currObject;
- options = options || {};
- if (!options.hasOwnProperty("partitioned")) {
- options.partitioned = false;
- }
- if (!options.hasOwnProperty("delimited")) {
- options.delimited = true;
- }
- if (!options.hasOwnProperty("delimiter")) {
- options.delimiter = this.options.destructureDelimiter;
- }
- // Partitioned
- // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true }
- // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false }
- // -or- single partition
- if (options.partitioned) {
- // handle single partition
- if (options.hasOwnProperty('partition')) {
- // db only
- if (options.partition === -1) {
- cdb = JSON.parse(destructuredSource[0]);
- return cdb;
- }
- // single collection, return doc array
- return this.deserializeCollection(destructuredSource[options.partition+1], options);
- }
- // Otherwise we are restoring an entire partitioned db
- cdb = JSON.parse(destructuredSource[0]);
- collCount = cdb.collections.length;
- for(collIndex=0; collIndex<collCount; collIndex++) {
- // attach each collection docarray to container collection data, add 1 to collection array index since db is at 0
- cdb.collections[collIndex].data = this.deserializeCollection(destructuredSource[collIndex+1], options);
- }
- return cdb;
- }
- // Non-Partitioned
- // D : one big Delimited string { partitioned: false, delimited : true }
- // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false }
- // D
- if (options.delimited) {
- workarray = destructuredSource.split(options.delimiter);
- destructuredSource = null; // lower memory pressure
- len = workarray.length;
- if (len === 0) {
- return null;
- }
- }
- // NDA
- else {
- workarray = destructuredSource;
- }
- // first line is database and collection shells
- cdb = JSON.parse(workarray[0]);
- collCount = cdb.collections.length;
- workarray[0] = null;
- while (!done) {
- currLine = workarray[lineIndex];
- // empty string indicates either end of collection or end of file
- if (workarray[lineIndex] === "") {
- // if no more collections to load into, we are done
- if (++collIndex > collCount) {
- done = true;
- }
- }
- else {
- currObject = JSON.parse(workarray[lineIndex]);
- cdb.collections[collIndex].data.push(currObject);
- }
- // lower memory pressure and advance iterator
- workarray[lineIndex++] = null;
- }
- return cdb;
- };
- /**
- * Collection level utility function to deserializes a destructured collection.
- *
- * @param {string|array} destructuredSource - destructured representation of collection to inflate
- * @param {object=} options - used to describe format of destructuredSource input
- * @param {int=} [options.delimited=false] - whether source is delimited string or an array
- * @param {string=} options.delimiter - if delimited, this is delimiter to use (if other than default)
- *
- * @returns {array} an array of documents to attach to collection.data.
- * @memberof Loki
- */
- Loki.prototype.deserializeCollection = function(destructuredSource, options) {
- var workarray=[];
- var idx, len;
- options = options || {};
- if (!options.hasOwnProperty("partitioned")) {
- options.partitioned = false;
- }
- if (!options.hasOwnProperty("delimited")) {
- options.delimited = true;
- }
- if (!options.hasOwnProperty("delimiter")) {
- options.delimiter = this.options.destructureDelimiter;
- }
- if (options.delimited) {
- workarray = destructuredSource.split(options.delimiter);
- workarray.pop();
- }
- else {
- workarray = destructuredSource;
- }
- len = workarray.length;
- for (idx=0; idx < len; idx++) {
- workarray[idx] = JSON.parse(workarray[idx]);
- }
- return workarray;
- };
- /**
- * Inflates a loki database from a serialized JSON string
- *
- * @param {string} serializedDb - a serialized loki database string
- * @param {object=} options - apply or override collection level settings
- * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved
- * @memberof Loki
- */
- Loki.prototype.loadJSON = function (serializedDb, options) {
- var dbObject;
- if (serializedDb.length === 0) {
- dbObject = {};
- } else {
- // using option defined in instantiated db not what was in serialized db
- switch (this.options.serializationMethod) {
- case "normal":
- case "pretty": dbObject = JSON.parse(serializedDb); break;
- case "destructured": dbObject = this.deserializeDestructured(serializedDb); break;
- default: dbObject = JSON.parse(serializedDb); break;
- }
- }
- this.loadJSONObject(dbObject, options);
- };
- /**
- * Inflates a loki database from a JS object
- *
- * @param {object} dbObject - a serialized loki database string
- * @param {object=} options - apply or override collection level settings
- * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved
- * @memberof Loki
- */
- Loki.prototype.loadJSONObject = function (dbObject, options) {
- var i = 0,
- len = dbObject.collections ? dbObject.collections.length : 0,
- coll,
- copyColl,
- clen,
- j,
- loader,
- collObj;
- this.name = dbObject.name;
- // restore save throttled boolean only if not defined in options
- if (dbObject.hasOwnProperty('throttledSaves') && options && !options.hasOwnProperty('throttledSaves')) {
- this.throttledSaves = dbObject.throttledSaves;
- }
- this.collections = [];
- function makeLoader(coll) {
- var collOptions = options[coll.name];
- var inflater;
- if(collOptions.proto) {
- inflater = collOptions.inflate || Utils.copyProperties;
- return function(data) {
- var collObj = new(collOptions.proto)();
- inflater(data, collObj);
- return collObj;
- };
- }
- return collOptions.inflate;
- }
- for (i; i < len; i += 1) {
- coll = dbObject.collections[i];
- copyColl = this.addCollection(coll.name, { disableChangesApi: coll.disableChangesApi, disableDeltaChangesApi: coll.disableDeltaChangesApi, disableMeta: coll.disableMeta });
- copyColl.adaptiveBinaryIndices = coll.hasOwnProperty('adaptiveBinaryIndices')?(coll.adaptiveBinaryIndices === true): false;
- copyColl.transactional = coll.transactional;
- copyColl.asyncListeners = coll.asyncListeners;
- copyColl.cloneObjects = coll.cloneObjects;
- copyColl.cloneMethod = coll.cloneMethod || "parse-stringify";
- copyColl.autoupdate = coll.autoupdate;
- copyColl.changes = coll.changes;
- if (options && options.retainDirtyFlags === true) {
- copyColl.dirty = coll.dirty;
- }
- else {
- copyColl.dirty = false;
- }
- // load each element individually
- clen = coll.data.length;
- j = 0;
- if (options && options.hasOwnProperty(coll.name)) {
- loader = makeLoader(coll);
- for (j; j < clen; j++) {
- collObj = loader(coll.data[j]);
- copyColl.data[j] = collObj;
- copyColl.addAutoUpdateObserver(collObj);
- }
- } else {
- for (j; j < clen; j++) {
- copyColl.data[j] = coll.data[j];
- copyColl.addAutoUpdateObserver(copyColl.data[j]);
- }
- }
- copyColl.maxId = (typeof coll.maxId === 'undefined') ? 0 : coll.maxId;
- copyColl.idIndex = coll.idIndex;
- if (typeof (coll.binaryIndices) !== 'undefined') {
- copyColl.binaryIndices = coll.binaryIndices;
- }
- if (typeof coll.transforms !== 'undefined') {
- copyColl.transforms = coll.transforms;
- }
- copyColl.ensureId();
- // regenerate unique indexes
- copyColl.uniqueNames = [];
- if (coll.hasOwnProperty("uniqueNames")) {
- copyColl.uniqueNames = coll.uniqueNames;
- for (j = 0; j < copyColl.uniqueNames.length; j++) {
- copyColl.ensureUniqueIndex(copyColl.uniqueNames[j]);
- }
- }
- // in case they are loading a database created before we added dynamic views, handle undefined
- if (typeof (coll.DynamicViews) === 'undefined') continue;
- // reinflate DynamicViews and attached Resultsets
- for (var idx = 0; idx < coll.DynamicViews.length; idx++) {
- var colldv = coll.DynamicViews[idx];
- var dv = copyColl.addDynamicView(colldv.name, colldv.options);
- dv.resultdata = colldv.resultdata;
- dv.resultsdirty = colldv.resultsdirty;
- dv.filterPipeline = colldv.filterPipeline;
- dv.sortCriteria = colldv.sortCriteria;
- dv.sortFunction = null;
- dv.sortDirty = colldv.sortDirty;
- dv.resultset.filteredrows = colldv.resultset.filteredrows;
- dv.resultset.filterInitialized = colldv.resultset.filterInitialized;
- dv.rematerialize({
- removeWhereFilters: true
- });
- }
- // Upgrade Logic for binary index refactoring at version 1.5
- if (dbObject.databaseVersion < 1.5) {
- // rebuild all indices
- copyColl.ensureAllIndexes(true);
- copyColl.dirty = true;
- }
- }
- };
- /**
- * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer.
- * Does not actually destroy the db.
- *
- * @param {function=} callback - (Optional) if supplied will be registered with close event before emitting.
- * @memberof Loki
- */
- Loki.prototype.close = function (callback) {
- // for autosave scenarios, we will let close perform final save (if dirty)
- // For web use, you might call from window.onbeforeunload to shutdown database, saving pending changes
- if (this.autosave) {
- this.autosaveDisable();
- if (this.autosaveDirty()) {
- this.saveDatabase(callback);
- callback = undefined;
- }
- }
- if (callback) {
- this.on('close', callback);
- }
- this.emit('close');
- };
- /**-------------------------+
- | Changes API |
- +--------------------------*/
- /**
- * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session,
- * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db)
- */
- /**
- * (Changes API) : takes all the changes stored in each
- * collection and creates a single array for the entire database. If an array of names
- * of collections is passed then only the included collections will be tracked.
- *
- * @param {array=} optional array of collection names. No arg means all collections are processed.
- * @returns {array} array of changes
- * @see private method createChange() in Collection
- * @memberof Loki
- */
- Loki.prototype.generateChangesNotification = function (arrayOfCollectionNames) {
- function getCollName(coll) {
- return coll.name;
- }
- var changes = [],
- selectedCollections = arrayOfCollectionNames || this.collections.map(getCollName);
- this.collections.forEach(function (coll) {
- if (selectedCollections.indexOf(getCollName(coll)) !== -1) {
- changes = changes.concat(coll.getChanges());
- }
- });
- return changes;
- };
- /**
- * (Changes API) - stringify changes for network transmission
- * @returns {string} string representation of the changes
- * @memberof Loki
- */
- Loki.prototype.serializeChanges = function (collectionNamesArray) {
- return JSON.stringify(this.generateChangesNotification(collectionNamesArray));
- };
- /**
- * (Changes API) : clears all the changes in all collections.
- * @memberof Loki
- */
- Loki.prototype.clearChanges = function () {
- this.collections.forEach(function (coll) {
- if (coll.flushChanges) {
- coll.flushChanges();
- }
- });
- };
- /*------------------+
- | PERSISTENCE |
- -------------------*/
- /** there are two build in persistence adapters for internal use
- * fs for use in Nodejs type environments
- * localStorage for use in browser environment
- * defined as helper classes here so its easy and clean to use
- */
- /**
- * In in-memory persistence adapter for an in-memory database.
- * This simple 'key/value' adapter is intended for unit testing and diagnostics.
- *
- * @param {object=} options - memory adapter options
- * @param {boolean} [options.asyncResponses=false] - whether callbacks are invoked asynchronously
- * @param {int} [options.asyncTimeout=50] - timeout in ms to queue callbacks
- * @constructor LokiMemoryAdapter
- */
- function LokiMemoryAdapter(options) {
- this.hashStore = {};
- this.options = options || {};
- if (!this.options.hasOwnProperty('asyncResponses')) {
- this.options.asyncResponses = false;
- }
- if (!this.options.hasOwnProperty('asyncTimeout')) {
- this.options.asyncTimeout = 50; // 50 ms default
- }
- }
- /**
- * Loads a serialized database from its in-memory store.
- * (Loki persistence adapter interface function)
- *
- * @param {string} dbname - name of the database (filename/keyname)
- * @param {function} callback - adapter callback to return load result to caller
- * @memberof LokiMemoryAdapter
- */
- LokiMemoryAdapter.prototype.loadDatabase = function (dbname, callback) {
- var self=this;
- if (this.options.asyncResponses) {
- setTimeout(function() {
- if (self.hashStore.hasOwnProperty(dbname)) {
- callback(self.hashStore[dbname].value);
- }
- else {
- // database doesn't exist, return falsy
- callback (null);
- }
- }, this.options.asyncTimeout);
- }
- else {
- if (this.hashStore.hasOwnProperty(dbname)) {
- // database doesn't exist, return falsy
- callback(this.hashStore[dbname].value);
- }
- else {
- callback (null);
- }
- }
- };
- /**
- * Saves a serialized database to its in-memory store.
- * (Loki persistence adapter interface function)
- *
- * @param {string} dbname - name of the database (filename/keyname)
- * @param {function} callback - adapter callback to return load result to caller
- * @memberof LokiMemoryAdapter
- */
- LokiMemoryAdapter.prototype.saveDatabase = function (dbname, dbstring, callback) {
- var self=this;
- var saveCount;
- if (this.options.asyncResponses) {
- setTimeout(function() {
- saveCount = (self.hashStore.hasOwnProperty(dbname)?self.hashStore[dbname].savecount:0);
- self.hashStore[dbname] = {
- savecount: saveCount+1,
- lastsave: new Date(),
- value: dbstring
- };
- callback();
- }, this.options.asyncTimeout);
- }
- else {
- saveCount = (this.hashStore.hasOwnProperty(dbname)?this.hashStore[dbname].savecount:0);
- this.hashStore[dbname] = {
- savecount: saveCount+1,
- lastsave: new Date(),
- value: dbstring
- };
- callback();
- }
- };
- /**
- * Deletes a database from its in-memory store.
- *
- * @param {string} dbname - name of the database (filename/keyname)
- * @param {function} callback - function to call when done
- * @memberof LokiMemoryAdapter
- */
- LokiMemoryAdapter.prototype.deleteDatabase = function(dbname, callback) {
- if (this.hashStore.hasOwnProperty(dbname)) {
- delete this.hashStore[dbname];
- }
- if (typeof callback === "function") {
- callback();
- }
- };
- /**
- * An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter
- * which can perform destructuring and partioning. Each collection will be stored in its own key/save and
- * only dirty collections will be saved. If you turn on paging with default page size of 25megs and save
- * a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter).
- * A dirty collection that spans three pages will save all three pages again
- * Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a
- * single indexeddb row. If a single document update causes the collection to be flagged as dirty, all
- * of that collection's pages will be written on next save.
- *
- * @param {object} adapter - reference to a 'non-reference' mode loki adapter instance.
- * @param {object=} options - configuration options for partitioning and paging
- * @param {bool} options.paging - (default: false) set to true to enable paging collection data.
- * @param {int} options.pageSize - (default : 25MB) you can use this to limit size of strings passed to inner adapter.
- * @param {string} options.delimiter - allows you to override the default delimeter
- * @constructor LokiPartitioningAdapter
- */
- function LokiPartitioningAdapter(adapter, options) {
- this.mode = "reference";
- this.adapter = null;
- this.options = options || {};
- this.dbref = null;
- this.dbname = "";
- this.pageIterator = {};
- // verify user passed an appropriate adapter
- if (adapter) {
- if (adapter.mode === "reference") {
- throw new Error("LokiPartitioningAdapter cannot be instantiated with a reference mode adapter");
- }
- else {
- this.adapter = adapter;
- }
- }
- else {
- throw new Error("LokiPartitioningAdapter requires a (non-reference mode) adapter on construction");
- }
- // set collection paging defaults
- if (!this.options.hasOwnProperty("paging")) {
- this.options.paging = false;
- }
- // default to page size of 25 megs (can be up to your largest serialized object size larger than this)
- if (!this.options.hasOwnProperty("pageSize")) {
- this.options.pageSize = 25*1024*1024;
- }
- if (!this.options.hasOwnProperty("delimiter")) {
- this.options.delimiter = '$<\n';
- }
- }
- /**
- * Loads a database which was partitioned into several key/value saves.
- * (Loki persistence adapter interface function)
- *
- * @param {string} dbname - name of the database (filename/keyname)
- * @param {function} callback - adapter callback to return load result to caller
- * @memberof LokiPartitioningAdapter
- */
- LokiPartitioningAdapter.prototype.loadDatabase = function (dbname, callback) {
- var self=this;
- this.dbname = dbname;
- this.dbref = new Loki(dbname);
- // load the db container (without data)
- this.adapter.loadDatabase(dbname, function(result) {
- // empty database condition is for inner adapter return null/undefined/falsy
- if (!result) {
- // partition 0 not found so new database, no need to try to load other partitions.
- // return same falsy result to loadDatabase to signify no database exists (yet)
- callback(result);
- return;
- }
- if (typeof result !== "string") {
- callback(new Error("LokiPartitioningAdapter received an unexpected response from inner adapter loadDatabase()"));
- }
- // I will want to use loki destructuring helper methods so i will inflate into typed instance
- var db = JSON.parse(result);
- self.dbref.loadJSONObject(db);
- db = null;
- var clen = self.dbref.collections.length;
- if (self.dbref.collections.length === 0) {
- callback(self.dbref);
- return;
- }
- self.pageIterator = {
- collection: 0,
- pageIndex: 0
- };
- self.loadNextPartition(0, function() {
- callback(self.dbref);
- });
- });
- };
- /**
- * Used to sequentially load each collection partition, one at a time.
- *
- * @param {int} partition - ordinal collection position to load next
- * @param {function} callback - adapter callback to return load result to caller
- */
- LokiPartitioningAdapter.prototype.loadNextPartition = function(partition, callback) {
- var keyname = this.dbname + "." + partition;
- var self=this;
- if (this.options.paging === true) {
- this.pageIterator.pageIndex = 0;
- this.loadNextPage(callback);
- return;
- }
- this.adapter.loadDatabase(keyname, function(result) {
- var data = self.dbref.deserializeCollection(result, { delimited: true, collectionIndex: partition });
- self.dbref.collections[partition].data = data;
- if (++partition < self.dbref.collections.length) {
- self.loadNextPartition(partition, callback);
- }
- else {
- callback();
- }
- });
- };
- /**
- * Used to sequentially load the next page of collection partition, one at a time.
- *
- * @param {function} callback - adapter callback to return load result to caller
- */
- LokiPartitioningAdapter.prototype.loadNextPage = function(callback) {
- // calculate name for next saved page in sequence
- var keyname = this.dbname + "." + this.pageIterator.collection + "." + this.pageIterator.pageIndex;
- var self=this;
- // load whatever page is next in sequence
- this.adapter.loadDatabase(keyname, function(result) {
- var data = result.split(self.options.delimiter);
- result = ""; // free up memory now that we have split it into array
- var dlen = data.length;
- var idx;
- // detect if last page by presence of final empty string element and remove it if so
- var isLastPage = (data[dlen-1] === "");
- if (isLastPage) {
- data.pop();
- dlen = data.length;
- // empty collections are just a delimiter meaning two blank items
- if (data[dlen-1] === "" && dlen === 1) {
- data.pop();
- dlen = data.length;
- }
- }
- // convert stringified array elements to object instances and push to collection data
- for(idx=0; idx < dlen; idx++) {
- self.dbref.collections[self.pageIterator.collection].data.push(JSON.parse(data[idx]));
- data[idx] = null;
- }
- data = [];
- // if last page, we are done with this partition
- if (isLastPage) {
- // if there are more partitions, kick off next partition load
- if (++self.pageIterator.collection < self.dbref.collections.length) {
- self.loadNextPartition(self.pageIterator.collection, callback);
- }
- else {
- callback();
- }
- }
- else {
- self.pageIterator.pageIndex++;
- self.loadNextPage(callback);
- }
- });
- };
- /**
- * Saves a database by partioning into separate key/value saves.
- * (Loki 'reference mode' persistence adapter interface function)
- *
- * @param {string} dbname - name of the database (filename/keyname)
- * @param {object} dbref - reference to database which we will partition and save.
- * @param {function} callback - adapter callback to return load result to caller
- *
- * @memberof LokiPartitioningAdapter
- */
- LokiPartitioningAdapter.prototype.exportDatabase = function(dbname, dbref, callback) {
- var self=this;
- var idx, clen = dbref.collections.length;
- this.dbref = dbref;
- this.dbname = dbname;
- // queue up dirty partitions to be saved
- this.dirtyPartitions = [-1];
- for(idx=0; idx<clen; idx++) {
- if (dbref.collections[idx].dirty) {
- this.dirtyPartitions.push(idx);
- }
- }
- this.saveNextPartition(function(err) {
- callback(err);
- });
- };
- /**
- * Helper method used internally to save each dirty collection, one at a time.
- *
- * @param {function} callback - adapter callback to return load result to caller
- */
- LokiPartitioningAdapter.prototype.saveNextPartition = function(callback) {
- var self=this;
- var partition = this.dirtyPartitions.shift();
- var keyname = this.dbname + ((partition===-1)?"":("." + partition));
- // if we are doing paging and this is collection partition
- if (this.options.paging && partition !== -1) {
- this.pageIterator = {
- collection: partition,
- docIndex: 0,
- pageIndex: 0
- };
- // since saveNextPage recursively calls itself until done, our callback means this whole paged partition is finished
- this.saveNextPage(function(err) {
- if (self.dirtyPartitions.length === 0) {
- callback(err);
- }
- else {
- self.saveNextPartition(callback);
- }
- });
- return;
- }
- // otherwise this is 'non-paged' partioning...
- var result = this.dbref.serializeDestructured({
- partitioned : true,
- delimited: true,
- partition: partition
- });
- this.adapter.saveDatabase(keyname, result, function(err) {
- if (err) {
- callback(err);
- return;
- }
- if (self.dirtyPartitions.length === 0) {
- callback(null);
- }
- else {
- self.saveNextPartition(callback);
- }
- });
- };
- /**
- * Helper method used internally to generate and save the next page of the current (dirty) partition.
- *
- * @param {function} callback - adapter callback to return load result to caller
- */
- LokiPartitioningAdapter.prototype.saveNextPage = function(callback) {
- var self=this;
- var coll = this.dbref.collections[this.pageIterator.collection];
- var keyname = this.dbname + "." + this.pageIterator.collection + "." + this.pageIterator.pageIndex;
- var pageLen=0,
- cdlen = coll.data.length,
- delimlen = this.options.delimiter.length;
- var serializedObject = "",
- pageBuilder = "";
- var doneWithPartition=false,
- doneWithPage=false;
- var pageSaveCallback = function(err) {
- pageBuilder = "";
- if (err) {
- callback(err);
- }
- // update meta properties then continue process by invoking callback
- if (doneWithPartition) {
- callback(null);
- }
- else {
- self.pageIterator.pageIndex++;
- self.saveNextPage(callback);
- }
- };
- if (coll.data.length === 0) {
- doneWithPartition = true;
- }
- while (true) {
- if (!doneWithPartition) {
- // serialize object
- serializedObject = JSON.stringify(coll.data[this.pageIterator.docIndex]);
- pageBuilder += serializedObject;
- pageLen += serializedObject.length;
- // if no more documents in collection to add, we are done with partition
- if (++this.pageIterator.docIndex >= cdlen) doneWithPartition = true;
- }
- // if our current page is bigger than defined pageSize, we are done with page
- if (pageLen >= this.options.pageSize) doneWithPage = true;
- // if not done with current page, need delimiter before next item
- // if done with partition we also want a delmiter to indicate 'end of pages' final empty row
- if (!doneWithPage || doneWithPartition) {
- pageBuilder += this.options.delimiter;
- pageLen += delimlen;
- }
- // if we are done with page save it and pass off to next recursive call or callback
- if (doneWithPartition || doneWithPage) {
- this.adapter.saveDatabase(keyname, pageBuilder, pageSaveCallback);
- return;
- }
- }
- };
- /**
- * A loki persistence adapter which persists using node fs module
- * @constructor LokiFsAdapter
- */
- function LokiFsAdapter() {
- try {
- this.fs = require('fs');
- }catch(e) {
- this.fs = null;
- }
- }
- /**
- * loadDatabase() - Load data from file, will throw an error if the file does not exist
- * @param {string} dbname - the filename of the database to load
- * @param {function} callback - the callback to handle the result
- * @memberof LokiFsAdapter
- */
- LokiFsAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) {
- var self = this;
- this.fs.stat(dbname, function (err, stats) {
- if (!err && stats.isFile()) {
- self.fs.readFile(dbname, {
- encoding: 'utf8'
- }, function readFileCallback(err, data) {
- if (err) {
- callback(new Error(err));
- } else {
- callback(data);
- }
- });
- }
- else {
- callback(null);
- }
- });
- };
- /**
- * saveDatabase() - save data to file, will throw an error if the file can't be saved
- * might want to expand this to avoid dataloss on partial save
- * @param {string} dbname - the filename of the database to load
- * @param {function} callback - the callback to handle the result
- * @memberof LokiFsAdapter
- */
- LokiFsAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) {
- var self = this;
- var tmpdbname = dbname + '~';
- this.fs.writeFile(tmpdbname, dbstring, function writeFileCallback(err) {
- if (err) {
- callback(new Error(err));
- } else {
- self.fs.rename(tmpdbname,dbname,callback);
- }
- });
- };
- /**
- * deleteDatabase() - delete the database file, will throw an error if the
- * file can't be deleted
- * @param {string} dbname - the filename of the database to delete
- * @param {function} callback - the callback to handle the result
- * @memberof LokiFsAdapter
- */
- LokiFsAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) {
- this.fs.unlink(dbname, function deleteDatabaseCallback(err) {
- if (err) {
- callback(new Error(err));
- } else {
- callback();
- }
- });
- };
- /**
- * A loki persistence adapter which persists to web browser's local storage object
- * @constructor LokiLocalStorageAdapter
- */
- function LokiLocalStorageAdapter() {}
- /**
- * loadDatabase() - Load data from localstorage
- * @param {string} dbname - the name of the database to load
- * @param {function} callback - the callback to handle the result
- * @memberof LokiLocalStorageAdapter
- */
- LokiLocalStorageAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) {
- if (localStorageAvailable()) {
- callback(localStorage.getItem(dbname));
- } else {
- callback(new Error('localStorage is not available'));
- }
- };
- /**
- * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved
- * might want to expand this to avoid dataloss on partial save
- * @param {string} dbname - the filename of the database to load
- * @param {function} callback - the callback to handle the result
- * @memberof LokiLocalStorageAdapter
- */
- LokiLocalStorageAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) {
- if (localStorageAvailable()) {
- localStorage.setItem(dbname, dbstring);
- callback(null);
- } else {
- callback(new Error('localStorage is not available'));
- }
- };
- /**
- * deleteDatabase() - delete the database from localstorage, will throw an error if it
- * can't be deleted
- * @param {string} dbname - the filename of the database to delete
- * @param {function} callback - the callback to handle the result
- * @memberof LokiLocalStorageAdapter
- */
- LokiLocalStorageAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) {
- if (localStorageAvailable()) {
- localStorage.removeItem(dbname);
- callback(null);
- } else {
- callback(new Error('localStorage is not available'));
- }
- };
- /**
- * Wait for throttledSaves to complete and invoke your callback when drained or duration is met.
- *
- * @param {function} callback - callback to fire when save queue is drained, it is passed a sucess parameter value
- * @param {object=} options - configuration options
- * @param {boolean} options.recursiveWait - (default: true) if after queue is drained, another save was kicked off, wait for it
- * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration
- * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining
- * @memberof Loki
- */
- Loki.prototype.throttledSaveDrain = function(callback, options) {
- var self = this;
- var now = (new Date()).getTime();
- if (!this.throttledSaves) {
- callback(true);
- }
- options = options || {};
- if (!options.hasOwnProperty('recursiveWait')) {
- options.recursiveWait = true;
- }
- if (!options.hasOwnProperty('recursiveWaitLimit')) {
- options.recursiveWaitLimit = false;
- }
- if (!options.hasOwnProperty('recursiveWaitLimitDuration')) {
- options.recursiveWaitLimitDuration = 2000;
- }
- if (!options.hasOwnProperty('started')) {
- options.started = (new Date()).getTime();
- }
- // if save is pending
- if (this.throttledSaves && this.throttledSavePending) {
- // if we want to wait until we are in a state where there are no pending saves at all
- if (options.recursiveWait) {
- // queue the following meta callback for when it completes
- this.throttledCallbacks.push(function() {
- // if there is now another save pending...
- if (self.throttledSavePending) {
- // if we wish to wait only so long and we have exceeded limit of our waiting, callback with false success value
- if (options.recursiveWaitLimit && (now - options.started > options.recursiveWaitLimitDuration)) {
- callback(false);
- return;
- }
- // it must be ok to wait on next queue drain
- self.throttledSaveDrain(callback, options);
- return;
- }
- // no pending saves so callback with true success
- else {
- callback(true);
- return;
- }
- });
- }
- // just notify when current queue is depleted
- else {
- this.throttledCallbacks.push(callback);
- return;
- }
- }
- // no save pending, just callback
- else {
- callback(true);
- }
- };
- /**
- * Internal load logic, decoupled from throttling/contention logic
- *
- * @param {object} options - not currently used (remove or allow overrides?)
- * @param {function=} callback - (Optional) user supplied async callback / error handler
- */
- Loki.prototype.loadDatabaseInternal = function (options, callback) {
- var cFun = callback || function (err, data) {
- if (err) {
- throw err;
- }
- },
- self = this;
- // the persistenceAdapter should be present if all is ok, but check to be sure.
- if (this.persistenceAdapter !== null) {
- this.persistenceAdapter.loadDatabase(this.filename, function loadDatabaseCallback(dbString) {
- if (typeof (dbString) === 'string') {
- var parseSuccess = false;
- try {
- self.loadJSON(dbString, options || {});
- parseSuccess = true;
- } catch (err) {
- cFun(err);
- }
- if (parseSuccess) {
- cFun(null);
- self.emit('loaded', 'database ' + self.filename + ' loaded');
- }
- } else {
- // falsy result means new database
- if (!dbString) {
- cFun(null);
- self.emit('loaded', 'empty database ' + self.filename + ' loaded');
- return;
- }
- // instanceof error means load faulted
- if (dbString instanceof Error) {
- cFun(dbString);
- return;
- }
- // if adapter has returned an js object (other than null or error) attempt to load from JSON object
- if (typeof (dbString) === "object") {
- self.loadJSONObject(dbString, options || {});
- cFun(null); // return null on success
- self.emit('loaded', 'database ' + self.filename + ' loaded');
- return;
- }
- cFun("unexpected adapter response : " + dbString);
- }
- });
- } else {
- cFun(new Error('persistenceAdapter not configured'));
- }
- };
- /**
- * Handles manually loading from file system, local storage, or adapter (such as indexeddb)
- * This method utilizes loki configuration options (if provided) to determine which
- * persistence method to use, or environment detection (if configuration was not provided).
- * To avoid contention with any throttledSaves, we will drain the save queue first.
- *
- * If you are configured with autosave, you do not need to call this method yourself.
- *
- * @param {object} options - if throttling saves and loads, this controls how we drain save queue before loading
- * @param {boolean} options.recursiveWait - (default: true) wait recursively until no saves are queued
- * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration
- * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining
- * @param {function=} callback - (Optional) user supplied async callback / error handler
- * @memberof Loki
- * @example
- * db.loadDatabase({}, function(err) {
- * if (err) {
- * console.log("error : " + err);
- * }
- * else {
- * console.log("database loaded.");
- * }
- * });
- */
- Loki.prototype.loadDatabase = function (options, callback) {
- var self=this;
- // if throttling disabled, just call internal
- if (!this.throttledSaves) {
- this.loadDatabaseInternal(options, callback);
- return;
- }
- // try to drain any pending saves in the queue to lock it for loading
- this.throttledSaveDrain(function(success) {
- if (success) {
- // pause/throttle saving until loading is done
- self.throttledSavePending = true;
- self.loadDatabaseInternal(options, function(err) {
- // now that we are finished loading, if no saves were throttled, disable flag
- if (self.throttledCallbacks.length === 0) {
- self.throttledSavePending = false;
- }
- // if saves requests came in while loading, kick off new save to kick off resume saves
- else {
- self.saveDatabase();
- }
- if (typeof callback === 'function') {
- callback(err);
- }
- });
- return;
- }
- else {
- if (typeof callback === 'function') {
- callback(new Error("Unable to pause save throttling long enough to read database"));
- }
- }
- }, options);
- };
- /**
- * Internal save logic, decoupled from save throttling logic
- */
- Loki.prototype.saveDatabaseInternal = function (callback) {
- var cFun = callback || function (err) {
- if (err) {
- throw err;
- }
- return;
- },
- self = this;
- // the persistenceAdapter should be present if all is ok, but check to be sure.
- if (this.persistenceAdapter !== null) {
- // check if the adapter is requesting (and supports) a 'reference' mode export
- if (this.persistenceAdapter.mode === "reference" && typeof this.persistenceAdapter.exportDatabase === "function") {
- // filename may seem redundant but loadDatabase will need to expect this same filename
- this.persistenceAdapter.exportDatabase(this.filename, this.copy({removeNonSerializable:true}), function exportDatabaseCallback(err) {
- self.autosaveClearFlags();
- cFun(err);
- });
- }
- // otherwise just pass the serialized database to adapter
- else {
- // persistenceAdapter might be asynchronous, so we must clear `dirty` immediately
- // or autosave won't work if an update occurs between here and the callback
- self.autosaveClearFlags();
- this.persistenceAdapter.saveDatabase(this.filename, self.serialize(), function saveDatabasecallback(err) {
- cFun(err);
- });
- }
- } else {
- cFun(new Error('persistenceAdapter not configured'));
- }
- };
- /**
- * Handles manually saving to file system, local storage, or adapter (such as indexeddb)
- * This method utilizes loki configuration options (if provided) to determine which
- * persistence method to use, or environment detection (if configuration was not provided).
- *
- * If you are configured with autosave, you do not need to call this method yourself.
- *
- * @param {function=} callback - (Optional) user supplied async callback / error handler
- * @memberof Loki
- * @example
- * db.saveDatabase(function(err) {
- * if (err) {
- * console.log("error : " + err);
- * }
- * else {
- * console.log("database saved.");
- * }
- * });
- */
- Loki.prototype.saveDatabase = function (callback) {
- if (!this.throttledSaves) {
- this.saveDatabaseInternal(callback);
- return;
- }
- if (this.throttledSavePending) {
- this.throttledCallbacks.push(callback);
- return;
- }
- var localCallbacks = this.throttledCallbacks;
- this.throttledCallbacks = [];
- localCallbacks.unshift(callback);
- this.throttledSavePending = true;
- var self = this;
- this.saveDatabaseInternal(function(err) {
- self.throttledSavePending = false;
- localCallbacks.forEach(function(pcb) {
- if (typeof pcb === 'function') {
- // Queue the callbacks so we first finish this method execution
- setTimeout(function() {
- pcb(err);
- }, 1);
- }
- });
- // since this is called async, future requests may have come in, if so.. kick off next save
- if (self.throttledCallbacks.length > 0) {
- self.saveDatabase();
- }
- });
- };
- // alias
- Loki.prototype.save = Loki.prototype.saveDatabase;
- /**
- * Handles deleting a database from file system, local
- * storage, or adapter (indexeddb)
- * This method utilizes loki configuration options (if provided) to determine which
- * persistence method to use, or environment detection (if configuration was not provided).
- *
- * @param {function=} callback - (Optional) user supplied async callback / error handler
- * @memberof Loki
- */
- Loki.prototype.deleteDatabase = function (options, callback) {
- var cFun = callback || function (err, data) {
- if (err) {
- throw err;
- }
- };
- // we aren't even using options, so we will support syntax where
- // callback is passed as first and only argument
- if (typeof options === 'function' && !callback) {
- cFun = options;
- }
- // the persistenceAdapter should be present if all is ok, but check to be sure.
- if (this.persistenceAdapter !== null) {
- this.persistenceAdapter.deleteDatabase(this.filename, function deleteDatabaseCallback(err) {
- cFun(err);
- });
- } else {
- cFun(new Error('persistenceAdapter not configured'));
- }
- };
- /**
- * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database
- *
- * @returns {boolean} - true if database has changed since last autosave, false if not.
- */
- Loki.prototype.autosaveDirty = function () {
- for (var idx = 0; idx < this.collections.length; idx++) {
- if (this.collections[idx].dirty) {
- return true;
- }
- }
- return false;
- };
- /**
- * autosaveClearFlags - resets dirty flags on all collections.
- * Called from saveDatabase() after db is saved.
- *
- */
- Loki.prototype.autosaveClearFlags = function () {
- for (var idx = 0; idx < this.collections.length; idx++) {
- this.collections[idx].dirty = false;
- }
- };
- /**
- * autosaveEnable - begin a javascript interval to periodically save the database.
- *
- * @param {object} options - not currently used (remove or allow overrides?)
- * @param {function=} callback - (Optional) user supplied async callback
- */
- Loki.prototype.autosaveEnable = function (options, callback) {
- this.autosave = true;
- var delay = 5000,
- self = this;
- if (typeof (this.autosaveInterval) !== 'undefined' && this.autosaveInterval !== null) {
- delay = this.autosaveInterval;
- }
- this.autosaveHandle = setInterval(function autosaveHandleInterval() {
- // use of dirty flag will need to be hierarchical since mods are done at collection level with no visibility of 'db'
- // so next step will be to implement collection level dirty flags set on insert/update/remove
- // along with loki level isdirty() function which iterates all collections to see if any are dirty
- if (self.autosaveDirty()) {
- self.saveDatabase(callback);
- }
- }, delay);
- };
- /**
- * autosaveDisable - stop the autosave interval timer.
- *
- */
- Loki.prototype.autosaveDisable = function () {
- if (typeof (this.autosaveHandle) !== 'undefined' && this.autosaveHandle !== null) {
- clearInterval(this.autosaveHandle);
- this.autosaveHandle = null;
- }
- };
- /**
- * Resultset class allowing chainable queries. Intended to be instanced internally.
- * Collection.find(), Collection.where(), and Collection.chain() instantiate this.
- *
- * @example
- * mycollection.chain()
- * .find({ 'doors' : 4 })
- * .where(function(obj) { return obj.name === 'Toyota' })
- * .data();
- *
- * @constructor Resultset
- * @param {Collection} collection - The collection which this Resultset will query against.
- */
- function Resultset(collection, options) {
- options = options || {};
- // retain reference to collection we are querying against
- this.collection = collection;
- this.filteredrows = [];
- this.filterInitialized = false;
- return this;
- }
- /**
- * reset() - Reset the resultset to its initial state.
- *
- * @returns {Resultset} Reference to this resultset, for future chain operations.
- */
- Resultset.prototype.reset = function () {
- if (this.filteredrows.length > 0) {
- this.filteredrows = [];
- }
- this.filterInitialized = false;
- return this;
- };
- /**
- * toJSON() - Override of toJSON to avoid circular references
- *
- */
- Resultset.prototype.toJSON = function () {
- var copy = this.copy();
- copy.collection = null;
- return copy;
- };
- /**
- * Allows you to limit the number of documents passed to next chain operation.
- * A resultset copy() is made to avoid altering original resultset.
- *
- * @param {int} qty - The number of documents to return.
- * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops.
- * @memberof Resultset
- * // find the two oldest users
- * var result = users.chain().simplesort("age", true).limit(2).data();
- */
- Resultset.prototype.limit = function (qty) {
- // if this has no filters applied, we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- var rscopy = new Resultset(this.collection);
- rscopy.filteredrows = this.filteredrows.slice(0, qty);
- rscopy.filterInitialized = true;
- return rscopy;
- };
- /**
- * Used for skipping 'pos' number of documents in the resultset.
- *
- * @param {int} pos - Number of documents to skip; all preceding documents are filtered out.
- * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops.
- * @memberof Resultset
- * // find everyone but the two oldest users
- * var result = users.chain().simplesort("age", true).offset(2).data();
- */
- Resultset.prototype.offset = function (pos) {
- // if this has no filters applied, we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- var rscopy = new Resultset(this.collection);
- rscopy.filteredrows = this.filteredrows.slice(pos);
- rscopy.filterInitialized = true;
- return rscopy;
- };
- /**
- * copy() - To support reuse of resultset in branched query situations.
- *
- * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same.
- * @memberof Resultset
- */
- Resultset.prototype.copy = function () {
- var result = new Resultset(this.collection);
- if (this.filteredrows.length > 0) {
- result.filteredrows = this.filteredrows.slice();
- }
- result.filterInitialized = this.filterInitialized;
- return result;
- };
- /**
- * Alias of copy()
- * @memberof Resultset
- */
- Resultset.prototype.branch = Resultset.prototype.copy;
- /**
- * transform() - executes a named collection transform or raw array of transform steps against the resultset.
- *
- * @param transform {(string|array)} - name of collection transform or raw transform array
- * @param parameters {object=} - (Optional) object property hash of parameters, if the transform requires them.
- * @returns {Resultset} either (this) resultset or a clone of of this resultset (depending on steps)
- * @memberof Resultset
- * @example
- * users.addTransform('CountryFilter', [
- * {
- * type: 'find',
- * value: {
- * 'country': { $eq: '[%lktxp]Country' }
- * }
- * },
- * {
- * type: 'simplesort',
- * property: 'age',
- * options: { desc: false}
- * }
- * ]);
- * var results = users.chain().transform("CountryFilter", { Country: 'fr' }).data();
- */
- Resultset.prototype.transform = function (transform, parameters) {
- var idx,
- step,
- rs = this;
- // if transform is name, then do lookup first
- if (typeof transform === 'string') {
- if (this.collection.transforms.hasOwnProperty(transform)) {
- transform = this.collection.transforms[transform];
- }
- }
- // either they passed in raw transform array or we looked it up, so process
- if (typeof transform !== 'object' || !Array.isArray(transform)) {
- throw new Error("Invalid transform");
- }
- if (typeof parameters !== 'undefined') {
- transform = Utils.resolveTransformParams(transform, parameters);
- }
- for (idx = 0; idx < transform.length; idx++) {
- step = transform[idx];
- switch (step.type) {
- case "find":
- rs.find(step.value);
- break;
- case "where":
- rs.where(step.value);
- break;
- case "simplesort":
- rs.simplesort(step.property, step.desc || step.options);
- break;
- case "compoundsort":
- rs.compoundsort(step.value);
- break;
- case "sort":
- rs.sort(step.value);
- break;
- case "limit":
- rs = rs.limit(step.value);
- break; // limit makes copy so update reference
- case "offset":
- rs = rs.offset(step.value);
- break; // offset makes copy so update reference
- case "map":
- rs = rs.map(step.value, step.dataOptions);
- break;
- case "eqJoin":
- rs = rs.eqJoin(step.joinData, step.leftJoinKey, step.rightJoinKey, step.mapFun, step.dataOptions);
- break;
- // following cases break chain by returning array data so make any of these last in transform steps
- case "mapReduce":
- rs = rs.mapReduce(step.mapFunction, step.reduceFunction);
- break;
- // following cases update documents in current filtered resultset (use carefully)
- case "update":
- rs.update(step.value);
- break;
- case "remove":
- rs.remove();
- break;
- default:
- break;
- }
- }
- return rs;
- };
- /**
- * User supplied compare function is provided two documents to compare. (chainable)
- * @example
- * rslt.sort(function(obj1, obj2) {
- * if (obj1.name === obj2.name) return 0;
- * if (obj1.name > obj2.name) return 1;
- * if (obj1.name < obj2.name) return -1;
- * });
- *
- * @param {function} comparefun - A javascript compare function used for sorting.
- * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
- * @memberof Resultset
- */
- Resultset.prototype.sort = function (comparefun) {
- // if this has no filters applied, just we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- var wrappedComparer =
- (function (userComparer, data) {
- return function (a, b) {
- return userComparer(data[a], data[b]);
- };
- })(comparefun, this.collection.data);
- this.filteredrows.sort(wrappedComparer);
- return this;
- };
- /**
- * Simpler, loose evaluation for user to sort based on a property name. (chainable).
- * Sorting based on the same lt/gt helper functions used for binary indices.
- *
- * @param {string} propname - name of property to sort by.
- * @param {object|bool=} options - boolean to specify if isdescending, or options object
- * @param {boolean} [options.desc=false] - whether to sort descending
- * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection.
- * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists).
- * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort.
- * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
- * @memberof Resultset
- * @example
- * var results = users.chain().simplesort('age').data();
- */
- Resultset.prototype.simplesort = function (propname, options) {
- var eff,
- targetEff = 10,
- dc = this.collection.data.length,
- frl = this.filteredrows.length,
- hasBinaryIndex = this.collection.binaryIndices.hasOwnProperty(propname);
- if (typeof (options) === 'undefined' || options === false) {
- options = { desc: false };
- }
- if (options === true) {
- options = { desc: true };
- }
- // if nothing in filtered rows array...
- if (frl === 0) {
- // if the filter is initialized to be empty resultset, do nothing
- if (this.filterInitialized) {
- return this;
- }
-
- // otherwise no filters applied implies all documents, so we need to populate filteredrows first
-
- // if we have a binary index, we can just use that instead of sorting (again)
- if (this.collection.binaryIndices.hasOwnProperty(propname)) {
- // make sure index is up-to-date
- this.collection.ensureIndex(propname);
- // copy index values into filteredrows
- this.filteredrows = this.collection.binaryIndices[propname].values.slice(0);
- if (options.desc) {
- this.filteredrows.reverse();
- }
- // we are done, return this (resultset) for further chain ops
- return this;
- }
- // otherwise initialize array for sort below
- else {
- // build full document index (to be sorted subsequently)
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- }
- // otherwise we had results to begin with, see if we qualify for index intercept optimization
- else {
- // If already filtered, but we want to leverage binary index on sort.
- // This will use custom array intection algorithm.
- if (!options.disableIndexIntersect && hasBinaryIndex) {
- // calculate filter efficiency
- eff = dc/frl;
- // when javascript sort fallback is enabled, you generally need more than ~17% of total docs in resultset
- // before array intersect is determined to be the faster algorithm, otherwise leave at 10% for loki sort.
- if (options.useJavascriptSorting) {
- targetEff = 6;
- }
- // anything more than ratio of 10:1 (total documents/current results) should use old sort code path
- // So we will only use array intersection if you have more than 10% of total docs in your current resultset.
- if (eff <= targetEff || options.forceIndexIntersect) {
- var idx, fr=this.filteredrows;
- var io = {};
- // set up hashobject for simple 'inclusion test' with existing (filtered) results
- for(idx=0; idx<frl; idx++) {
- io[fr[idx]] = true;
- }
- // grab full sorted binary index array
- var pv = this.collection.binaryIndices[propname].values;
- // filter by existing results
- this.filteredrows = pv.filter(function(n) { return io[n]; });
- if (options.desc) {
- this.filteredrows.reverse();
- }
- return this;
- }
- }
- }
- // at this point, we will not be able to leverage binary index so we will have to do an array sort
-
- // if we have opted to use simplified javascript comparison function...
- if (options.useJavascriptSorting) {
- return this.sort(function(obj1, obj2) {
- if (obj1[propname] === obj2[propname]) return 0;
- if (obj1[propname] > obj2[propname]) return 1;
- if (obj1[propname] < obj2[propname]) return -1;
- });
- }
- // otherwise use loki sort which will return same results if column is indexed or not
- var wrappedComparer =
- (function (prop, desc, data) {
- var val1, val2, arr;
- return function (a, b) {
- if (~prop.indexOf('.')) {
- arr = prop.split('.');
- val1 = Utils.getIn(data[a], arr, true);
- val2 = Utils.getIn(data[b], arr, true);
- } else {
- val1 = data[a][prop];
- val2 = data[b][prop];
- }
- return sortHelper(val1, val2, desc);
- };
- })(propname, options.desc, this.collection.data);
- this.filteredrows.sort(wrappedComparer);
- return this;
- };
- /**
- * Allows sorting a resultset based on multiple columns.
- * @example
- * // to sort by age and then name (both ascending)
- * rs.compoundsort(['age', 'name']);
- * // to sort by age (ascending) and then by name (descending)
- * rs.compoundsort(['age', ['name', true]]);
- *
- * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
- * @returns {Resultset} Reference to this resultset, sorted, for future chain operations.
- * @memberof Resultset
- */
- Resultset.prototype.compoundsort = function (properties) {
- if (properties.length === 0) {
- throw new Error("Invalid call to compoundsort, need at least one property");
- }
- var prop;
- if (properties.length === 1) {
- prop = properties[0];
- if (Array.isArray(prop)) {
- return this.simplesort(prop[0], prop[1]);
- }
- return this.simplesort(prop, false);
- }
- // unify the structure of 'properties' to avoid checking it repeatedly while sorting
- for (var i = 0, len = properties.length; i < len; i += 1) {
- prop = properties[i];
- if (!Array.isArray(prop)) {
- properties[i] = [prop, false];
- }
- }
- // if this has no filters applied, just we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- var wrappedComparer =
- (function (props, data) {
- return function (a, b) {
- return compoundeval(props, data[a], data[b]);
- };
- })(properties, this.collection.data);
- this.filteredrows.sort(wrappedComparer);
- return this;
- };
- /**
- * findOr() - oversee the operation of OR'ed query expressions.
- * OR'ed expression evaluation runs each expression individually against the full collection,
- * and finally does a set OR on each expression's results.
- * Each evaluation can utilize a binary index to prevent multiple linear array scans.
- *
- * @param {array} expressionArray - array of expressions
- * @returns {Resultset} this resultset for further chain ops.
- */
- Resultset.prototype.findOr = function (expressionArray) {
- var fr = null,
- fri = 0,
- frlen = 0,
- docset = [],
- idxset = [],
- idx = 0,
- origCount = this.count();
- // If filter is already initialized, then we query against only those items already in filter.
- // This means no index utilization for fields, so hopefully its filtered to a smallish filteredrows.
- for (var ei = 0, elen = expressionArray.length; ei < elen; ei++) {
- // we need to branch existing query to run each filter separately and combine results
- fr = this.branch().find(expressionArray[ei]).filteredrows;
- frlen = fr.length;
- // if the find operation did not reduce the initial set, then the initial set is the actual result
- if (frlen === origCount) {
- return this;
- }
- // add any document 'hits'
- for (fri = 0; fri < frlen; fri++) {
- idx = fr[fri];
- if (idxset[idx] === undefined) {
- idxset[idx] = true;
- docset.push(idx);
- }
- }
- }
- this.filteredrows = docset;
- this.filterInitialized = true;
- return this;
- };
- Resultset.prototype.$or = Resultset.prototype.findOr;
- // precompile recursively
- function precompileQuery (operator, value) {
- // for regex ops, precompile
- if (operator === '$regex') {
- if (Array.isArray(value)) {
- value = new RegExp(value[0], value[1]);
- } else if (!(value instanceof RegExp)) {
- value = new RegExp(value);
- }
- }
- else if (typeof value === 'object') {
- for (var key in value) {
- if (key === '$regex' || typeof value[key] === 'object') {
- value[key] = precompileQuery(key, value[key]);
- }
- }
- }
- return value;
- }
- /**
- * findAnd() - oversee the operation of AND'ed query expressions.
- * AND'ed expression evaluation runs each expression progressively against the full collection,
- * internally utilizing existing chained resultset functionality.
- * Only the first filter can utilize a binary index.
- *
- * @param {array} expressionArray - array of expressions
- * @returns {Resultset} this resultset for further chain ops.
- */
- Resultset.prototype.findAnd = function (expressionArray) {
- // we have already implementing method chaining in this (our Resultset class)
- // so lets just progressively apply user supplied and filters
- for (var i = 0, len = expressionArray.length; i < len; i++) {
- if (this.count() === 0) {
- return this;
- }
- this.find(expressionArray[i]);
- }
- return this;
- };
- Resultset.prototype.$and = Resultset.prototype.findAnd;
- /**
- * Used for querying via a mongo-style query object.
- *
- * @param {object} query - A mongo-style query object used for filtering current results.
- * @param {boolean=} firstOnly - (Optional) Used by collection.findOne()
- * @returns {Resultset} this resultset for further chain ops.
- * @memberof Resultset
- * @example
- * var over30 = users.chain().find({ age: { $gte: 30 } }).data();
- */
- Resultset.prototype.find = function (query, firstOnly) {
- if (this.collection.data.length === 0) {
- this.filteredrows = [];
- this.filterInitialized = true;
- return this;
- }
- var queryObject = query || 'getAll',
- p,
- property,
- queryObjectOp,
- obj,
- operator,
- value,
- key,
- searchByIndex = false,
- result = [],
- filters = [],
- index = null;
- // flag if this was invoked via findOne()
- firstOnly = firstOnly || false;
- if (typeof queryObject === 'object') {
- for (p in queryObject) {
- obj = {};
- obj[p] = queryObject[p];
- filters.push(obj);
- if (hasOwnProperty.call(queryObject, p)) {
- property = p;
- queryObjectOp = queryObject[p];
- }
- }
- // if more than one expression in single query object,
- // convert implicit $and to explicit $and
- if (filters.length > 1) {
- return this.find({ '$and': filters }, firstOnly);
- }
- }
- // apply no filters if they want all
- if (!property || queryObject === 'getAll') {
- if (firstOnly) {
- this.filteredrows = (this.collection.data.length > 0)?[0]: [];
- this.filterInitialized = true;
- }
- return this;
- }
- // injecting $and and $or expression tree evaluation here.
- if (property === '$and' || property === '$or') {
- this[property](queryObjectOp);
- // for chained find with firstonly,
- if (firstOnly && this.filteredrows.length > 1) {
- this.filteredrows = this.filteredrows.slice(0, 1);
- }
- return this;
- }
- // see if query object is in shorthand mode (assuming eq operator)
- if (queryObjectOp === null || (typeof queryObjectOp !== 'object' || queryObjectOp instanceof Date)) {
- operator = '$eq';
- value = queryObjectOp;
- } else if (typeof queryObjectOp === 'object') {
- for (key in queryObjectOp) {
- if (hasOwnProperty.call(queryObjectOp, key)) {
- operator = key;
- value = queryObjectOp[key];
- break;
- }
- }
- } else {
- throw new Error('Do not know what you want to do.');
- }
- if (operator === '$regex' || typeof value === 'object') {
- value = precompileQuery(operator, value);
- }
- // if user is deep querying the object such as find('name.first': 'odin')
- var usingDotNotation = (property.indexOf('.') !== -1);
- // if an index exists for the property being queried against, use it
- // for now only enabling where it is the first filter applied and prop is indexed
- var doIndexCheck = !this.filterInitialized;
- if (doIndexCheck && this.collection.binaryIndices[property] && indexedOps[operator]) {
- // this is where our lazy index rebuilding will take place
- // basically we will leave all indexes dirty until we need them
- // so here we will rebuild only the index tied to this property
- // ensureIndex() will only rebuild if flagged as dirty since we are not passing force=true param
- if (this.collection.adaptiveBinaryIndices !== true) {
- this.collection.ensureIndex(property);
- }
- searchByIndex = true;
- index = this.collection.binaryIndices[property];
- }
- // the comparison function
- var fun = LokiOps[operator];
- // "shortcut" for collection data
- var t = this.collection.data;
- // filter data length
- var i = 0,
- len = 0;
- // Query executed differently depending on :
- // - whether the property being queried has an index defined
- // - if chained, we handle first pass differently for initial filteredrows[] population
- //
- // For performance reasons, each case has its own if block to minimize in-loop calculations
- var filter, rowIdx = 0;
- // If the filteredrows[] is already initialized, use it
- if (this.filterInitialized) {
- filter = this.filteredrows;
- len = filter.length;
- // currently supporting dot notation for non-indexed conditions only
- if (usingDotNotation) {
- property = property.split('.');
- for(i=0; i<len; i++) {
- rowIdx = filter[i];
- if (dotSubScan(t[rowIdx], property, fun, value)) {
- result.push(rowIdx);
- }
- }
- } else {
- for(i=0; i<len; i++) {
- rowIdx = filter[i];
- if (fun(t[rowIdx][property], value)) {
- result.push(rowIdx);
- }
- }
- }
- }
- // first chained query so work against data[] but put results in filteredrows
- else {
- // if not searching by index
- if (!searchByIndex) {
- len = t.length;
- if (usingDotNotation) {
- property = property.split('.');
- for(i=0; i<len; i++) {
- if (dotSubScan(t[i], property, fun, value)) {
- result.push(i);
- if (firstOnly) {
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- }
- }
- } else {
- for(i=0; i<len; i++) {
- if (fun(t[i][property], value)) {
- result.push(i);
- if (firstOnly) {
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- }
- }
- }
- } else {
- // search by index
- var segm = this.collection.calculateRange(operator, property, value);
- if (operator !== '$in') {
- for (i = segm[0]; i <= segm[1]; i++) {
- if (indexedOps[operator] !== true) {
- // must be a function, implying 2nd phase filtering of results from calculateRange
- if (indexedOps[operator](Utils.getIn(t[index.values[i]], property, usingDotNotation), value)) {
- result.push(index.values[i]);
- if (firstOnly) {
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- }
- }
- else {
- result.push(index.values[i]);
- if (firstOnly) {
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- }
- }
- } else {
- for (i = 0, len = segm.length; i < len; i++) {
- result.push(index.values[segm[i]]);
- if (firstOnly) {
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- }
- }
- }
- }
- this.filteredrows = result;
- this.filterInitialized = true; // next time work against filteredrows[]
- return this;
- };
- /**
- * where() - Used for filtering via a javascript filter function.
- *
- * @param {function} fun - A javascript function used for filtering current results by.
- * @returns {Resultset} this resultset for further chain ops.
- * @memberof Resultset
- * @example
- * var over30 = users.chain().where(function(obj) { return obj.age >= 30; }.data();
- */
- Resultset.prototype.where = function (fun) {
- var viewFunction,
- result = [];
- if ('function' === typeof fun) {
- viewFunction = fun;
- } else {
- throw new TypeError('Argument is not a stored view or a function');
- }
- try {
- // If the filteredrows[] is already initialized, use it
- if (this.filterInitialized) {
- var j = this.filteredrows.length;
- while (j--) {
- if (viewFunction(this.collection.data[this.filteredrows[j]]) === true) {
- result.push(this.filteredrows[j]);
- }
- }
- this.filteredrows = result;
- return this;
- }
- // otherwise this is initial chained op, work against data, push into filteredrows[]
- else {
- var k = this.collection.data.length;
- while (k--) {
- if (viewFunction(this.collection.data[k]) === true) {
- result.push(k);
- }
- }
- this.filteredrows = result;
- this.filterInitialized = true;
- return this;
- }
- } catch (err) {
- throw err;
- }
- };
- /**
- * count() - returns the number of documents in the resultset.
- *
- * @returns {number} The number of documents in the resultset.
- * @memberof Resultset
- * @example
- * var over30Count = users.chain().find({ age: { $gte: 30 } }).count();
- */
- Resultset.prototype.count = function () {
- if (this.filterInitialized) {
- return this.filteredrows.length;
- }
- return this.collection.count();
- };
- /**
- * Terminates the chain and returns array of filtered documents
- *
- * @param {object=} options - allows specifying 'forceClones' and 'forceCloneMethod' options.
- * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when
- * the collection is not configured for clone object.
- * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method.
- * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
- * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents
- *
- * @returns {array} Array of documents in the resultset
- * @memberof Resultset
- * @example
- * var resutls = users.chain().find({ age: 34 }).data();
- */
- Resultset.prototype.data = function (options) {
- var result = [],
- data = this.collection.data,
- obj,
- len,
- i,
- method;
- options = options || {};
- // if user opts to strip meta, then force clones and use 'shallow' if 'force' options are not present
- if (options.removeMeta && !options.forceClones) {
- options.forceClones = true;
- options.forceCloneMethod = options.forceCloneMethod || 'shallow';
- }
- // if collection has delta changes active, then force clones and use 'parse-stringify' for effective change tracking of nested objects
- if (!this.collection.disableDeltaChangesApi) {
- options.forceClones = true;
- options.forceCloneMethod = 'parse-stringify';
- }
- // if this has no filters applied, just return collection.data
- if (!this.filterInitialized) {
- if (this.filteredrows.length === 0) {
- // determine whether we need to clone objects or not
- if (this.collection.cloneObjects || options.forceClones) {
- len = data.length;
- method = options.forceCloneMethod || this.collection.cloneMethod;
- for (i = 0; i < len; i++) {
- obj = clone(data[i], method);
- if (options.removeMeta) {
- delete obj.$loki;
- delete obj.meta;
- }
- result.push(obj);
- }
- return result;
- }
- // otherwise we are not cloning so return sliced array with same object references
- else {
- return data.slice();
- }
- } else {
- // filteredrows must have been set manually, so use it
- this.filterInitialized = true;
- }
- }
- var fr = this.filteredrows;
- len = fr.length;
- if (this.collection.cloneObjects || options.forceClones) {
- method = options.forceCloneMethod || this.collection.cloneMethod;
- for (i = 0; i < len; i++) {
- obj = clone(data[fr[i]], method);
- if (options.removeMeta) {
- delete obj.$loki;
- delete obj.meta;
- }
- result.push(obj);
- }
- } else {
- for (i = 0; i < len; i++) {
- result.push(data[fr[i]]);
- }
- }
- return result;
- };
- /**
- * Used to run an update operation on all documents currently in the resultset.
- *
- * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object.
- * @returns {Resultset} this resultset for further chain ops.
- * @memberof Resultset
- * @example
- * users.chain().find({ country: 'de' }).update(function(user) {
- * user.phoneFormat = "+49 AAAA BBBBBB";
- * });
- */
- Resultset.prototype.update = function (updateFunction) {
- if (typeof (updateFunction) !== "function") {
- throw new TypeError('Argument is not a function');
- }
- // if this has no filters applied, we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- var obj, len = this.filteredrows.length,
- rcd = this.collection.data;
- // pass in each document object currently in resultset to user supplied updateFunction
- for (var idx = 0; idx < len; idx++) {
- // if we have cloning option specified or are doing differential delta changes, clone object first
- if (this.collection.cloneObjects || !this.collection.disableDeltaChangesApi) {
- obj = clone(rcd[this.filteredrows[idx]], this.collection.cloneMethod);
- updateFunction(obj);
- this.collection.update(obj);
- }
- else {
- // no need to clone, so just perform update on collection data object instance
- updateFunction(rcd[this.filteredrows[idx]]);
- this.collection.update(rcd[this.filteredrows[idx]]);
- }
- }
- return this;
- };
- /**
- * Removes all document objects which are currently in resultset from collection (as well as resultset)
- *
- * @returns {Resultset} this (empty) resultset for further chain ops.
- * @memberof Resultset
- * @example
- * // remove users inactive since 1/1/2001
- * users.chain().find({ lastActive: { $lte: new Date("1/1/2001").getTime() } }).remove();
- */
- Resultset.prototype.remove = function () {
- // if this has no filters applied, we need to populate filteredrows first
- if (!this.filterInitialized && this.filteredrows.length === 0) {
- this.filteredrows = this.collection.prepareFullDocIndex();
- }
- this.collection.removeBatchByPositions(this.filteredrows);
- this.filteredrows = [];
- return this;
- };
- /**
- * data transformation via user supplied functions
- *
- * @param {function} mapFunction - this function accepts a single document for you to transform and return
- * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
- * @returns {value} The output of your reduceFunction
- * @memberof Resultset
- * @example
- * var db = new loki("order.db");
- * var orders = db.addCollection("orders");
- * orders.insert([{ qty: 4, unitCost: 100.00 }, { qty: 10, unitCost: 999.99 }, { qty: 2, unitCost: 49.99 }]);
- *
- * function mapfun (obj) { return obj.qty*obj.unitCost };
- * function reducefun(array) {
- * var grandTotal=0;
- * array.forEach(function(orderTotal) { grandTotal += orderTotal; });
- * return grandTotal;
- * }
- * var grandOrderTotal = orders.chain().mapReduce(mapfun, reducefun);
- * console.log(grandOrderTotal);
- */
- Resultset.prototype.mapReduce = function (mapFunction, reduceFunction) {
- try {
- return reduceFunction(this.data().map(mapFunction));
- } catch (err) {
- throw err;
- }
- };
- /**
- * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties
- * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key
- * @param {Array|Resultset|Collection} joinData - Data array to join to.
- * @param {(string|function)} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on
- * @param {(string|function)} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on
- * @param {function=} mapFun - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject}
- * @param {object=} dataOptions - options to data() before input to your map function
- * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
- * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
- * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
- * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}]
- * @memberof Resultset
- * @example
- * var db = new loki('sandbox.db');
- *
- * var products = db.addCollection('products');
- * var orders = db.addCollection('orders');
- *
- * products.insert({ productId: "100234", name: "flywheel energy storage", unitCost: 19999.99 });
- * products.insert({ productId: "140491", name: "300F super capacitor", unitCost: 129.99 });
- * products.insert({ productId: "271941", name: "fuel cell", unitCost: 3999.99 });
- * products.insert({ productId: "174592", name: "390V 3AH lithium bank", unitCost: 4999.99 });
- *
- * orders.insert({ orderDate : new Date("12/1/2017").getTime(), prodId: "174592", qty: 2, customerId: 2 });
- * orders.insert({ orderDate : new Date("4/15/2016").getTime(), prodId: "271941", qty: 1, customerId: 1 });
- * orders.insert({ orderDate : new Date("3/12/2017").getTime(), prodId: "140491", qty: 4, customerId: 4 });
- * orders.insert({ orderDate : new Date("7/31/2017").getTime(), prodId: "100234", qty: 7, customerId: 3 });
- * orders.insert({ orderDate : new Date("8/3/2016").getTime(), prodId: "174592", qty: 3, customerId: 5 });
- *
- * var mapfun = function(left, right) {
- * return {
- * orderId: left.$loki,
- * orderDate: new Date(left.orderDate) + '',
- * customerId: left.customerId,
- * qty: left.qty,
- * productId: left.prodId,
- * prodName: right.name,
- * prodCost: right.unitCost,
- * orderTotal: +((right.unitCost * left.qty).toFixed(2))
- * };
- * };
- *
- * // join orders with relevant product info via eqJoin
- * var orderSummary = orders.chain().eqJoin(products, "prodId", "productId", mapfun).data();
- *
- * console.log(orderSummary);
- */
- Resultset.prototype.eqJoin = function (joinData, leftJoinKey, rightJoinKey, mapFun, dataOptions) {
- var leftData = [],
- leftDataLength,
- rightData = [],
- rightDataLength,
- key,
- result = [],
- leftKeyisFunction = typeof leftJoinKey === 'function',
- rightKeyisFunction = typeof rightJoinKey === 'function',
- joinMap = {};
- //get the left data
- leftData = this.data(dataOptions);
- leftDataLength = leftData.length;
- //get the right data
- if (joinData instanceof Collection) {
- rightData = joinData.chain().data(dataOptions);
- } else if (joinData instanceof Resultset) {
- rightData = joinData.data(dataOptions);
- } else if (Array.isArray(joinData)) {
- rightData = joinData;
- } else {
- throw new TypeError('joinData needs to be an array or result set');
- }
- rightDataLength = rightData.length;
- //construct a lookup table
- for (var i = 0; i < rightDataLength; i++) {
- key = rightKeyisFunction ? rightJoinKey(rightData[i]) : rightData[i][rightJoinKey];
- joinMap[key] = rightData[i];
- }
- if (!mapFun) {
- mapFun = function (left, right) {
- return {
- left: left,
- right: right
- };
- };
- }
- //Run map function over each object in the resultset
- for (var j = 0; j < leftDataLength; j++) {
- key = leftKeyisFunction ? leftJoinKey(leftData[j]) : leftData[j][leftJoinKey];
- result.push(mapFun(leftData[j], joinMap[key] || {}));
- }
- //return return a new resultset with no filters
- this.collection = new Collection('joinData');
- this.collection.insert(result);
- this.filteredrows = [];
- this.filterInitialized = false;
- return this;
- };
- /**
- * Applies a map function into a new collection for further chaining.
- * @param {function} mapFun - javascript map function
- * @param {object=} dataOptions - options to data() before input to your map function
- * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
- * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
- * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
- * @memberof Resultset
- * @example
- * var orders.chain().find({ productId: 32 }).map(function(obj) {
- * return {
- * orderId: $loki,
- * productId: productId,
- * quantity: qty
- * };
- * });
- */
- Resultset.prototype.map = function (mapFun, dataOptions) {
- var data = this.data(dataOptions).map(mapFun);
- //return return a new resultset with no filters
- this.collection = new Collection('mappedData');
- this.collection.insert(data);
- this.filteredrows = [];
- this.filterInitialized = false;
- return this;
- };
- /**
- * DynamicView class is a versatile 'live' view class which can have filters and sorts applied.
- * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it
- * whenever documents are add/updated/removed so it can remain up-to-date. (chainable)
- *
- * @example
- * var mydv = mycollection.addDynamicView('test'); // default is non-persistent
- * mydv.applyFind({ 'doors' : 4 });
- * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; });
- * var results = mydv.data();
- *
- * @constructor DynamicView
- * @implements LokiEventEmitter
- * @param {Collection} collection - A reference to the collection to work against
- * @param {string} name - The name of this dynamic view
- * @param {object=} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options.
- * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
- * @param {string} [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates)
- * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here)
- * @see {@link Collection#addDynamicView} to construct instances of DynamicView
- */
- function DynamicView(collection, name, options) {
- this.collection = collection;
- this.name = name;
- this.rebuildPending = false;
- this.options = options || {};
- if (!this.options.hasOwnProperty('persistent')) {
- this.options.persistent = false;
- }
- // 'persistentSortPriority':
- // 'passive' will defer the sort phase until they call data(). (most efficient overall)
- // 'active' will sort async whenever next idle. (prioritizes read speeds)
- if (!this.options.hasOwnProperty('sortPriority')) {
- this.options.sortPriority = 'passive';
- }
- if (!this.options.hasOwnProperty('minRebuildInterval')) {
- this.options.minRebuildInterval = 1;
- }
- this.resultset = new Resultset(collection);
- this.resultdata = [];
- this.resultsdirty = false;
- this.cachedresultset = null;
- // keep ordered filter pipeline
- this.filterPipeline = [];
- // sorting member variables
- // we only support one active search, applied using applySort() or applySimpleSort()
- this.sortFunction = null;
- this.sortCriteria = null;
- this.sortCriteriaSimple = null;
- this.sortDirty = false;
- // for now just have 1 event for when we finally rebuilt lazy view
- // once we refactor transactions, i will tie in certain transactional events
- this.events = {
- 'rebuild': []
- };
- }
- DynamicView.prototype = new LokiEventEmitter();
- /**
- * rematerialize() - internally used immediately after deserialization (loading)
- * This will clear out and reapply filterPipeline ops, recreating the view.
- * Since where filters do not persist correctly, this method allows
- * restoring the view to state where user can re-apply those where filters.
- *
- * @param {Object=} options - (Optional) allows specification of 'removeWhereFilters' option
- * @returns {DynamicView} This dynamic view for further chained ops.
- * @memberof DynamicView
- * @fires DynamicView.rebuild
- */
- DynamicView.prototype.rematerialize = function (options) {
- var fpl,
- fpi,
- idx;
- options = options || {};
- this.resultdata = [];
- this.resultsdirty = true;
- this.resultset = new Resultset(this.collection);
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.sortDirty = true;
- }
- if (options.hasOwnProperty('removeWhereFilters')) {
- // for each view see if it had any where filters applied... since they don't
- // serialize those functions lets remove those invalid filters
- fpl = this.filterPipeline.length;
- fpi = fpl;
- while (fpi--) {
- if (this.filterPipeline[fpi].type === 'where') {
- if (fpi !== this.filterPipeline.length - 1) {
- this.filterPipeline[fpi] = this.filterPipeline[this.filterPipeline.length - 1];
- }
- this.filterPipeline.length--;
- }
- }
- }
- // back up old filter pipeline, clear filter pipeline, and reapply pipeline ops
- var ofp = this.filterPipeline;
- this.filterPipeline = [];
- // now re-apply 'find' filterPipeline ops
- fpl = ofp.length;
- for (idx = 0; idx < fpl; idx++) {
- this.applyFind(ofp[idx].val);
- }
- // during creation of unit tests, i will remove this forced refresh and leave lazy
- this.data();
- // emit rebuild event in case user wants to be notified
- this.emit('rebuild', this);
- return this;
- };
- /**
- * branchResultset() - Makes a copy of the internal resultset for branched queries.
- * Unlike this dynamic view, the branched resultset will not be 'live' updated,
- * so your branched query should be immediately resolved and not held for future evaluation.
- *
- * @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps
- * @param {object=} parameters - optional parameters (if optional transform requires them)
- * @returns {Resultset} A copy of the internal resultset for branched queries.
- * @memberof DynamicView
- * @example
- * var db = new loki('test');
- * var coll = db.addCollection('mydocs');
- * var dv = coll.addDynamicView('myview');
- * var tx = [
- * {
- * type: 'offset',
- * value: '[%lktxp]pageStart'
- * },
- * {
- * type: 'limit',
- * value: '[%lktxp]pageSize'
- * }
- * ];
- * coll.addTransform('viewPaging', tx);
- *
- * // add some records
- *
- * var results = dv.branchResultset('viewPaging', { pageStart: 10, pageSize: 10 }).data();
- */
- DynamicView.prototype.branchResultset = function (transform, parameters) {
- var rs = this.resultset.branch();
- if (typeof transform === 'undefined') {
- return rs;
- }
- return rs.transform(transform, parameters);
- };
- /**
- * toJSON() - Override of toJSON to avoid circular references
- *
- */
- DynamicView.prototype.toJSON = function () {
- var copy = new DynamicView(this.collection, this.name, this.options);
- copy.resultset = this.resultset;
- copy.resultdata = []; // let's not save data (copy) to minimize size
- copy.resultsdirty = true;
- copy.filterPipeline = this.filterPipeline;
- copy.sortFunction = this.sortFunction;
- copy.sortCriteria = this.sortCriteria;
- copy.sortCriteriaSimple = this.sortCriteriaSimple || null;
- copy.sortDirty = this.sortDirty;
- // avoid circular reference, reapply in db.loadJSON()
- copy.collection = null;
- return copy;
- };
- /**
- * removeFilters() - Used to clear pipeline and reset dynamic view to initial state.
- * Existing options should be retained.
- * @param {object=} options - configure removeFilter behavior
- * @param {boolean=} options.queueSortPhase - (default: false) if true we will async rebuild view (maybe set default to true in future?)
- * @memberof DynamicView
- */
- DynamicView.prototype.removeFilters = function (options) {
- options = options || {};
- this.rebuildPending = false;
- this.resultset.reset();
- this.resultdata = [];
- this.resultsdirty = true;
- this.cachedresultset = null;
- // keep ordered filter pipeline
- this.filterPipeline = [];
- // sorting member variables
- // we only support one active search, applied using applySort() or applySimpleSort()
- this.sortFunction = null;
- this.sortCriteria = null;
- this.sortCriteriaSimple = null;
- this.sortDirty = false;
- if (options.queueSortPhase === true) {
- this.queueSortPhase();
- }
- };
- /**
- * applySort() - Used to apply a sort to the dynamic view
- * @example
- * dv.applySort(function(obj1, obj2) {
- * if (obj1.name === obj2.name) return 0;
- * if (obj1.name > obj2.name) return 1;
- * if (obj1.name < obj2.name) return -1;
- * });
- *
- * @param {function} comparefun - a javascript compare function used for sorting
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.applySort = function (comparefun) {
- this.sortFunction = comparefun;
- this.sortCriteria = null;
- this.sortCriteriaSimple = null;
- this.queueSortPhase();
- return this;
- };
- /**
- * applySimpleSort() - Used to specify a property used for view translation.
- * @example
- * dv.applySimpleSort("name");
- *
- * @param {string} propname - Name of property by which to sort.
- * @param {object|boolean=} options - boolean for sort descending or options object
- * @param {boolean} [options.desc=false] - whether we should sort descending.
- * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection.
- * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists).
- * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort.
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.applySimpleSort = function (propname, options) {
- this.sortCriteriaSimple = { propname: propname, options: options || false };
- this.sortCriteria = null;
- this.sortFunction = null;
- this.queueSortPhase();
- return this;
- };
- /**
- * applySortCriteria() - Allows sorting a resultset based on multiple columns.
- * @example
- * // to sort by age and then name (both ascending)
- * dv.applySortCriteria(['age', 'name']);
- * // to sort by age (ascending) and then by name (descending)
- * dv.applySortCriteria(['age', ['name', true]);
- * // to sort by age (descending) and then by name (descending)
- * dv.applySortCriteria(['age', true], ['name', true]);
- *
- * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
- * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations.
- * @memberof DynamicView
- */
- DynamicView.prototype.applySortCriteria = function (criteria) {
- this.sortCriteria = criteria;
- this.sortCriteriaSimple = null;
- this.sortFunction = null;
- this.queueSortPhase();
- return this;
- };
- /**
- * startTransaction() - marks the beginning of a transaction.
- *
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- */
- DynamicView.prototype.startTransaction = function () {
- this.cachedresultset = this.resultset.copy();
- return this;
- };
- /**
- * commit() - commits a transaction.
- *
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- */
- DynamicView.prototype.commit = function () {
- this.cachedresultset = null;
- return this;
- };
- /**
- * rollback() - rolls back a transaction.
- *
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- */
- DynamicView.prototype.rollback = function () {
- this.resultset = this.cachedresultset;
- if (this.options.persistent) {
- // for now just rebuild the persistent dynamic view data in this worst case scenario
- // (a persistent view utilizing transactions which get rolled back), we already know the filter so not too bad.
- this.resultdata = this.resultset.data();
- this.emit('rebuild', this);
- }
- return this;
- };
- /**
- * Implementation detail.
- * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID.
- *
- * @param {(string|number)} uid - The unique ID of the filter.
- * @returns {number}: index of the referenced filter in the pipeline; -1 if not found.
- */
- DynamicView.prototype._indexOfFilterWithId = function (uid) {
- if (typeof uid === 'string' || typeof uid === 'number') {
- for (var idx = 0, len = this.filterPipeline.length; idx < len; idx += 1) {
- if (uid === this.filterPipeline[idx].uid) {
- return idx;
- }
- }
- }
- return -1;
- };
- /**
- * Implementation detail.
- * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset.
- *
- * @param {object} filter - The filter object. Refer to applyFilter() for extra details.
- */
- DynamicView.prototype._addFilter = function (filter) {
- this.filterPipeline.push(filter);
- this.resultset[filter.type](filter.val);
- };
- /**
- * reapplyFilters() - Reapply all the filters in the current pipeline.
- *
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- */
- DynamicView.prototype.reapplyFilters = function () {
- this.resultset.reset();
- this.cachedresultset = null;
- if (this.options.persistent) {
- this.resultdata = [];
- this.resultsdirty = true;
- }
- var filters = this.filterPipeline;
- this.filterPipeline = [];
- for (var idx = 0, len = filters.length; idx < len; idx += 1) {
- this._addFilter(filters[idx]);
- }
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return this;
- };
- /**
- * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline
- *
- * @param {object} filter - A filter object to add to the pipeline.
- * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id }
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.applyFilter = function (filter) {
- var idx = this._indexOfFilterWithId(filter.uid);
- if (idx >= 0) {
- this.filterPipeline[idx] = filter;
- return this.reapplyFilters();
- }
- this.cachedresultset = null;
- if (this.options.persistent) {
- this.resultdata = [];
- this.resultsdirty = true;
- }
- this._addFilter(filter);
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return this;
- };
- /**
- * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline
- *
- * @param {object} query - A mongo-style query object to apply to pipeline
- * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future.
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.applyFind = function (query, uid) {
- this.applyFilter({
- type: 'find',
- val: query,
- uid: uid
- });
- return this;
- };
- /**
- * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline
- *
- * @param {function} fun - A javascript filter function to apply to pipeline
- * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future.
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.applyWhere = function (fun, uid) {
- this.applyFilter({
- type: 'where',
- val: fun,
- uid: uid
- });
- return this;
- };
- /**
- * removeFilter() - Remove the specified filter from the DynamicView filter pipeline
- *
- * @param {(string|number)} uid - The unique ID of the filter to be removed.
- * @returns {DynamicView} this DynamicView object, for further chain ops.
- * @memberof DynamicView
- */
- DynamicView.prototype.removeFilter = function (uid) {
- var idx = this._indexOfFilterWithId(uid);
- if (idx < 0) {
- throw new Error("Dynamic view does not contain a filter with ID: " + uid);
- }
- this.filterPipeline.splice(idx, 1);
- this.reapplyFilters();
- return this;
- };
- /**
- * count() - returns the number of documents representing the current DynamicView contents.
- *
- * @returns {number} The number of documents representing the current DynamicView contents.
- * @memberof DynamicView
- */
- DynamicView.prototype.count = function () {
- // in order to be accurate we will pay the minimum cost (and not alter dv state management)
- // recurring resultset data resolutions should know internally its already up to date.
- // for persistent data this will not update resultdata nor fire rebuild event.
- if (this.resultsdirty) {
- this.resultdata = this.resultset.data();
- }
- return this.resultset.count();
- };
- /**
- * data() - resolves and pending filtering and sorting, then returns document array as result.
- *
- * @param {object=} options - optional parameters to pass to resultset.data() if non-persistent
- * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when
- * the collection is not configured for clone object.
- * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method.
- * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
- * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents
- * @returns {array} An array of documents representing the current DynamicView contents.
- * @memberof DynamicView
- */
- DynamicView.prototype.data = function (options) {
- // using final sort phase as 'catch all' for a few use cases which require full rebuild
- if (this.sortDirty || this.resultsdirty) {
- this.performSortPhase({
- suppressRebuildEvent: true
- });
- }
- return (this.options.persistent) ? (this.resultdata) : (this.resultset.data(options));
- };
- /**
- * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events.
- * This event will throttle and queue a single rebuild event when batches of updates affect the view.
- */
- DynamicView.prototype.queueRebuildEvent = function () {
- if (this.rebuildPending) {
- return;
- }
- this.rebuildPending = true;
- var self = this;
- setTimeout(function () {
- if (self.rebuildPending) {
- self.rebuildPending = false;
- self.emit('rebuild', self);
- }
- }, this.options.minRebuildInterval);
- };
- /**
- * queueSortPhase : If the view is sorted we will throttle sorting to either :
- * (1) passive - when the user calls data(), or
- * (2) active - once they stop updating and yield js thread control
- */
- DynamicView.prototype.queueSortPhase = function () {
- // already queued? exit without queuing again
- if (this.sortDirty) {
- return;
- }
- this.sortDirty = true;
- var self = this;
- if (this.options.sortPriority === "active") {
- // active sorting... once they are done and yield js thread, run async performSortPhase()
- setTimeout(function () {
- self.performSortPhase();
- }, this.options.minRebuildInterval);
- } else {
- // must be passive sorting... since not calling performSortPhase (until data call), lets use queueRebuildEvent to
- // potentially notify user that data has changed.
- this.queueRebuildEvent();
- }
- };
- /**
- * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed)
- *
- */
- DynamicView.prototype.performSortPhase = function (options) {
- // async call to this may have been pre-empted by synchronous call to data before async could fire
- if (!this.sortDirty && !this.resultsdirty) {
- return;
- }
- options = options || {};
- if (this.sortDirty) {
- if (this.sortFunction) {
- this.resultset.sort(this.sortFunction);
- } else if (this.sortCriteria) {
- this.resultset.compoundsort(this.sortCriteria);
- } else if (this.sortCriteriaSimple) {
- this.resultset.simplesort(this.sortCriteriaSimple.propname, this.sortCriteriaSimple.options);
- }
- this.sortDirty = false;
- }
- if (this.options.persistent) {
- // persistent view, rebuild local resultdata array
- this.resultdata = this.resultset.data();
- this.resultsdirty = false;
- }
- if (!options.suppressRebuildEvent) {
- this.emit('rebuild', this);
- }
- };
- /**
- * evaluateDocument() - internal method for (re)evaluating document inclusion.
- * Called by : collection.insert() and collection.update().
- *
- * @param {int} objIndex - index of document to (re)run through filter pipeline.
- * @param {bool} isNew - true if the document was just added to the collection.
- */
- DynamicView.prototype.evaluateDocument = function (objIndex, isNew) {
- // if no filter applied yet, the result 'set' should remain 'everything'
- if (!this.resultset.filterInitialized) {
- if (this.options.persistent) {
- this.resultdata = this.resultset.data();
- }
- // need to re-sort to sort new document
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return;
- }
- var ofr = this.resultset.filteredrows;
- var oldPos = (isNew) ? (-1) : (ofr.indexOf(+objIndex));
- var oldlen = ofr.length;
- // creating a 1-element resultset to run filter chain ops on to see if that doc passes filters;
- // mostly efficient algorithm, slight stack overhead price (this function is called on inserts and updates)
- var evalResultset = new Resultset(this.collection);
- evalResultset.filteredrows = [objIndex];
- evalResultset.filterInitialized = true;
- var filter;
- for (var idx = 0, len = this.filterPipeline.length; idx < len; idx++) {
- filter = this.filterPipeline[idx];
- evalResultset[filter.type](filter.val);
- }
- // not a true position, but -1 if not pass our filter(s), 0 if passed filter(s)
- var newPos = (evalResultset.filteredrows.length === 0) ? -1 : 0;
- // wasn't in old, shouldn't be now... do nothing
- if (oldPos === -1 && newPos === -1) return;
- // wasn't in resultset, should be now... add
- if (oldPos === -1 && newPos !== -1) {
- ofr.push(objIndex);
- if (this.options.persistent) {
- this.resultdata.push(this.collection.data[objIndex]);
- }
- // need to re-sort to sort new document
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return;
- }
- // was in resultset, shouldn't be now... delete
- if (oldPos !== -1 && newPos === -1) {
- if (oldPos < oldlen - 1) {
- ofr.splice(oldPos, 1);
- if (this.options.persistent) {
- this.resultdata.splice(oldPos, 1);
- }
- } else {
- ofr.length = oldlen - 1;
- if (this.options.persistent) {
- this.resultdata.length = oldlen - 1;
- }
- }
- // in case changes to data altered a sort column
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return;
- }
- // was in resultset, should still be now... (update persistent only?)
- if (oldPos !== -1 && newPos !== -1) {
- if (this.options.persistent) {
- // in case document changed, replace persistent view data with the latest collection.data document
- this.resultdata[oldPos] = this.collection.data[objIndex];
- }
- // in case changes to data altered a sort column
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return;
- }
- };
- /**
- * removeDocument() - internal function called on collection.delete()
- * @param {number|number[]} objIndex - index of document to (re)run through filter pipeline.
- */
- DynamicView.prototype.removeDocument = function (objIndex) {
- var idx, rmidx, rmlen, rxo = {}, fxo = {};
- var adjels = [];
- var drs = this.resultset;
- var fr = this.resultset.filteredrows;
- var frlen = fr.length;
- // if no filter applied yet, the result 'set' should remain 'everything'
- if (!this.resultset.filterInitialized) {
- if (this.options.persistent) {
- this.resultdata = this.resultset.data();
- }
- // in case changes to data altered a sort column
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- return;
- }
- // if passed single index, wrap in array
- if (!Array.isArray(objIndex)) {
- objIndex = [objIndex];
- }
- rmlen = objIndex.length;
- // create intersection object of data indices to remove
- for(rmidx=0;rmidx<rmlen; rmidx++) {
- rxo[objIndex[rmidx]] = true;
- }
- // pivot remove data indices into remove filteredrows indices and dump in hashobject
- for (idx=0; idx<frlen; idx++) {
- if (rxo[fr[idx]]) fxo[idx] = true;
- }
- // if any of the removed items were in our filteredrows...
- if (Object.keys(fxo).length > 0) {
- // remove them from filtered rows
- this.resultset.filteredrows = this.resultset.filteredrows.filter(function(di, idx) { return !fxo[idx]; });
- // if persistent...
- if (this.options.persistent) {
- // remove from resultdata
- this.resultdata = this.resultdata.filter(function(obj, idx) { return !fxo[idx]; });
- }
- // and queue sorts
- if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) {
- this.queueSortPhase();
- } else {
- this.queueRebuildEvent();
- }
- }
- // to remove holes, we need to 'shift down' indices, this filter function finds number of positions to shift
- var filt = function(idx) { return function(di) { return di < drs.filteredrows[idx]; }; };
- frlen = drs.filteredrows.length;
- for (idx = 0; idx < frlen; idx++) {
- // grab subset of removed elements where data index is less than current filtered row data index;
- // use this to determine how many positions iterated remaining data index needs to be 'shifted down'
- adjels = objIndex.filter(filt(idx));
- drs.filteredrows[idx] -= adjels.length;
- }
- };
- /**
- * mapReduce() - data transformation via user supplied functions
- *
- * @param {function} mapFunction - this function accepts a single document for you to transform and return
- * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
- * @returns The output of your reduceFunction
- * @memberof DynamicView
- */
- DynamicView.prototype.mapReduce = function (mapFunction, reduceFunction) {
- try {
- return reduceFunction(this.data().map(mapFunction));
- } catch (err) {
- throw err;
- }
- };
- /**
- * Collection class that handles documents of same type
- * @constructor Collection
- * @implements LokiEventEmitter
- * @param {string} name - collection name
- * @param {(array|object)=} options - (optional) array of property names to be indicized OR a configuration object
- * @param {array=} [options.unique=[]] - array of property names to define unique constraints for
- * @param {array=} [options.exact=[]] - array of property names to define exact constraints for
- * @param {array=} [options.indices=[]] - array property names to define binary indexes for
- * @param {boolean} [options.adaptiveBinaryIndices=true] - collection indices will be actively rebuilt rather than lazily
- * @param {boolean} [options.asyncListeners=false] - whether listeners are invoked asynchronously
- * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
- * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes API
- * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
- * @param {boolean} [options.autoupdate=false] - use Object.observe to update objects automatically
- * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
- * @param {boolean} [options.serializableIndices=true[]] - converts date values on binary indexed properties to epoch time
- * @param {string} [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
- * @param {int=} options.ttl - age of document (in ms.) before document is considered aged/stale.
- * @param {int=} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
- * @see {@link Loki#addCollection} for normal creation of collections
- */
- function Collection(name, options) {
- // the name of the collection
- this.name = name;
- // the data held by the collection
- this.data = [];
- this.idIndex = []; // index of id
- this.binaryIndices = {}; // user defined indexes
- this.constraints = {
- unique: {},
- exact: {}
- };
- // unique contraints contain duplicate object references, so they are not persisted.
- // we will keep track of properties which have unique contraint applied here, and regenerate on load
- this.uniqueNames = [];
- // transforms will be used to store frequently used query chains as a series of steps
- // which itself can be stored along with the database.
- this.transforms = {};
- // the object type of the collection
- this.objType = name;
- // in autosave scenarios we will use collection level dirty flags to determine whether save is needed.
- // currently, if any collection is dirty we will autosave the whole database if autosave is configured.
- // defaulting to true since this is called from addCollection and adding a collection should trigger save
- this.dirty = true;
- // private holders for cached data
- this.cachedIndex = null;
- this.cachedBinaryIndex = null;
- this.cachedData = null;
- var self = this;
- /* OPTIONS */
- options = options || {};
- // exact match and unique constraints
- if (options.hasOwnProperty('unique')) {
- if (!Array.isArray(options.unique)) {
- options.unique = [options.unique];
- }
- options.unique.forEach(function (prop) {
- self.uniqueNames.push(prop); // used to regenerate on subsequent database loads
- self.constraints.unique[prop] = new UniqueIndex(prop);
- });
- }
- if (options.hasOwnProperty('exact')) {
- options.exact.forEach(function (prop) {
- self.constraints.exact[prop] = new ExactIndex(prop);
- });
- }
- // if set to true we will optimally keep indices 'fresh' during insert/update/remove ops (never dirty/never needs rebuild)
- // if you frequently intersperse insert/update/remove ops between find ops this will likely be significantly faster option.
- this.adaptiveBinaryIndices = options.hasOwnProperty('adaptiveBinaryIndices') ? options.adaptiveBinaryIndices : true;
- // is collection transactional
- this.transactional = options.hasOwnProperty('transactional') ? options.transactional : false;
- // options to clone objects when inserting them
- this.cloneObjects = options.hasOwnProperty('clone') ? options.clone : false;
- // default clone method (if enabled) is parse-stringify
- this.cloneMethod = options.hasOwnProperty('cloneMethod') ? options.cloneMethod : "parse-stringify";
- // option to make event listeners async, default is sync
- this.asyncListeners = options.hasOwnProperty('asyncListeners') ? options.asyncListeners : false;
- // if set to true we will not maintain a meta property for a document
- this.disableMeta = options.hasOwnProperty('disableMeta') ? options.disableMeta : false;
- // disable track changes
- this.disableChangesApi = options.hasOwnProperty('disableChangesApi') ? options.disableChangesApi : true;
- // disable delta update object style on changes
- this.disableDeltaChangesApi = options.hasOwnProperty('disableDeltaChangesApi') ? options.disableDeltaChangesApi : true;
- if (this.disableChangesApi) { this.disableDeltaChangesApi = true; }
- // option to observe objects and update them automatically, ignored if Object.observe is not supported
- this.autoupdate = options.hasOwnProperty('autoupdate') ? options.autoupdate : false;
- // by default, if you insert a document into a collection with binary indices, if those indexed properties contain
- // a DateTime we will convert to epoch time format so that (across serializations) its value position will be the
- // same 'after' serialization as it was 'before'.
- this.serializableIndices = options.hasOwnProperty('serializableIndices') ? options.serializableIndices : true;
- //option to activate a cleaner daemon - clears "aged" documents at set intervals.
- this.ttl = {
- age: null,
- ttlInterval: null,
- daemon: null
- };
- this.setTTL(options.ttl || -1, options.ttlInterval);
- // currentMaxId - change manually at your own peril!
- this.maxId = 0;
- this.DynamicViews = [];
- // events
- this.events = {
- 'insert': [],
- 'update': [],
- 'pre-insert': [],
- 'pre-update': [],
- 'close': [],
- 'flushbuffer': [],
- 'error': [],
- 'delete': [],
- 'warning': []
- };
- // changes are tracked by collection and aggregated by the db
- this.changes = [];
- // initialize the id index
- this.ensureId();
- var indices = [];
- // initialize optional user-supplied indices array ['age', 'lname', 'zip']
- if (options && options.indices) {
- if (Object.prototype.toString.call(options.indices) === '[object Array]') {
- indices = options.indices;
- } else if (typeof options.indices === 'string') {
- indices = [options.indices];
- } else {
- throw new TypeError('Indices needs to be a string or an array of strings');
- }
- }
- for (var idx = 0; idx < indices.length; idx++) {
- this.ensureIndex(indices[idx]);
- }
- function observerCallback(changes) {
- var changedObjects = typeof Set === 'function' ? new Set() : [];
- if (!changedObjects.add)
- changedObjects.add = function (object) {
- if (this.indexOf(object) === -1)
- this.push(object);
- return this;
- };
- changes.forEach(function (change) {
- changedObjects.add(change.object);
- });
- changedObjects.forEach(function (object) {
- if (!hasOwnProperty.call(object, '$loki'))
- return self.removeAutoUpdateObserver(object);
- try {
- self.update(object);
- } catch (err) {}
- });
- }
- this.observerCallback = observerCallback;
- //Compare changed object (which is a forced clone) with existing object and return the delta
- function getChangeDelta(obj, old) {
- if (old) {
- return getObjectDelta(old, obj);
- }
- else {
- return JSON.parse(JSON.stringify(obj));
- }
- }
- this.getChangeDelta = getChangeDelta;
- function getObjectDelta(oldObject, newObject) {
- var propertyNames = newObject !== null && typeof newObject === 'object' ? Object.keys(newObject) : null;
- if (propertyNames && propertyNames.length && ['string', 'boolean', 'number'].indexOf(typeof(newObject)) < 0) {
- var delta = {};
- for (var i = 0; i < propertyNames.length; i++) {
- var propertyName = propertyNames[i];
- if (newObject.hasOwnProperty(propertyName)) {
- if (!oldObject.hasOwnProperty(propertyName) || self.uniqueNames.indexOf(propertyName) >= 0 || propertyName == '$loki' || propertyName == 'meta') {
- delta[propertyName] = newObject[propertyName];
- }
- else {
- var propertyDelta = getObjectDelta(oldObject[propertyName], newObject[propertyName]);
- if (typeof propertyDelta !== "undefined" && propertyDelta != {}) {
- delta[propertyName] = propertyDelta;
- }
- }
- }
- }
- return Object.keys(delta).length === 0 ? undefined : delta;
- }
- else {
- return oldObject === newObject ? undefined : newObject;
- }
- }
- this.getObjectDelta = getObjectDelta;
- // clear all the changes
- function flushChanges() {
- self.changes = [];
- }
- this.getChanges = function () {
- return self.changes;
- };
- this.flushChanges = flushChanges;
- this.setChangesApi = function (enabled) {
- self.disableChangesApi = !enabled;
- if (!enabled) { self.disableDeltaChangesApi = false; }
- };
- this.on('delete', function deleteCallback(obj) {
- if (!self.disableChangesApi) {
- self.createChange(self.name, 'R', obj);
- }
- });
- this.on('warning', function (warning) {
- self.console.warn(warning);
- });
- // for de-serialization purposes
- flushChanges();
- }
- Collection.prototype = new LokiEventEmitter();
- /*
- * For ChangeAPI default to clone entire object, for delta changes create object with only differences (+ $loki and meta)
- */
- Collection.prototype.createChange = function(name, op, obj, old) {
- this.changes.push({
- name: name,
- operation: op,
- obj: op == 'U' && !this.disableDeltaChangesApi ? this.getChangeDelta(obj, old) : JSON.parse(JSON.stringify(obj))
- });
- };
- Collection.prototype.insertMeta = function(obj) {
- var len, idx;
- if (this.disableMeta || !obj) {
- return;
- }
- // if batch insert
- if (Array.isArray(obj)) {
- len = obj.length;
- for(idx=0; idx<len; idx++) {
- if (!obj[idx].hasOwnProperty('meta')) {
- obj[idx].meta = {};
- }
- obj[idx].meta.created = (new Date()).getTime();
- obj[idx].meta.revision = 0;
- }
- return;
- }
- // single object
- if (!obj.meta) {
- obj.meta = {};
- }
- obj.meta.created = (new Date()).getTime();
- obj.meta.revision = 0;
- };
- Collection.prototype.updateMeta = function(obj) {
- if (this.disableMeta || !obj) {
- return;
- }
- obj.meta.updated = (new Date()).getTime();
- obj.meta.revision += 1;
- };
- Collection.prototype.createInsertChange = function(obj) {
- this.createChange(this.name, 'I', obj);
- };
- Collection.prototype.createUpdateChange = function(obj, old) {
- this.createChange(this.name, 'U', obj, old);
- };
- Collection.prototype.insertMetaWithChange = function(obj) {
- this.insertMeta(obj);
- this.createInsertChange(obj);
- };
- Collection.prototype.updateMetaWithChange = function(obj, old) {
- this.updateMeta(obj);
- this.createUpdateChange(obj, old);
- };
- Collection.prototype.console = {
- log: function () {},
- warn: function () {},
- error: function () {},
- };
- Collection.prototype.addAutoUpdateObserver = function (object) {
- if (!this.autoupdate || typeof Object.observe !== 'function')
- return;
- Object.observe(object, this.observerCallback, ['add', 'update', 'delete', 'reconfigure', 'setPrototype']);
- };
- Collection.prototype.removeAutoUpdateObserver = function (object) {
- if (!this.autoupdate || typeof Object.observe !== 'function')
- return;
- Object.unobserve(object, this.observerCallback);
- };
- /**
- * Adds a named collection transform to the collection
- * @param {string} name - name to associate with transform
- * @param {array} transform - an array of transformation 'step' objects to save into the collection
- * @memberof Collection
- * @example
- * users.addTransform('progeny', [
- * {
- * type: 'find',
- * value: {
- * 'age': {'$lte': 40}
- * }
- * }
- * ]);
- *
- * var results = users.chain('progeny').data();
- */
- Collection.prototype.addTransform = function (name, transform) {
- if (this.transforms.hasOwnProperty(name)) {
- throw new Error("a transform by that name already exists");
- }
- this.transforms[name] = transform;
- };
- /**
- * Retrieves a named transform from the collection.
- * @param {string} name - name of the transform to lookup.
- * @memberof Collection
- */
- Collection.prototype.getTransform = function (name) {
- return this.transforms[name];
- };
- /**
- * Updates a named collection transform to the collection
- * @param {string} name - name to associate with transform
- * @param {object} transform - a transformation object to save into collection
- * @memberof Collection
- */
- Collection.prototype.setTransform = function (name, transform) {
- this.transforms[name] = transform;
- };
- /**
- * Removes a named collection transform from the collection
- * @param {string} name - name of collection transform to remove
- * @memberof Collection
- */
- Collection.prototype.removeTransform = function (name) {
- delete this.transforms[name];
- };
- Collection.prototype.byExample = function (template) {
- var k, obj, query;
- query = [];
- for (k in template) {
- if (!template.hasOwnProperty(k)) continue;
- query.push((
- obj = {},
- obj[k] = template[k],
- obj
- ));
- }
- return {
- '$and': query
- };
- };
- Collection.prototype.findObject = function (template) {
- return this.findOne(this.byExample(template));
- };
- Collection.prototype.findObjects = function (template) {
- return this.find(this.byExample(template));
- };
- /*----------------------------+
- | TTL daemon |
- +----------------------------*/
- Collection.prototype.ttlDaemonFuncGen = function () {
- var collection = this;
- var age = this.ttl.age;
- return function ttlDaemon() {
- var now = Date.now();
- var toRemove = collection.chain().where(function daemonFilter(member) {
- var timestamp = member.meta.updated || member.meta.created;
- var diff = now - timestamp;
- return age < diff;
- });
- toRemove.remove();
- };
- };
- /**
- * Updates or applies collection TTL settings.
- * @param {int} age - age (in ms) to expire document from collection
- * @param {int} interval - time (in ms) to clear collection of aged documents.
- * @memberof Collection
- */
- Collection.prototype.setTTL = function (age, interval) {
- if (age < 0) {
- clearInterval(this.ttl.daemon);
- } else {
- this.ttl.age = age;
- this.ttl.ttlInterval = interval;
- this.ttl.daemon = setInterval(this.ttlDaemonFuncGen(), interval);
- }
- };
- /*----------------------------+
- | INDEXING |
- +----------------------------*/
- /**
- * create a row filter that covers all documents in the collection
- */
- Collection.prototype.prepareFullDocIndex = function () {
- var len = this.data.length;
- var indexes = new Array(len);
- for (var i = 0; i < len; i += 1) {
- indexes[i] = i;
- }
- return indexes;
- };
- /**
- * Will allow reconfiguring certain collection options.
- * @param {boolean} options.adaptiveBinaryIndices - collection indices will be actively rebuilt rather than lazily
- * @memberof Collection
- */
- Collection.prototype.configureOptions = function (options) {
- options = options || {};
- if (options.hasOwnProperty('adaptiveBinaryIndices')) {
- this.adaptiveBinaryIndices = options.adaptiveBinaryIndices;
- // if switching to adaptive binary indices, make sure none are 'dirty'
- if (this.adaptiveBinaryIndices) {
- this.ensureAllIndexes();
- }
- }
- };
- /**
- * Ensure binary index on a certain field
- * @param {string} property - name of property to create binary index on
- * @param {boolean=} force - (Optional) flag indicating whether to construct index immediately
- * @memberof Collection
- */
- Collection.prototype.ensureIndex = function (property, force) {
- // optional parameter to force rebuild whether flagged as dirty or not
- if (typeof (force) === 'undefined') {
- force = false;
- }
- if (property === null || property === undefined) {
- throw new Error('Attempting to set index without an associated property');
- }
- if (this.binaryIndices[property] && !force) {
- if (!this.binaryIndices[property].dirty) return;
- }
- // if the index is already defined and we are using adaptiveBinaryIndices and we are not forcing a rebuild, return.
- if (this.adaptiveBinaryIndices === true && this.binaryIndices.hasOwnProperty(property) && !force) {
- return;
- }
- var index = {
- 'name': property,
- 'dirty': true,
- 'values': this.prepareFullDocIndex()
- };
- this.binaryIndices[property] = index;
- var wrappedComparer =
- (function (prop, data) {
- var val1, val2, arr;
- return function (a, b) {
- if (~prop.indexOf('.')) {
- arr = prop.split('.');
- val1 = Utils.getIn(data[a], arr, true);
- val2 = Utils.getIn(data[b], arr, true);
- } else {
- val1 = data[a][prop];
- val2 = data[b][prop];
- }
- if (val1 !== val2) {
- if (Comparators.lt(val1, val2, false)) return -1;
- if (Comparators.gt(val1, val2, false)) return 1;
- }
- return 0;
- };
- })(property, this.data);
- index.values.sort(wrappedComparer);
- index.dirty = false;
- this.dirty = true; // for autosave scenarios
- };
- /**
- * Perform checks to determine validity/consistency of all binary indices
- * @param {object=} options - optional configuration object
- * @param {boolean} [options.randomSampling=false] - whether (faster) random sampling should be used
- * @param {number} [options.randomSamplingFactor=0.10] - percentage of total rows to randomly sample
- * @param {boolean} [options.repair=false] - whether to fix problems if they are encountered
- * @returns {string[]} array of index names where problems were found.
- * @memberof Collection
- * @example
- * // check all indices on a collection, returns array of invalid index names
- * var result = coll.checkAllIndexes({ repair: true, randomSampling: true, randomSamplingFactor: 0.15 });
- * if (result.length > 0) {
- * results.forEach(function(name) {
- * console.log('problem encountered with index : ' + name);
- * });
- * }
- */
- Collection.prototype.checkAllIndexes = function (options) {
- var key, bIndices = this.binaryIndices;
- var results = [], result;
- for (key in bIndices) {
- if (hasOwnProperty.call(bIndices, key)) {
- result = this.checkIndex(key, options);
- if (!result) {
- results.push(key);
- }
- }
- }
- return results;
- };
- /**
- * Perform checks to determine validity/consistency of a binary index
- * @param {string} property - name of the binary-indexed property to check
- * @param {object=} options - optional configuration object
- * @param {boolean} [options.randomSampling=false] - whether (faster) random sampling should be used
- * @param {number} [options.randomSamplingFactor=0.10] - percentage of total rows to randomly sample
- * @param {boolean} [options.repair=false] - whether to fix problems if they are encountered
- * @returns {boolean} whether the index was found to be valid (before optional correcting).
- * @memberof Collection
- * @example
- * // full test
- * var valid = coll.checkIndex('name');
- * // full test with repair (if issues found)
- * valid = coll.checkIndex('name', { repair: true });
- * // random sampling (default is 10% of total document count)
- * valid = coll.checkIndex('name', { randomSampling: true });
- * // random sampling (sample 20% of total document count)
- * valid = coll.checkIndex('name', { randomSampling: true, randomSamplingFactor: 0.20 });
- * // random sampling (implied boolean)
- * valid = coll.checkIndex('name', { randomSamplingFactor: 0.20 });
- * // random sampling with repair (if issues found)
- * valid = coll.checkIndex('name', { repair: true, randomSampling: true });
- */
- Collection.prototype.checkIndex = function (property, options) {
- options = options || {};
- // if 'randomSamplingFactor' specified but not 'randomSampling', assume true
- if (options.randomSamplingFactor && options.randomSampling !== false) {
- options.randomSampling = true;
- }
- options.randomSamplingFactor = options.randomSamplingFactor || 0.1;
- if (options.randomSamplingFactor < 0 || options.randomSamplingFactor > 1) {
- options.randomSamplingFactor = 0.1;
- }
- var valid=true, idx, iter, pos, len, biv;
- // make sure we are passed a valid binary index name
- if (!this.binaryIndices.hasOwnProperty(property)) {
- throw new Error("called checkIndex on property without an index: " + property);
- }
- // if lazy indexing, rebuild only if flagged as dirty
- if (!this.adaptiveBinaryIndices) {
- this.ensureIndex(property);
- }
- biv = this.binaryIndices[property].values;
- len = biv.length;
- // if the index has an incorrect number of values
- if (len !== this.data.length) {
- if (options.repair) {
- this.ensureIndex(property, true);
- }
- return false;
- }
- if (len === 0) {
- return true;
- }
- var usingDotNotation = (property.indexOf('.') !== -1);
- if (len === 1) {
- valid = (biv[0] === 0);
- }
- else {
- if (options.randomSampling) {
- // validate first and last
- if (!LokiOps.$lte(Utils.getIn(this.data[biv[0]], property, usingDotNotation),
- Utils.getIn(this.data[biv[1]], property, usingDotNotation))) {
- valid=false;
- }
- if (!LokiOps.$lte(Utils.getIn(this.data[biv[len-2]], property, usingDotNotation),
- Utils.getIn(this.data[biv[len-1]], property, usingDotNotation))) {
- valid=false;
- }
- // if first and last positions are sorted correctly with their nearest neighbor,
- // continue onto random sampling phase...
- if (valid) {
- // # random samplings = total count * sampling factor
- iter = Math.floor((len-1) * options.randomSamplingFactor);
- // for each random sampling, validate that the binary index is sequenced properly
- // with next higher value.
- for(idx=0; idx<iter-1; idx++) {
- // calculate random position
- pos = Math.floor(Math.random() * (len-1));
- if (!LokiOps.$lte(Utils.getIn(this.data[biv[pos]], property, usingDotNotation),
- Utils.getIn(this.data[biv[pos+1]], property, usingDotNotation))) {
- valid=false;
- break;
- }
- }
- }
- }
- else {
- // validate that the binary index is sequenced properly
- for(idx=0; idx<len-1; idx++) {
- if (!LokiOps.$lte(Utils.getIn(this.data[biv[idx]], property, usingDotNotation),
- Utils.getIn(this.data[biv[idx+1]], property, usingDotNotation))) {
- valid=false;
- break;
- }
- }
- }
- }
- // if incorrectly sequenced and we are to fix problems, rebuild index
- if (!valid && options.repair) {
- this.ensureIndex(property, true);
- }
- return valid;
- };
- Collection.prototype.getBinaryIndexValues = function (property) {
- var idx, idxvals = this.binaryIndices[property].values;
- var result = [];
- for (idx = 0; idx < idxvals.length; idx++) {
- result.push(Utils.getIn(this.data[idxvals[idx]], property, true));
- }
- return result;
- };
- Collection.prototype.ensureUniqueIndex = function (field) {
- var index = this.constraints.unique[field];
- if (!index) {
- // keep track of new unique index for regenerate after database (re)load.
- if (this.uniqueNames.indexOf(field) == -1) {
- this.uniqueNames.push(field);
- }
- }
- // if index already existed, (re)loading it will likely cause collisions, rebuild always
- this.constraints.unique[field] = index = new UniqueIndex(field);
- this.data.forEach(function (obj) {
- index.set(obj);
- });
- return index;
- };
- /**
- * Ensure all binary indices
- * @param {boolean} force - whether to force rebuild of existing lazy binary indices
- * @memberof Collection
- */
- Collection.prototype.ensureAllIndexes = function (force) {
- var key, bIndices = this.binaryIndices;
- for (key in bIndices) {
- if (hasOwnProperty.call(bIndices, key)) {
- this.ensureIndex(key, force);
- }
- }
- };
- /**
- * Internal method used to flag all lazy index as dirty
- */
- Collection.prototype.flagBinaryIndexesDirty = function () {
- var key, bIndices = this.binaryIndices;
- for (key in bIndices) {
- if (hasOwnProperty.call(bIndices, key)) {
- bIndices[key].dirty = true;
- }
- }
- };
- /**
- * Internal method used to flag a lazy index as dirty
- */
- Collection.prototype.flagBinaryIndexDirty = function (index) {
- if (this.binaryIndices[index])
- this.binaryIndices[index].dirty = true;
- };
- /**
- * Quickly determine number of documents in collection (or query)
- * @param {object=} query - (optional) query object to count results of
- * @returns {number} number of documents in the collection
- * @memberof Collection
- */
- Collection.prototype.count = function (query) {
- if (!query) {
- return this.data.length;
- }
- return this.chain().find(query).filteredrows.length;
- };
- /**
- * Rebuild idIndex
- */
- Collection.prototype.ensureId = function () {
- var len = this.data.length,
- i = 0;
- this.idIndex = [];
- for (i; i < len; i += 1) {
- this.idIndex.push(this.data[i].$loki);
- }
- };
- /**
- * Rebuild idIndex async with callback - useful for background syncing with a remote server
- */
- Collection.prototype.ensureIdAsync = function (callback) {
- this.async(function () {
- this.ensureId();
- }, callback);
- };
- /**
- * Add a dynamic view to the collection
- * @param {string} name - name of dynamic view to add
- * @param {object=} options - options to configure dynamic view with
- * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
- * @param {string} [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates)
- * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here)
- * @returns {DynamicView} reference to the dynamic view added
- * @memberof Collection
- * @example
- * var pview = users.addDynamicView('progeny');
- * pview.applyFind({'age': {'$lte': 40}});
- * pview.applySimpleSort('name');
- *
- * var results = pview.data();
- **/
- Collection.prototype.addDynamicView = function (name, options) {
- var dv = new DynamicView(this, name, options);
- this.DynamicViews.push(dv);
- return dv;
- };
- /**
- * Remove a dynamic view from the collection
- * @param {string} name - name of dynamic view to remove
- * @memberof Collection
- **/
- Collection.prototype.removeDynamicView = function (name) {
- this.DynamicViews =
- this.DynamicViews.filter(function(dv) { return dv.name !== name; });
- };
- /**
- * Look up dynamic view reference from within the collection
- * @param {string} name - name of dynamic view to retrieve reference of
- * @returns {DynamicView} A reference to the dynamic view with that name
- * @memberof Collection
- **/
- Collection.prototype.getDynamicView = function (name) {
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- if (this.DynamicViews[idx].name === name) {
- return this.DynamicViews[idx];
- }
- }
- return null;
- };
- /**
- * Applies a 'mongo-like' find query object and passes all results to an update function.
- * For filter function querying you should migrate to [updateWhere()]{@link Collection#updateWhere}.
- *
- * @param {object|function} filterObject - 'mongo-like' query object (or deprecated filterFunction mode)
- * @param {function} updateFunction - update function to run against filtered documents
- * @memberof Collection
- */
- Collection.prototype.findAndUpdate = function (filterObject, updateFunction) {
- if (typeof (filterObject) === "function") {
- this.updateWhere(filterObject, updateFunction);
- }
- else {
- this.chain().find(filterObject).update(updateFunction);
- }
- };
- /**
- * Applies a 'mongo-like' find query object removes all documents which match that filter.
- *
- * @param {object} filterObject - 'mongo-like' query object
- * @memberof Collection
- */
- Collection.prototype.findAndRemove = function(filterObject) {
- this.chain().find(filterObject).remove();
- };
- /**
- * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc.
- * @param {(object|array)} doc - the document (or array of documents) to be inserted
- * @returns {(object|array)} document or documents inserted
- * @memberof Collection
- * @example
- * users.insert({
- * name: 'Odin',
- * age: 50,
- * address: 'Asgard'
- * });
- *
- * // alternatively, insert array of documents
- * users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]);
- */
- Collection.prototype.insert = function (doc) {
- if (!Array.isArray(doc)) {
- return this.insertOne(doc);
- }
- // holder to the clone of the object inserted if collections is set to clone objects
- var obj;
- var results = [];
- this.emit('pre-insert', doc);
- for (var i = 0, len = doc.length; i < len; i++) {
- obj = this.insertOne(doc[i], true);
- if (!obj) {
- return undefined;
- }
- results.push(obj);
- }
- // at the 'batch' level, if clone option is true then emitted docs are clones
- this.emit('insert', results);
- // if clone option is set, clone return values
- results = this.cloneObjects ? clone(results, this.cloneMethod) : results;
- return results.length === 1 ? results[0] : results;
- };
- /**
- * Adds a single object, ensures it has meta properties, clone it if necessary, etc.
- * @param {object} doc - the document to be inserted
- * @param {boolean} bulkInsert - quiet pre-insert and insert event emits
- * @returns {object} document or 'undefined' if there was a problem inserting it
- */
- Collection.prototype.insertOne = function (doc, bulkInsert) {
- var err = null;
- var returnObj;
- if (typeof doc !== 'object') {
- err = new TypeError('Document needs to be an object');
- } else if (doc === null) {
- err = new TypeError('Object cannot be null');
- }
- if (err !== null) {
- this.emit('error', err);
- throw err;
- }
- // if configured to clone, do so now... otherwise just use same obj reference
- var obj = this.cloneObjects ? clone(doc, this.cloneMethod) : doc;
- if (!this.disableMeta && typeof obj.meta === 'undefined') {
- obj.meta = {
- revision: 0,
- created: 0
- };
- }
- // both 'pre-insert' and 'insert' events are passed internal data reference even when cloning
- // insert needs internal reference because that is where loki itself listens to add meta
- if (!bulkInsert) {
- this.emit('pre-insert', obj);
- }
- if (!this.add(obj)) {
- return undefined;
- }
- // update meta and store changes if ChangesAPI is enabled
- // (moved from "insert" event listener to allow internal reference to be used)
- if (this.disableChangesApi) {
- this.insertMeta(obj);
- }
- else {
- this.insertMetaWithChange(obj);
- }
- // if cloning is enabled, emit insert event with clone of new object
- returnObj = this.cloneObjects ? clone(obj, this.cloneMethod) : obj;
- if (!bulkInsert) {
- this.emit('insert', returnObj);
- }
- this.addAutoUpdateObserver(returnObj);
- return returnObj;
- };
- /**
- * Empties the collection.
- * @param {object=} options - configure clear behavior
- * @param {bool=} [options.removeIndices=false] - whether to remove indices in addition to data
- * @memberof Collection
- */
- Collection.prototype.clear = function (options) {
- var self = this;
- options = options || {};
- this.data = [];
- this.idIndex = [];
- this.cachedIndex = null;
- this.cachedBinaryIndex = null;
- this.cachedData = null;
- this.maxId = 0;
- this.DynamicViews = [];
- this.dirty = true;
- // if removing indices entirely
- if (options.removeIndices === true) {
- this.binaryIndices = {};
- this.constraints = {
- unique: {},
- exact: {}
- };
- this.uniqueNames = [];
- }
- // clear indices but leave definitions in place
- else {
- // clear binary indices
- var keys = Object.keys(this.binaryIndices);
- keys.forEach(function(biname) {
- self.binaryIndices[biname].dirty = false;
- self.binaryIndices[biname].values = [];
- });
- // clear entire unique indices definition
- this.constraints = {
- unique: {},
- exact: {}
- };
- // add definitions back
- this.uniqueNames.forEach(function(uiname) {
- self.ensureUniqueIndex(uiname);
- });
- }
- };
- /**
- * Updates an object and notifies collection that the document has changed.
- * @param {object} doc - document to update within the collection
- * @memberof Collection
- */
- Collection.prototype.update = function (doc) {
- var adaptiveBatchOverride, k, len;
- if (Array.isArray(doc)) {
- len = doc.length;
- // if not cloning, disable adaptive binary indices for the duration of the batch update,
- // followed by lazy rebuild and re-enabling adaptive indices after batch update.
- adaptiveBatchOverride = !this.cloneObjects &&
- this.adaptiveBinaryIndices && Object.keys(this.binaryIndices).length > 0;
- if (adaptiveBatchOverride) {
- this.adaptiveBinaryIndices = false;
- }
- try {
- for (k=0; k < len; k += 1) {
- this.update(doc[k]);
- }
- }
- finally {
- if (adaptiveBatchOverride) {
- this.ensureAllIndexes();
- this.adaptiveBinaryIndices = true;
- }
- }
- return;
- }
- // verify object is a properly formed document
- if (!hasOwnProperty.call(doc, '$loki')) {
- throw new Error('Trying to update unsynced document. Please save the document first by using insert() or addMany()');
- }
- try {
- this.startTransaction();
- var arr = this.get(doc.$loki, true),
- oldInternal, // ref to existing obj
- newInternal, // ref to new internal obj
- position,
- self = this;
- if (!arr) {
- throw new Error('Trying to update a document not in collection.');
- }
- oldInternal = arr[0]; // -internal- obj ref
- position = arr[1]; // position in data array
- // if configured to clone, do so now... otherwise just use same obj reference
- newInternal = this.cloneObjects || !this.disableDeltaChangesApi ? clone(doc, this.cloneMethod) : doc;
- this.emit('pre-update', doc);
- Object.keys(this.constraints.unique).forEach(function (key) {
- self.constraints.unique[key].update(oldInternal, newInternal);
- });
- // operate the update
- this.data[position] = newInternal;
- if (newInternal !== doc) {
- this.addAutoUpdateObserver(doc);
- }
- // now that we can efficiently determine the data[] position of newly added document,
- // submit it for all registered DynamicViews to evaluate for inclusion/exclusion
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- this.DynamicViews[idx].evaluateDocument(position, false);
- }
- var key;
- if (this.adaptiveBinaryIndices) {
- // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
- var bIndices = this.binaryIndices;
- for (key in bIndices) {
- this.adaptiveBinaryIndexUpdate(position, key);
- }
- }
- else {
- this.flagBinaryIndexesDirty();
- }
- this.idIndex[position] = newInternal.$loki;
- //this.flagBinaryIndexesDirty();
- this.commit();
- this.dirty = true; // for autosave scenarios
- // update meta and store changes if ChangesAPI is enabled
- if (this.disableChangesApi) {
- this.updateMeta(newInternal, null);
- }
- else {
- this.updateMetaWithChange(newInternal, oldInternal);
- }
- var returnObj;
- // if cloning is enabled, emit 'update' event and return with clone of new object
- if (this.cloneObjects) {
- returnObj = clone(newInternal, this.cloneMethod);
- }
- else {
- returnObj = newInternal;
- }
- this.emit('update', returnObj, oldInternal);
- return returnObj;
- } catch (err) {
- this.rollback();
- this.console.error(err.message);
- this.emit('error', err);
- throw (err); // re-throw error so user does not think it succeeded
- }
- };
- /**
- * Add object to collection
- */
- Collection.prototype.add = function (obj) {
- // if parameter isn't object exit with throw
- if ('object' !== typeof obj) {
- throw new TypeError('Object being added needs to be an object');
- }
- // if object you are adding already has id column it is either already in the collection
- // or the object is carrying its own 'id' property. If it also has a meta property,
- // then this is already in collection so throw error, otherwise rename to originalId and continue adding.
- if (typeof (obj.$loki) !== 'undefined') {
- throw new Error('Document is already in collection, please use update()');
- }
- /*
- * try adding object to collection
- */
- try {
- this.startTransaction();
- this.maxId++;
- if (isNaN(this.maxId)) {
- this.maxId = (this.data[this.data.length - 1].$loki + 1);
- }
- obj.$loki = this.maxId;
- if (!this.disableMeta) {
- obj.meta.version = 0;
- }
- var key, constrUnique = this.constraints.unique;
- for (key in constrUnique) {
- if (hasOwnProperty.call(constrUnique, key)) {
- constrUnique[key].set(obj);
- }
- }
- // add new obj id to idIndex
- this.idIndex.push(obj.$loki);
- // add the object
- this.data.push(obj);
- var addedPos = this.data.length - 1;
- // now that we can efficiently determine the data[] position of newly added document,
- // submit it for all registered DynamicViews to evaluate for inclusion/exclusion
- var dvlen = this.DynamicViews.length;
- for (var i = 0; i < dvlen; i++) {
- this.DynamicViews[i].evaluateDocument(addedPos, true);
- }
- if (this.adaptiveBinaryIndices) {
- // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
- var bIndices = this.binaryIndices;
- for (key in bIndices) {
- this.adaptiveBinaryIndexInsert(addedPos, key);
- }
- }
- else {
- this.flagBinaryIndexesDirty();
- }
- this.commit();
- this.dirty = true; // for autosave scenarios
- return (this.cloneObjects) ? (clone(obj, this.cloneMethod)) : (obj);
- } catch (err) {
- this.rollback();
- this.console.error(err.message);
- this.emit('error', err);
- throw (err); // re-throw error so user does not think it succeeded
- }
- };
- /**
- * Applies a filter function and passes all results to an update function.
- *
- * @param {function} filterFunction - filter function whose results will execute update
- * @param {function} updateFunction - update function to run against filtered documents
- * @memberof Collection
- */
- Collection.prototype.updateWhere = function(filterFunction, updateFunction) {
- var results = this.where(filterFunction),
- i = 0,
- obj;
- try {
- for (i; i < results.length; i++) {
- obj = updateFunction(results[i]);
- this.update(obj);
- }
- } catch (err) {
- this.rollback();
- this.console.error(err.message);
- }
- };
- /**
- * Remove all documents matching supplied filter function.
- * For 'mongo-like' querying you should migrate to [findAndRemove()]{@link Collection#findAndRemove}.
- * @param {function|object} query - query object to filter on
- * @memberof Collection
- */
- Collection.prototype.removeWhere = function (query) {
- var list;
- if (typeof query === 'function') {
- list = this.data.filter(query);
- this.remove(list);
- } else {
- this.chain().find(query).remove();
- }
- };
- Collection.prototype.removeDataOnly = function () {
- this.remove(this.data.slice());
- };
- /**
- * Internal method to remove a batch of documents from the collection.
- * @param {number[]} positions - data/idIndex positions to remove
- */
- Collection.prototype.removeBatchByPositions = function(positions) {
- var len = positions.length;
- var xo = {};
- var dlen, didx, idx;
- var bic=Object.keys(this.binaryIndices).length;
- var uic=Object.keys(this.constraints.unique).length;
- var adaptiveOverride = this.adaptiveBinaryIndices && Object.keys(this.binaryIndices).length > 0;
- var doc, self=this;
- try {
- this.startTransaction();
- // create hashobject for positional removal inclusion tests...
- // all keys defined in this hashobject represent $loki ids of the documents to remove.
- for(idx=0; idx < len; idx++) {
- xo[this.idIndex[positions[idx]]] = true;
- }
- // if we will need to notify dynamic views and/or binary indices to update themselves...
- dlen = this.DynamicViews.length;
- if ((dlen > 0) || (bic > 0) || (uic > 0)) {
- if (dlen > 0) {
- // notify dynamic views to remove relevant documents at data positions
- for (didx = 0; didx < dlen; didx++) {
- // notify dv of remove (passing batch/array of positions)
- this.DynamicViews[didx].removeDocument(positions);
- }
- }
- // notify binary indices to update
- if (this.adaptiveBinaryIndices && !adaptiveOverride) {
- // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
- var key, bIndices = this.binaryIndices;
- for (key in bIndices) {
- this.adaptiveBinaryIndexRemove(positions, key);
- }
- }
- else {
- this.flagBinaryIndexesDirty();
- }
- if (uic) {
- Object.keys(this.constraints.unique).forEach(function (key) {
- for(idx=0; idx < len; idx++) {
- doc = self.data[positions[idx]];
- if (doc[key] !== null && doc[key] !== undefined) {
- self.constraints.unique[key].remove(doc[key]);
- }
- }
- });
- }
- }
- // emit 'delete' events only of listeners are attached.
- // since data not removed yet, in future we can emit single delete event with array...
- // for now that might be breaking change to put in potential 1.6 or LokiDB (lokijs2) version
- if (!this.disableChangesApi || this.events.delete.length > 1) {
- for(idx=0; idx < len; idx++) {
- this.emit('delete', this.data[positions[idx]]);
- }
- }
- // remove from data[] :
- // filter collection data for items not in inclusion hashobject
- this.data = this.data.filter(function(obj) {
- return !xo[obj.$loki];
- });
- // remove from idIndex[] :
- // filter idIndex for items not in inclusion hashobject
- this.idIndex = this.idIndex.filter(function(id) {
- return !xo[id];
- });
- if (this.adaptiveBinaryIndices && adaptiveOverride) {
- this.adaptiveBinaryIndices = false;
- this.ensureAllIndexes(true);
- this.adaptiveBinaryIndices = true;
- }
- this.commit();
- // flag collection as dirty for autosave
- this.dirty = true;
- }
- catch (err) {
- this.rollback();
- if (adaptiveOverride) {
- this.adaptiveBinaryIndices = true;
- }
- this.console.error(err.message);
- this.emit('error', err);
- return null;
- }
- };
- /**
- * Internal method called by remove()
- * @param {object[]|number[]} batch - array of documents or $loki ids to remove
- */
- Collection.prototype.removeBatch = function(batch) {
- var len = batch.length,
- dlen=this.data.length,
- idx;
- var xlt = {};
- var posx = [];
-
- // create lookup hashobject to translate $loki id to position
- for (idx=0; idx < dlen; idx++) {
- xlt[this.data[idx].$loki] = idx;
- }
- // iterate the batch
- for (idx=0; idx < len; idx++) {
- if (typeof(batch[idx]) === 'object') {
- posx.push(xlt[batch[idx].$loki]);
- }
- else {
- posx.push(xlt[batch[idx]]);
- }
- }
- this.removeBatchByPositions(posx);
- };
- /**
- * Remove a document from the collection
- * @param {object} doc - document to remove from collection
- * @memberof Collection
- */
- Collection.prototype.remove = function (doc) {
- if (typeof doc === 'number') {
- doc = this.get(doc);
- }
- if ('object' !== typeof doc) {
- throw new Error('Parameter is not an object');
- }
- if (Array.isArray(doc)) {
- this.removeBatch(doc);
- return;
- }
- if (!hasOwnProperty.call(doc, '$loki')) {
- throw new Error('Object is not a document stored in the collection');
- }
- try {
- this.startTransaction();
- var arr = this.get(doc.$loki, true),
- // obj = arr[0],
- position = arr[1];
- var self = this;
- Object.keys(this.constraints.unique).forEach(function (key) {
- if (doc[key] !== null && typeof doc[key] !== 'undefined') {
- self.constraints.unique[key].remove(doc[key]);
- }
- });
- // now that we can efficiently determine the data[] position of newly added document,
- // submit it for all registered DynamicViews to remove
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- this.DynamicViews[idx].removeDocument(position);
- }
- if (this.adaptiveBinaryIndices) {
- // for each binary index defined in collection, immediately update rather than flag for lazy rebuild
- var key, bIndices = this.binaryIndices;
- for (key in bIndices) {
- this.adaptiveBinaryIndexRemove(position, key);
- }
- }
- else {
- this.flagBinaryIndexesDirty();
- }
- this.data.splice(position, 1);
- this.removeAutoUpdateObserver(doc);
- // remove id from idIndex
- this.idIndex.splice(position, 1);
- this.commit();
- this.dirty = true; // for autosave scenarios
- this.emit('delete', arr[0]);
- delete doc.$loki;
- delete doc.meta;
- return doc;
- } catch (err) {
- this.rollback();
- this.console.error(err.message);
- this.emit('error', err);
- return null;
- }
- };
- /*---------------------+
- | Finding methods |
- +----------------------*/
- /**
- * Get by Id - faster than other methods because of the searching algorithm
- * @param {int} id - $loki id of document you want to retrieve
- * @param {boolean} returnPosition - if 'true' we will return [object, position]
- * @returns {(object|array|null)} Object reference if document was found, null if not,
- * or an array if 'returnPosition' was passed.
- * @memberof Collection
- */
- Collection.prototype.get = function (id, returnPosition) {
- var retpos = returnPosition || false,
- data = this.idIndex,
- max = data.length - 1,
- min = 0,
- mid = (min + max) >> 1;
- id = typeof id === 'number' ? id : parseInt(id, 10);
- if (isNaN(id)) {
- throw new TypeError('Passed id is not an integer');
- }
- while (data[min] < data[max]) {
- mid = (min + max) >> 1;
- if (data[mid] < id) {
- min = mid + 1;
- } else {
- max = mid;
- }
- }
- if (max === min && data[min] === id) {
- if (retpos) {
- return [this.data[min], min];
- }
- return this.data[min];
- }
- return null;
- };
- /**
- * Perform binary range lookup for the data[dataPosition][binaryIndexName] property value
- * Since multiple documents may contain the same value (which the index is sorted on),
- * we hone in on range and then linear scan range to find exact index array position.
- * @param {int} dataPosition : coll.data array index/position
- * @param {string} binaryIndexName : index to search for dataPosition in
- */
- Collection.prototype.getBinaryIndexPosition = function(dataPosition, binaryIndexName) {
- var val = Utils.getIn(this.data[dataPosition], binaryIndexName, true);
- var index = this.binaryIndices[binaryIndexName].values;
- // i think calculateRange can probably be moved to collection
- // as it doesn't seem to need resultset. need to verify
- var range = this.calculateRange("$eq", binaryIndexName, val);
- if (range[0] === 0 && range[1] === -1) {
- // uhoh didn't find range
- return null;
- }
- var min = range[0];
- var max = range[1];
- // narrow down the sub-segment of index values
- // where the indexed property value exactly matches our
- // value and then linear scan to find exact -index- position
- for(var idx = min; idx <= max; idx++) {
- if (index[idx] === dataPosition) return idx;
- }
- // uhoh
- return null;
- };
- /**
- * Adaptively insert a selected item to the index.
- * @param {int} dataPosition : coll.data array index/position
- * @param {string} binaryIndexName : index to search for dataPosition in
- */
- Collection.prototype.adaptiveBinaryIndexInsert = function(dataPosition, binaryIndexName) {
- var usingDotNotation = (binaryIndexName.indexOf('.') !== -1);
- var index = this.binaryIndices[binaryIndexName].values;
- var val = Utils.getIn(this.data[dataPosition], binaryIndexName, usingDotNotation);
- // If you are inserting a javascript Date value into a binary index, convert to epoch time
- if (this.serializableIndices === true && val instanceof Date) {
- this.data[dataPosition][binaryIndexName] = val.getTime();
- val = Utils.getIn(this.data[dataPosition], binaryIndexName);
- }
- var idxPos = (index.length === 0)?0:this.calculateRangeStart(binaryIndexName, val, true, usingDotNotation);
- // insert new data index into our binary index at the proper sorted location for relevant property calculated by idxPos.
- // doing this after adjusting dataPositions so no clash with previous item at that position.
- this.binaryIndices[binaryIndexName].values.splice(idxPos, 0, dataPosition);
- };
- /**
- * Adaptively update a selected item within an index.
- * @param {int} dataPosition : coll.data array index/position
- * @param {string} binaryIndexName : index to search for dataPosition in
- */
- Collection.prototype.adaptiveBinaryIndexUpdate = function(dataPosition, binaryIndexName) {
- // linear scan needed to find old position within index unless we optimize for clone scenarios later
- // within (my) node 5.6.0, the following for() loop with strict compare is -much- faster than indexOf()
- var idxPos,
- index = this.binaryIndices[binaryIndexName].values,
- len=index.length;
- for(idxPos=0; idxPos < len; idxPos++) {
- if (index[idxPos] === dataPosition) break;
- }
- //var idxPos = this.binaryIndices[binaryIndexName].values.indexOf(dataPosition);
- this.binaryIndices[binaryIndexName].values.splice(idxPos, 1);
- //this.adaptiveBinaryIndexRemove(dataPosition, binaryIndexName, true);
- this.adaptiveBinaryIndexInsert(dataPosition, binaryIndexName);
- };
- /**
- * Adaptively remove a selected item from the index.
- * @param {number|number[]} dataPosition : coll.data array index/position
- * @param {string} binaryIndexName : index to search for dataPosition in
- */
- Collection.prototype.adaptiveBinaryIndexRemove = function(dataPosition, binaryIndexName, removedFromIndexOnly) {
- var bi = this.binaryIndices[binaryIndexName];
- var len, idx, rmidx, rmlen, rxo = {};
- var curr, shift, idxPos;
- if (Array.isArray(dataPosition)) {
- // when called from chained remove, and only one document in array,
- // it will be faster to use old algorithm
- rmlen = dataPosition.length;
- if (rmlen === 1) {
- dataPosition = dataPosition[0];
- }
- // we were passed an array (batch) of documents so use this 'batch optimized' algorithm
- else {
- for(rmidx=0;rmidx<rmlen; rmidx++) {
- rxo[dataPosition[rmidx]] = true;
- }
-
- // remove document from index (with filter function)
- bi.values = bi.values.filter(function(di) { return !rxo[di]; });
-
- // if we passed this optional flag parameter, we are calling from adaptiveBinaryIndexUpdate,
- // in which case data positions stay the same.
- if (removedFromIndexOnly === true) {
- return;
- }
-
- var sortedPositions = dataPosition.slice();
- sortedPositions.sort(function (a, b) { return a-b; });
-
- // to remove holes, we need to 'shift down' the index's data array positions
- // we need to adjust array positions -1 for each index data positions greater than removed positions
- len = bi.values.length;
- for (idx=0; idx<len; idx++) {
- curr=bi.values[idx];
- shift=0;
- for(rmidx=0; rmidx<rmlen && curr > sortedPositions[rmidx]; rmidx++) {
- shift++;
- }
- bi.values[idx]-=shift;
- }
- // batch processed, bail out
- return;
- }
- // not a batch so continue...
- }
- idxPos = this.getBinaryIndexPosition(dataPosition, binaryIndexName);
- if (idxPos === null) {
- // throw new Error('unable to determine binary index position');
- return null;
- }
- // remove document from index (with splice)
- bi.values.splice(idxPos, 1);
- // if we passed this optional flag parameter, we are calling from adaptiveBinaryIndexUpdate,
- // in which case data positions stay the same.
- if (removedFromIndexOnly === true) {
- return;
- }
- // since index stores data array positions, if we remove a document
- // we need to adjust array positions -1 for all document positions greater than removed position
- len = bi.values.length;
- for (idx = 0; idx < len; idx++) {
- if (bi.values[idx] > dataPosition) {
- bi.values[idx]--;
- }
- }
- };
- /**
- * Internal method used for index maintenance and indexed searching.
- * Calculates the beginning of an index range for a given value.
- * For index maintainance (adaptive:true), we will return a valid index position to insert to.
- * For querying (adaptive:false/undefined), we will :
- * return lower bound/index of range of that value (if found)
- * return next lower index position if not found (hole)
- * If index is empty it is assumed to be handled at higher level, so
- * this method assumes there is at least 1 document in index.
- *
- * @param {string} prop - name of property which has binary index
- * @param {any} val - value to find within index
- * @param {bool?} adaptive - if true, we will return insert position
- */
- Collection.prototype.calculateRangeStart = function (prop, val, adaptive, usingDotNotation) {
- var rcd = this.data;
- var index = this.binaryIndices[prop].values;
- var min = 0;
- var max = index.length - 1;
- var mid = 0;
- if (index.length === 0) {
- return -1;
- }
- var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
- var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
- // hone in on start position of value
- while (min < max) {
- mid = (min + max) >> 1;
- if (Comparators.lt(Utils.getIn(rcd[index[mid]], prop, usingDotNotation), val, false)) {
- min = mid + 1;
- } else {
- max = mid;
- }
- }
- var lbound = min;
- // found it... return it
- if (Comparators.aeq(val, Utils.getIn(rcd[index[lbound]], prop, usingDotNotation))) {
- return lbound;
- }
- // if not in index and our value is less than the found one
- if (Comparators.lt(val, Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), false)) {
- return adaptive?lbound:lbound-1;
- }
- // not in index and our value is greater than the found one
- return adaptive?lbound+1:lbound;
- };
- /**
- * Internal method used for indexed $between. Given a prop (index name), and a value
- * (which may or may not yet exist) this will find the final position of that upper range value.
- */
- Collection.prototype.calculateRangeEnd = function (prop, val, usingDotNotation) {
- var rcd = this.data;
- var index = this.binaryIndices[prop].values;
- var min = 0;
- var max = index.length - 1;
- var mid = 0;
- if (index.length === 0) {
- return -1;
- }
- var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
- var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
- // hone in on start position of value
- while (min < max) {
- mid = (min + max) >> 1;
- if (Comparators.lt(val, Utils.getIn(rcd[index[mid]], prop, usingDotNotation), false)) {
- max = mid;
- } else {
- min = mid + 1;
- }
- }
- var ubound = max;
- // only eq if last element in array is our val
- if (Comparators.aeq(val, Utils.getIn(rcd[index[ubound]], prop, usingDotNotation))) {
- return ubound;
- }
- // if not in index and our value is less than the found one
- if (Comparators.gt(val, Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), false)) {
- return ubound+1;
- }
- // either hole or first nonmatch
- if (Comparators.aeq(val, Utils.getIn(rcd[index[ubound-1]], prop, usingDotNotation))) {
- return ubound-1;
- }
- // hole, so ubound if nearest gt than the val we were looking for
- return ubound;
- };
- /**
- * calculateRange() - Binary Search utility method to find range/segment of values matching criteria.
- * this is used for collection.find() and first find filter of resultset/dynview
- * slightly different than get() binary search in that get() hones in on 1 value,
- * but we have to hone in on many (range)
- * @param {string} op - operation, such as $eq
- * @param {string} prop - name of property to calculate range for
- * @param {object} val - value to use for range calculation.
- * @returns {array} [start, end] index array positions
- */
- Collection.prototype.calculateRange = function (op, prop, val) {
- var rcd = this.data;
- var index = this.binaryIndices[prop].values;
- var min = 0;
- var max = index.length - 1;
- var mid = 0;
- var lbound, lval;
- var ubound, uval;
- // when no documents are in collection, return empty range condition
- if (rcd.length === 0) {
- return [0, -1];
- }
- var usingDotNotation = (prop.indexOf('.') !== -1);
- var minVal = Utils.getIn(rcd[index[min]], prop, usingDotNotation);
- var maxVal = Utils.getIn(rcd[index[max]], prop, usingDotNotation);
- // if value falls outside of our range return [0, -1] to designate no results
- switch (op) {
- case '$eq':
- case '$aeq':
- if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) {
- return [0, -1];
- }
- break;
- case '$dteq':
- if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) {
- return [0, -1];
- }
- break;
- case '$gt':
- // none are within range
- if (Comparators.gt(val, maxVal, true)) {
- return [0, -1];
- }
- // all are within range
- if (Comparators.gt(minVal, val, false)) {
- return [min, max];
- }
- break;
- case '$gte':
- // none are within range
- if (Comparators.gt(val, maxVal, false)) {
- return [0, -1];
- }
- // all are within range
- if (Comparators.gt(minVal, val, true)) {
- return [min, max];
- }
- break;
- case '$lt':
- // none are within range
- if (Comparators.lt(val, minVal, true)) {
- return [0, -1];
- }
- // all are within range
- if (Comparators.lt(maxVal, val, false)) {
- return [min, max];
- }
- break;
- case '$lte':
- // none are within range
- if (Comparators.lt(val, minVal, false)) {
- return [0, -1];
- }
- // all are within range
- if (Comparators.lt(maxVal, val, true)) {
- return [min, max];
- }
- break;
- case '$between':
- // none are within range (low range is greater)
- if (Comparators.gt(val[0], maxVal, false)) {
- return [0, -1];
- }
- // none are within range (high range lower)
- if (Comparators.lt(val[1], minVal, false)) {
- return [0, -1];
- }
- lbound = this.calculateRangeStart(prop, val[0], false, usingDotNotation);
- ubound = this.calculateRangeEnd(prop, val[1], usingDotNotation);
- if (lbound < 0) lbound++;
- if (ubound > max) ubound--;
- if (!Comparators.gt(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val[0], true)) lbound++;
- if (!Comparators.lt(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val[1], true)) ubound--;
- if (ubound < lbound) return [0, -1];
- return ([lbound, ubound]);
- case '$in':
- var idxset = [],
- segResult = [];
- // query each value '$eq' operator and merge the seqment results.
- for (var j = 0, len = val.length; j < len; j++) {
- var seg = this.calculateRange('$eq', prop, val[j]);
- for (var i = seg[0]; i <= seg[1]; i++) {
- if (idxset[i] === undefined) {
- idxset[i] = true;
- segResult.push(i);
- }
- }
- }
- return segResult;
- }
- // determine lbound where needed
- switch (op) {
- case '$eq':
- case '$aeq':
- case '$dteq':
- case '$gte':
- case '$lt':
- lbound = this.calculateRangeStart(prop, val, false, usingDotNotation);
- lval = Utils.getIn(rcd[index[lbound]], prop, usingDotNotation);
- break;
- default: break;
- }
- // determine ubound where needed
- switch (op) {
- case '$eq':
- case '$aeq':
- case '$dteq':
- case '$lte':
- case '$gt':
- ubound = this.calculateRangeEnd(prop, val, usingDotNotation);
- uval = Utils.getIn(rcd[index[ubound]], prop, usingDotNotation);
- break;
- default: break;
- }
- switch (op) {
- case '$eq':
- case '$aeq':
- case '$dteq':
- // if hole (not found)
- if (!Comparators.aeq(lval, val)) {
- return [0, -1];
- }
- return [lbound, ubound];
- case '$gt':
- // if hole (not found) ub position is already greater
- if (!Comparators.aeq(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val)) {
- return [ubound, max];
- }
- // otherwise (found) so ubound is still equal, get next
- return [ubound+1, max];
- case '$gte':
- // if hole (not found) lb position marks left outside of range
- if (!Comparators.aeq(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val)) {
- return [lbound+1, max];
- }
- // otherwise (found) so lb is first position where its equal
- return [lbound, max];
- case '$lt':
- // if hole (not found) position already is less than
- if (!Comparators.aeq(Utils.getIn(rcd[index[lbound]], prop, usingDotNotation), val)) {
- return [min, lbound];
- }
- // otherwise (found) so lb marks left inside of eq range, get previous
- return [min, lbound-1];
- case '$lte':
- // if hole (not found) ub position marks right outside so get previous
- if (!Comparators.aeq(Utils.getIn(rcd[index[ubound]], prop, usingDotNotation), val)) {
- return [min, ubound-1];
- }
- // otherwise (found) so ub is last position where its still equal
- return [min, ubound];
- default:
- return [0, rcd.length - 1];
- }
- };
- /**
- * Retrieve doc by Unique index
- * @param {string} field - name of uniquely indexed property to use when doing lookup
- * @param {value} value - unique value to search for
- * @returns {object} document matching the value passed
- * @memberof Collection
- */
- Collection.prototype.by = function (field, value) {
- var self;
- if (value === undefined) {
- self = this;
- return function (value) {
- return self.by(field, value);
- };
- }
- var result = this.constraints.unique[field].get(value);
- if (!this.cloneObjects) {
- return result;
- } else {
- return clone(result, this.cloneMethod);
- }
- };
- /**
- * Find one object by index property, by property equal to value
- * @param {object} query - query object used to perform search with
- * @returns {(object|null)} First matching document, or null if none
- * @memberof Collection
- */
- Collection.prototype.findOne = function (query) {
- query = query || {};
- // Instantiate Resultset and exec find op passing firstOnly = true param
- var result = this.chain().find(query,true).data();
- if (Array.isArray(result) && result.length === 0) {
- return null;
- } else {
- if (!this.cloneObjects) {
- return result[0];
- } else {
- return clone(result[0], this.cloneMethod);
- }
- }
- };
- /**
- * Chain method, used for beginning a series of chained find() and/or view() operations
- * on a collection.
- *
- * @param {string|array=} transform - named transform or array of transform steps
- * @param {object=} parameters - Object containing properties representing parameters to substitute
- * @returns {Resultset} (this) resultset, or data array if any map or join functions where called
- * @memberof Collection
- */
- Collection.prototype.chain = function (transform, parameters) {
- var rs = new Resultset(this);
- if (typeof transform === 'undefined') {
- return rs;
- }
- return rs.transform(transform, parameters);
- };
- /**
- * Find method, api is similar to mongodb.
- * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}.
- * @example {@tutorial Query Examples}
- * @param {object} query - 'mongo-like' query object
- * @returns {array} Array of matching documents
- * @memberof Collection
- */
- Collection.prototype.find = function (query) {
- return this.chain().find(query).data();
- };
- /**
- * Find object by unindexed field by property equal to value,
- * simply iterates and returns the first element matching the query
- */
- Collection.prototype.findOneUnindexed = function (prop, value) {
- var i = this.data.length,
- doc;
- while (i--) {
- if (Utils.getIn(this.data[i], prop, true) === value) {
- doc = this.data[i];
- return doc;
- }
- }
- return null;
- };
- /**
- * Transaction methods
- */
- /** start the transation */
- Collection.prototype.startTransaction = function () {
- if (this.transactional) {
- this.cachedData = clone(this.data, this.cloneMethod);
- this.cachedIndex = this.idIndex;
- this.cachedBinaryIndex = this.binaryIndices;
- // propagate startTransaction to dynamic views
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- this.DynamicViews[idx].startTransaction();
- }
- }
- };
- /** commit the transation */
- Collection.prototype.commit = function () {
- if (this.transactional) {
- this.cachedData = null;
- this.cachedIndex = null;
- this.cachedBinaryIndex = null;
- // propagate commit to dynamic views
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- this.DynamicViews[idx].commit();
- }
- }
- };
- /** roll back the transation */
- Collection.prototype.rollback = function () {
- if (this.transactional) {
- if (this.cachedData !== null && this.cachedIndex !== null) {
- this.data = this.cachedData;
- this.idIndex = this.cachedIndex;
- this.binaryIndices = this.cachedBinaryIndex;
- }
- // propagate rollback to dynamic views
- for (var idx = 0; idx < this.DynamicViews.length; idx++) {
- this.DynamicViews[idx].rollback();
- }
- }
- };
- // async executor. This is only to enable callbacks at the end of the execution.
- Collection.prototype.async = function (fun, callback) {
- setTimeout(function () {
- if (typeof fun === 'function') {
- fun();
- callback();
- } else {
- throw new TypeError('Argument passed for async execution is not a function');
- }
- }, 0);
- };
- /**
- * Query the collection by supplying a javascript filter function.
- * @example
- * var results = coll.where(function(obj) {
- * return obj.legs === 8;
- * });
- *
- * @param {function} fun - filter function to run against all collection docs
- * @returns {array} all documents which pass your filter function
- * @memberof Collection
- */
- Collection.prototype.where = function (fun) {
- return this.chain().where(fun).data();
- };
- /**
- * Map Reduce operation
- *
- * @param {function} mapFunction - function to use as map function
- * @param {function} reduceFunction - function to use as reduce function
- * @returns {data} The result of your mapReduce operation
- * @memberof Collection
- */
- Collection.prototype.mapReduce = function (mapFunction, reduceFunction) {
- try {
- return reduceFunction(this.data.map(mapFunction));
- } catch (err) {
- throw err;
- }
- };
- /**
- * Join two collections on specified properties
- *
- * @param {array|Resultset|Collection} joinData - array of documents to 'join' to this collection
- * @param {string} leftJoinProp - property name in collection
- * @param {string} rightJoinProp - property name in joinData
- * @param {function=} mapFun - (Optional) map function to use
- * @param {object=} dataOptions - options to data() before input to your map function
- * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun
- * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
- * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method.
- * @returns {Resultset} Result of the mapping operation
- * @memberof Collection
- */
- Collection.prototype.eqJoin = function (joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions) {
- // logic in Resultset class
- return new Resultset(this).eqJoin(joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions);
- };
- /* ------ STAGING API -------- */
- /**
- * stages: a map of uniquely identified 'stages', which hold copies of objects to be
- * manipulated without affecting the data in the original collection
- */
- Collection.prototype.stages = {};
- /**
- * (Staging API) create a stage and/or retrieve it
- * @memberof Collection
- */
- Collection.prototype.getStage = function (name) {
- if (!this.stages[name]) {
- this.stages[name] = {};
- }
- return this.stages[name];
- };
- /**
- * a collection of objects recording the changes applied through a commmitStage
- */
- Collection.prototype.commitLog = [];
- /**
- * (Staging API) create a copy of an object and insert it into a stage
- * @memberof Collection
- */
- Collection.prototype.stage = function (stageName, obj) {
- var copy = JSON.parse(JSON.stringify(obj));
- this.getStage(stageName)[obj.$loki] = copy;
- return copy;
- };
- /**
- * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt
- * then create a message to be inserted in the commitlog
- * @param {string} stageName - name of stage
- * @param {string} message
- * @memberof Collection
- */
- Collection.prototype.commitStage = function (stageName, message) {
- var stage = this.getStage(stageName),
- prop,
- timestamp = new Date().getTime();
- for (prop in stage) {
- this.update(stage[prop]);
- this.commitLog.push({
- timestamp: timestamp,
- message: message,
- data: JSON.parse(JSON.stringify(stage[prop]))
- });
- }
- this.stages[stageName] = {};
- };
- Collection.prototype.no_op = function () {
- return;
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.extract = function (field) {
- var i = 0,
- len = this.data.length,
- isDotNotation = isDeepProperty(field),
- result = [];
- for (i; i < len; i += 1) {
- result.push(deepProperty(this.data[i], field, isDotNotation));
- }
- return result;
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.max = function (field) {
- return Math.max.apply(null, this.extract(field));
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.min = function (field) {
- return Math.min.apply(null, this.extract(field));
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.maxRecord = function (field) {
- var i = 0,
- len = this.data.length,
- deep = isDeepProperty(field),
- result = {
- index: 0,
- value: undefined
- },
- max;
- for (i; i < len; i += 1) {
- if (max !== undefined) {
- if (max < deepProperty(this.data[i], field, deep)) {
- max = deepProperty(this.data[i], field, deep);
- result.index = this.data[i].$loki;
- }
- } else {
- max = deepProperty(this.data[i], field, deep);
- result.index = this.data[i].$loki;
- }
- }
- result.value = max;
- return result;
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.minRecord = function (field) {
- var i = 0,
- len = this.data.length,
- deep = isDeepProperty(field),
- result = {
- index: 0,
- value: undefined
- },
- min;
- for (i; i < len; i += 1) {
- if (min !== undefined) {
- if (min > deepProperty(this.data[i], field, deep)) {
- min = deepProperty(this.data[i], field, deep);
- result.index = this.data[i].$loki;
- }
- } else {
- min = deepProperty(this.data[i], field, deep);
- result.index = this.data[i].$loki;
- }
- }
- result.value = min;
- return result;
- };
- /**
- * @memberof Collection
- */
- Collection.prototype.extractNumerical = function (field) {
- return this.extract(field).map(parseBase10).filter(Number).filter(function (n) {
- return !(isNaN(n));
- });
- };
- /**
- * Calculates the average numerical value of a property
- *
- * @param {string} field - name of property in docs to average
- * @returns {number} average of property in all docs in the collection
- * @memberof Collection
- */
- Collection.prototype.avg = function (field) {
- return average(this.extractNumerical(field));
- };
- /**
- * Calculate standard deviation of a field
- * @memberof Collection
- * @param {string} field
- */
- Collection.prototype.stdDev = function (field) {
- return standardDeviation(this.extractNumerical(field));
- };
- /**
- * @memberof Collection
- * @param {string} field
- */
- Collection.prototype.mode = function (field) {
- var dict = {},
- data = this.extract(field);
- data.forEach(function (obj) {
- if (dict[obj]) {
- dict[obj] += 1;
- } else {
- dict[obj] = 1;
- }
- });
- var max,
- prop, mode;
- for (prop in dict) {
- if (max) {
- if (max < dict[prop]) {
- mode = prop;
- }
- } else {
- mode = prop;
- max = dict[prop];
- }
- }
- return mode;
- };
- /**
- * @memberof Collection
- * @param {string} field - property name
- */
- Collection.prototype.median = function (field) {
- var values = this.extractNumerical(field);
- values.sort(sub);
- var half = Math.floor(values.length / 2);
- if (values.length % 2) {
- return values[half];
- } else {
- return (values[half - 1] + values[half]) / 2.0;
- }
- };
- /**
- * General utils, including statistical functions
- */
- function isDeepProperty(field) {
- return field.indexOf('.') !== -1;
- }
- function parseBase10(num) {
- return parseFloat(num, 10);
- }
- function isNotUndefined(obj) {
- return obj !== undefined;
- }
- function add(a, b) {
- return a + b;
- }
- function sub(a, b) {
- return a - b;
- }
- function median(values) {
- values.sort(sub);
- var half = Math.floor(values.length / 2);
- return (values.length % 2) ? values[half] : ((values[half - 1] + values[half]) / 2.0);
- }
- function average(array) {
- return (array.reduce(add, 0)) / array.length;
- }
- function standardDeviation(values) {
- var avg = average(values);
- var squareDiffs = values.map(function (value) {
- var diff = value - avg;
- var sqrDiff = diff * diff;
- return sqrDiff;
- });
- var avgSquareDiff = average(squareDiffs);
- var stdDev = Math.sqrt(avgSquareDiff);
- return stdDev;
- }
- function deepProperty(obj, property, isDeep) {
- if (isDeep === false) {
- // pass without processing
- return obj[property];
- }
- var pieces = property.split('.'),
- root = obj;
- while (pieces.length > 0) {
- root = root[pieces.shift()];
- }
- return root;
- }
- function binarySearch(array, item, fun) {
- var lo = 0,
- hi = array.length,
- compared,
- mid;
- while (lo < hi) {
- mid = (lo + hi) >> 1;
- compared = fun.apply(null, [item, array[mid]]);
- if (compared === 0) {
- return {
- found: true,
- index: mid
- };
- } else if (compared < 0) {
- hi = mid;
- } else {
- lo = mid + 1;
- }
- }
- return {
- found: false,
- index: hi
- };
- }
- function BSonSort(fun) {
- return function (array, item) {
- return binarySearch(array, item, fun);
- };
- }
- function KeyValueStore() {}
- KeyValueStore.prototype = {
- keys: [],
- values: [],
- sort: function (a, b) {
- return (a < b) ? -1 : ((a > b) ? 1 : 0);
- },
- setSort: function (fun) {
- this.bs = new BSonSort(fun);
- },
- bs: function () {
- return new BSonSort(this.sort);
- },
- set: function (key, value) {
- var pos = this.bs(this.keys, key);
- if (pos.found) {
- this.values[pos.index] = value;
- } else {
- this.keys.splice(pos.index, 0, key);
- this.values.splice(pos.index, 0, value);
- }
- },
- get: function (key) {
- return this.values[binarySearch(this.keys, key, this.sort).index];
- }
- };
- function UniqueIndex(uniqueField) {
- this.field = uniqueField;
- this.keyMap = {};
- this.lokiMap = {};
- }
- UniqueIndex.prototype.keyMap = {};
- UniqueIndex.prototype.lokiMap = {};
- UniqueIndex.prototype.set = function (obj) {
- var fieldValue = obj[this.field];
- if (fieldValue !== null && typeof (fieldValue) !== 'undefined') {
- if (this.keyMap[fieldValue]) {
- throw new Error('Duplicate key for property ' + this.field + ': ' + fieldValue);
- } else {
- this.keyMap[fieldValue] = obj;
- this.lokiMap[obj.$loki] = fieldValue;
- }
- }
- };
- UniqueIndex.prototype.get = function (key) {
- return this.keyMap[key];
- };
- UniqueIndex.prototype.byId = function (id) {
- return this.keyMap[this.lokiMap[id]];
- };
- /**
- * Updates a document's unique index given an updated object.
- * @param {Object} obj Original document object
- * @param {Object} doc New document object (likely the same as obj)
- */
- UniqueIndex.prototype.update = function (obj, doc) {
- if (this.lokiMap[obj.$loki] !== doc[this.field]) {
- var old = this.lokiMap[obj.$loki];
- this.set(doc);
- // make the old key fail bool test, while avoiding the use of delete (mem-leak prone)
- this.keyMap[old] = undefined;
- } else {
- this.keyMap[obj[this.field]] = doc;
- }
- };
- UniqueIndex.prototype.remove = function (key) {
- var obj = this.keyMap[key];
- if (obj !== null && typeof obj !== 'undefined') {
- this.keyMap[key] = undefined;
- this.lokiMap[obj.$loki] = undefined;
- } else {
- throw new Error('Key is not in unique index: ' + this.field);
- }
- };
- UniqueIndex.prototype.clear = function () {
- this.keyMap = {};
- this.lokiMap = {};
- };
- function ExactIndex(exactField) {
- this.index = {};
- this.field = exactField;
- }
- // add the value you want returned to the key in the index
- ExactIndex.prototype = {
- set: function add(key, val) {
- if (this.index[key]) {
- this.index[key].push(val);
- } else {
- this.index[key] = [val];
- }
- },
- // remove the value from the index, if the value was the last one, remove the key
- remove: function remove(key, val) {
- var idxSet = this.index[key];
- for (var i in idxSet) {
- if (idxSet[i] == val) {
- idxSet.splice(i, 1);
- }
- }
- if (idxSet.length < 1) {
- this.index[key] = undefined;
- }
- },
- // get the values related to the key, could be more than one
- get: function get(key) {
- return this.index[key];
- },
- // clear will zap the index
- clear: function clear(key) {
- this.index = {};
- }
- };
- function SortedIndex(sortedField) {
- this.field = sortedField;
- }
- SortedIndex.prototype = {
- keys: [],
- values: [],
- // set the default sort
- sort: function (a, b) {
- return (a < b) ? -1 : ((a > b) ? 1 : 0);
- },
- bs: function () {
- return new BSonSort(this.sort);
- },
- // and allow override of the default sort
- setSort: function (fun) {
- this.bs = new BSonSort(fun);
- },
- // add the value you want returned to the key in the index
- set: function (key, value) {
- var pos = binarySearch(this.keys, key, this.sort);
- if (pos.found) {
- this.values[pos.index].push(value);
- } else {
- this.keys.splice(pos.index, 0, key);
- this.values.splice(pos.index, 0, [value]);
- }
- },
- // get all values which have a key == the given key
- get: function (key) {
- var bsr = binarySearch(this.keys, key, this.sort);
- if (bsr.found) {
- return this.values[bsr.index];
- } else {
- return [];
- }
- },
- // get all values which have a key < the given key
- getLt: function (key) {
- var bsr = binarySearch(this.keys, key, this.sort);
- var pos = bsr.index;
- if (bsr.found) pos--;
- return this.getAll(key, 0, pos);
- },
- // get all values which have a key > the given key
- getGt: function (key) {
- var bsr = binarySearch(this.keys, key, this.sort);
- var pos = bsr.index;
- if (bsr.found) pos++;
- return this.getAll(key, pos, this.keys.length);
- },
- // get all vals from start to end
- getAll: function (key, start, end) {
- var results = [];
- for (var i = start; i < end; i++) {
- results = results.concat(this.values[i]);
- }
- return results;
- },
- // just in case someone wants to do something smart with ranges
- getPos: function (key) {
- return binarySearch(this.keys, key, this.sort);
- },
- // remove the value from the index, if the value was the last one, remove the key
- remove: function (key, value) {
- var pos = binarySearch(this.keys, key, this.sort).index;
- var idxSet = this.values[pos];
- for (var i in idxSet) {
- if (idxSet[i] == value) idxSet.splice(i, 1);
- }
- if (idxSet.length < 1) {
- this.keys.splice(pos, 1);
- this.values.splice(pos, 1);
- }
- },
- // clear will zap the index
- clear: function () {
- this.keys = [];
- this.values = [];
- }
- };
- Loki.LokiOps = LokiOps;
- Loki.Collection = Collection;
- Loki.KeyValueStore = KeyValueStore;
- Loki.LokiMemoryAdapter = LokiMemoryAdapter;
- Loki.LokiPartitioningAdapter = LokiPartitioningAdapter;
- Loki.LokiLocalStorageAdapter = LokiLocalStorageAdapter;
- Loki.LokiFsAdapter = LokiFsAdapter;
- Loki.persistenceAdapters = {
- fs: LokiFsAdapter,
- localStorage: LokiLocalStorageAdapter
- };
- Loki.aeq = aeqHelper;
- Loki.lt = ltHelper;
- Loki.gt = gtHelper;
- Loki.Comparators = Comparators;
- return Loki;
- }());
- }));
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./loki-indexed-adapter.js":171,"_process":202,"fs":23}],173:[function(require,module,exports){
- /**
- * martinez v0.4.3
- * Martinez polygon clipping algorithm, does boolean operation on polygons (multipolygons, polygons with holes etc): intersection, union, difference, xor
- *
- * @author Alex Milevski <info@w8r.name>
- * @license MIT
- * @preserve
- */
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global.martinez = {})));
- }(this, (function (exports) { 'use strict';
- function DEFAULT_COMPARE (a, b) { return a > b ? 1 : a < b ? -1 : 0; }
- var SplayTree = function SplayTree(compare, noDuplicates) {
- if ( compare === void 0 ) compare = DEFAULT_COMPARE;
- if ( noDuplicates === void 0 ) noDuplicates = false;
- this._compare = compare;
- this._root = null;
- this._size = 0;
- this._noDuplicates = !!noDuplicates;
- };
- var prototypeAccessors = { size: { configurable: true } };
- SplayTree.prototype.rotateLeft = function rotateLeft (x) {
- var y = x.right;
- if (y) {
- x.right = y.left;
- if (y.left) { y.left.parent = x; }
- y.parent = x.parent;
- }
- if (!x.parent) { this._root = y; }
- else if (x === x.parent.left) { x.parent.left = y; }
- else { x.parent.right = y; }
- if (y) { y.left = x; }
- x.parent = y;
- };
- SplayTree.prototype.rotateRight = function rotateRight (x) {
- var y = x.left;
- if (y) {
- x.left = y.right;
- if (y.right) { y.right.parent = x; }
- y.parent = x.parent;
- }
- if (!x.parent) { this._root = y; }
- else if(x === x.parent.left) { x.parent.left = y; }
- else { x.parent.right = y; }
- if (y) { y.right = x; }
- x.parent = y;
- };
- SplayTree.prototype._splay = function _splay (x) {
- var this$1 = this;
- while (x.parent) {
- var p = x.parent;
- if (!p.parent) {
- if (p.left === x) { this$1.rotateRight(p); }
- else { this$1.rotateLeft(p); }
- } else if (p.left === x && p.parent.left === p) {
- this$1.rotateRight(p.parent);
- this$1.rotateRight(p);
- } else if (p.right === x && p.parent.right === p) {
- this$1.rotateLeft(p.parent);
- this$1.rotateLeft(p);
- } else if (p.left === x && p.parent.right === p) {
- this$1.rotateRight(p);
- this$1.rotateLeft(p);
- } else {
- this$1.rotateLeft(p);
- this$1.rotateRight(p);
- }
- }
- };
- SplayTree.prototype.splay = function splay (x) {
- var this$1 = this;
- var p, gp, ggp, l, r;
- while (x.parent) {
- p = x.parent;
- gp = p.parent;
- if (gp && gp.parent) {
- ggp = gp.parent;
- if (ggp.left === gp) { ggp.left= x; }
- else { ggp.right = x; }
- x.parent = ggp;
- } else {
- x.parent = null;
- this$1._root = x;
- }
- l = x.left; r = x.right;
- if (x === p.left) { // left
- if (gp) {
- if (gp.left === p) {
- /* zig-zig */
- if (p.right) {
- gp.left = p.right;
- gp.left.parent = gp;
- } else { gp.left = null; }
- p.right = gp;
- gp.parent = p;
- } else {
- /* zig-zag */
- if (l) {
- gp.right = l;
- l.parent = gp;
- } else { gp.right = null; }
- x.left = gp;
- gp.parent = x;
- }
- }
- if (r) {
- p.left = r;
- r.parent = p;
- } else { p.left = null; }
- x.right= p;
- p.parent = x;
- } else { // right
- if (gp) {
- if (gp.right === p) {
- /* zig-zig */
- if (p.left) {
- gp.right = p.left;
- gp.right.parent = gp;
- } else { gp.right = null; }
- p.left = gp;
- gp.parent = p;
- } else {
- /* zig-zag */
- if (r) {
- gp.left = r;
- r.parent = gp;
- } else { gp.left = null; }
- x.right = gp;
- gp.parent = x;
- }
- }
- if (l) {
- p.right = l;
- l.parent = p;
- } else { p.right = null; }
- x.left = p;
- p.parent = x;
- }
- }
- };
- SplayTree.prototype.replace = function replace (u, v) {
- if (!u.parent) { this._root = v; }
- else if (u === u.parent.left) { u.parent.left = v; }
- else { u.parent.right = v; }
- if (v) { v.parent = u.parent; }
- };
- SplayTree.prototype.minNode = function minNode (u) {
- if ( u === void 0 ) u = this._root;
- if (u) { while (u.left) { u = u.left; } }
- return u;
- };
- SplayTree.prototype.maxNode = function maxNode (u) {
- if ( u === void 0 ) u = this._root;
- if (u) { while (u.right) { u = u.right; } }
- return u;
- };
- SplayTree.prototype.insert = function insert (key, data) {
- var z = this._root;
- var p = null;
- var comp = this._compare;
- var cmp;
- if (this._noDuplicates) {
- while (z) {
- p = z;
- cmp = comp(z.key, key);
- if (cmp === 0) { return; }
- else if (comp(z.key, key) < 0) { z = z.right; }
- else { z = z.left; }
- }
- } else {
- while (z) {
- p = z;
- if (comp(z.key, key) < 0) { z = z.right; }
- else { z = z.left; }
- }
- }
- z = { key: key, data: data, left: null, right: null, parent: p };
- if (!p) { this._root = z; }
- else if (comp(p.key, z.key) < 0) { p.right = z; }
- else { p.left= z; }
- this.splay(z);
- this._size++;
- return z;
- };
- SplayTree.prototype.find = function find (key) {
- var z = this._root;
- var comp = this._compare;
- while (z) {
- var cmp = comp(z.key, key);
- if (cmp < 0) { z = z.right; }
- else if (cmp > 0) { z = z.left; }
- else { return z; }
- }
- return null;
- };
- /**
- * Whether the tree contains a node with the given key
- * @param{Key} key
- * @return {boolean} true/false
- */
- SplayTree.prototype.contains = function contains (key) {
- var node = this._root;
- var comparator = this._compare;
- while (node){
- var cmp = comparator(key, node.key);
- if (cmp === 0) { return true; }
- else if (cmp < 0) { node = node.left; }
- else { node = node.right; }
- }
- return false;
- };
- SplayTree.prototype.remove = function remove (key) {
- var z = this.find(key);
- if (!z) { return false; }
- this.splay(z);
- if (!z.left) { this.replace(z, z.right); }
- else if (!z.right) { this.replace(z, z.left); }
- else {
- var y = this.minNode(z.right);
- if (y.parent !== z) {
- this.replace(y, y.right);
- y.right = z.right;
- y.right.parent = y;
- }
- this.replace(z, y);
- y.left = z.left;
- y.left.parent = y;
- }
- this._size--;
- return true;
- };
- SplayTree.prototype.removeNode = function removeNode (z) {
- if (!z) { return false; }
- this.splay(z);
- if (!z.left) { this.replace(z, z.right); }
- else if (!z.right) { this.replace(z, z.left); }
- else {
- var y = this.minNode(z.right);
- if (y.parent !== z) {
- this.replace(y, y.right);
- y.right = z.right;
- y.right.parent = y;
- }
- this.replace(z, y);
- y.left = z.left;
- y.left.parent = y;
- }
- this._size--;
- return true;
- };
- SplayTree.prototype.erase = function erase (key) {
- var z = this.find(key);
- if (!z) { return; }
- this.splay(z);
- var s = z.left;
- var t = z.right;
- var sMax = null;
- if (s) {
- s.parent = null;
- sMax = this.maxNode(s);
- this.splay(sMax);
- this._root = sMax;
- }
- if (t) {
- if (s) { sMax.right = t; }
- else { this._root = t; }
- t.parent = sMax;
- }
- this._size--;
- };
- /**
- * Removes and returns the node with smallest key
- * @return {?Node}
- */
- SplayTree.prototype.pop = function pop () {
- var node = this._root, returnValue = null;
- if (node) {
- while (node.left) { node = node.left; }
- returnValue = { key: node.key, data: node.data };
- this.remove(node.key);
- }
- return returnValue;
- };
- /* eslint-disable class-methods-use-this */
- /**
- * Successor node
- * @param{Node} node
- * @return {?Node}
- */
- SplayTree.prototype.next = function next (node) {
- var successor = node;
- if (successor) {
- if (successor.right) {
- successor = successor.right;
- while (successor && successor.left) { successor = successor.left; }
- } else {
- successor = node.parent;
- while (successor && successor.right === node) {
- node = successor; successor = successor.parent;
- }
- }
- }
- return successor;
- };
- /**
- * Predecessor node
- * @param{Node} node
- * @return {?Node}
- */
- SplayTree.prototype.prev = function prev (node) {
- var predecessor = node;
- if (predecessor) {
- if (predecessor.left) {
- predecessor = predecessor.left;
- while (predecessor && predecessor.right) { predecessor = predecessor.right; }
- } else {
- predecessor = node.parent;
- while (predecessor && predecessor.left === node) {
- node = predecessor;
- predecessor = predecessor.parent;
- }
- }
- }
- return predecessor;
- };
- /* eslint-enable class-methods-use-this */
- /**
- * @param{forEachCallback} callback
- * @return {SplayTree}
- */
- SplayTree.prototype.forEach = function forEach (callback) {
- var current = this._root;
- var s = [], done = false, i = 0;
- while (!done) {
- // Reach the left most Node of the current Node
- if (current) {
- // Place pointer to a tree node on the stack
- // before traversing the node's left subtree
- s.push(current);
- current = current.left;
- } else {
- // BackTrack from the empty subtree and visit the Node
- // at the top of the stack; however, if the stack is
- // empty you are done
- if (s.length > 0) {
- current = s.pop();
- callback(current, i++);
- // We have visited the node and its left
- // subtree. Now, it's right subtree's turn
- current = current.right;
- } else { done = true; }
- }
- }
- return this;
- };
- /**
- * Walk key range from `low` to `high`. Stops if `fn` returns a value.
- * @param{Key} low
- * @param{Key} high
- * @param{Function} fn
- * @param{*?} ctx
- * @return {SplayTree}
- */
- SplayTree.prototype.range = function range (low, high, fn, ctx) {
- var this$1 = this;
- var Q = [];
- var compare = this._compare;
- var node = this._root, cmp;
- while (Q.length !== 0 || node) {
- if (node) {
- Q.push(node);
- node = node.left;
- } else {
- node = Q.pop();
- cmp = compare(node.key, high);
- if (cmp > 0) {
- break;
- } else if (compare(node.key, low) >= 0) {
- if (fn.call(ctx, node)) { return this$1; } // stop if smth is returned
- }
- node = node.right;
- }
- }
- return this;
- };
- /**
- * Returns all keys in order
- * @return {Array<Key>}
- */
- SplayTree.prototype.keys = function keys () {
- var current = this._root;
- var s = [], r = [], done = false;
- while (!done) {
- if (current) {
- s.push(current);
- current = current.left;
- } else {
- if (s.length > 0) {
- current = s.pop();
- r.push(current.key);
- current = current.right;
- } else { done = true; }
- }
- }
- return r;
- };
- /**
- * Returns `data` fields of all nodes in order.
- * @return {Array<Value>}
- */
- SplayTree.prototype.values = function values () {
- var current = this._root;
- var s = [], r = [], done = false;
- while (!done) {
- if (current) {
- s.push(current);
- current = current.left;
- } else {
- if (s.length > 0) {
- current = s.pop();
- r.push(current.data);
- current = current.right;
- } else { done = true; }
- }
- }
- return r;
- };
- /**
- * Returns node at given index
- * @param{number} index
- * @return {?Node}
- */
- SplayTree.prototype.at = function at (index) {
- // removed after a consideration, more misleading than useful
- // index = index % this.size;
- // if (index < 0) index = this.size - index;
- var current = this._root;
- var s = [], done = false, i = 0;
- while (!done) {
- if (current) {
- s.push(current);
- current = current.left;
- } else {
- if (s.length > 0) {
- current = s.pop();
- if (i === index) { return current; }
- i++;
- current = current.right;
- } else { done = true; }
- }
- }
- return null;
- };
- /**
- * Bulk-load items. Both array have to be same size
- * @param{Array<Key>} keys
- * @param{Array<Value>}[values]
- * @param{Boolean} [presort=false] Pre-sort keys and values, using
- * tree's comparator. Sorting is done
- * in-place
- * @return {AVLTree}
- */
- SplayTree.prototype.load = function load (keys, values, presort) {
- if ( keys === void 0 ) keys = [];
- if ( values === void 0 ) values = [];
- if ( presort === void 0 ) presort = false;
- if (this._size !== 0) { throw new Error('bulk-load: tree is not empty'); }
- var size = keys.length;
- if (presort) { sort(keys, values, 0, size - 1, this._compare); }
- this._root = loadRecursive(null, keys, values, 0, size);
- this._size = size;
- return this;
- };
- SplayTree.prototype.min = function min () {
- var node = this.minNode(this._root);
- if (node) { return node.key; }
- else { return null; }
- };
- SplayTree.prototype.max = function max () {
- var node = this.maxNode(this._root);
- if (node) { return node.key; }
- else { return null; }
- };
- SplayTree.prototype.isEmpty = function isEmpty () { return this._root === null; };
- prototypeAccessors.size.get = function () { return this._size; };
- /**
- * Create a tree and load it with items
- * @param{Array<Key>} keys
- * @param{Array<Value>?} [values]
- * @param{Function?} [comparator]
- * @param{Boolean?} [presort=false] Pre-sort keys and values, using
- * tree's comparator. Sorting is done
- * in-place
- * @param{Boolean?} [noDuplicates=false] Allow duplicates
- * @return {SplayTree}
- */
- SplayTree.createTree = function createTree (keys, values, comparator, presort, noDuplicates) {
- return new SplayTree(comparator, noDuplicates).load(keys, values, presort);
- };
- Object.defineProperties( SplayTree.prototype, prototypeAccessors );
- function loadRecursive (parent, keys, values, start, end) {
- var size = end - start;
- if (size > 0) {
- var middle = start + Math.floor(size / 2);
- var key = keys[middle];
- var data = values[middle];
- var node = { key: key, data: data, parent: parent };
- node.left = loadRecursive(node, keys, values, start, middle);
- node.right = loadRecursive(node, keys, values, middle + 1, end);
- return node;
- }
- return null;
- }
- function sort(keys, values, left, right, compare) {
- if (left >= right) { return; }
- var pivot = keys[(left + right) >> 1];
- var i = left - 1;
- var j = right + 1;
- while (true) {
- do { i++; } while (compare(keys[i], pivot) < 0);
- do { j--; } while (compare(keys[j], pivot) > 0);
- if (i >= j) { break; }
- var tmp = keys[i];
- keys[i] = keys[j];
- keys[j] = tmp;
- tmp = values[i];
- values[i] = values[j];
- values[j] = tmp;
- }
- sort(keys, values, left, j, compare);
- sort(keys, values, j + 1, right, compare);
- }
- var NORMAL = 0;
- var NON_CONTRIBUTING = 1;
- var SAME_TRANSITION = 2;
- var DIFFERENT_TRANSITION = 3;
- var INTERSECTION = 0;
- var UNION = 1;
- var DIFFERENCE = 2;
- var XOR = 3;
- /**
- * @param {SweepEvent} event
- * @param {SweepEvent} prev
- * @param {Operation} operation
- */
- function computeFields (event, prev, operation) {
- // compute inOut and otherInOut fields
- if (prev === null) {
- event.inOut = false;
- event.otherInOut = true;
- // previous line segment in sweepline belongs to the same polygon
- } else {
- if (event.isSubject === prev.isSubject) {
- event.inOut = !prev.inOut;
- event.otherInOut = prev.otherInOut;
- // previous line segment in sweepline belongs to the clipping polygon
- } else {
- event.inOut = !prev.otherInOut;
- event.otherInOut = prev.isVertical() ? !prev.inOut : prev.inOut;
- }
- // compute prevInResult field
- if (prev) {
- event.prevInResult = (!inResult(prev, operation) || prev.isVertical())
- ? prev.prevInResult : prev;
- }
- }
- // check if the line segment belongs to the Boolean operation
- event.inResult = inResult(event, operation);
- }
- /* eslint-disable indent */
- function inResult(event, operation) {
- switch (event.type) {
- case NORMAL:
- switch (operation) {
- case INTERSECTION:
- return !event.otherInOut;
- case UNION:
- return event.otherInOut;
- case DIFFERENCE:
- // return (event.isSubject && !event.otherInOut) ||
- // (!event.isSubject && event.otherInOut);
- return (event.isSubject && event.otherInOut) ||
- (!event.isSubject && !event.otherInOut);
- case XOR:
- return true;
- }
- break;
- case SAME_TRANSITION:
- return operation === INTERSECTION || operation === UNION;
- case DIFFERENT_TRANSITION:
- return operation === DIFFERENCE;
- case NON_CONTRIBUTING:
- return false;
- }
- return false;
- }
- /* eslint-enable indent */
- var SweepEvent = function SweepEvent (point, left, otherEvent, isSubject, edgeType) {
- /**
- * Is left endpoint?
- * @type {Boolean}
- */
- this.left = left;
- /**
- * @type {Array.<Number>}
- */
- this.point = point;
- /**
- * Other edge reference
- * @type {SweepEvent}
- */
- this.otherEvent = otherEvent;
- /**
- * Belongs to source or clipping polygon
- * @type {Boolean}
- */
- this.isSubject = isSubject;
- /**
- * Edge contribution type
- * @type {Number}
- */
- this.type = edgeType || NORMAL;
- /**
- * In-out transition for the sweepline crossing polygon
- * @type {Boolean}
- */
- this.inOut = false;
- /**
- * @type {Boolean}
- */
- this.otherInOut = false;
- /**
- * Previous event in result?
- * @type {SweepEvent}
- */
- this.prevInResult = null;
- /**
- * Does event belong to result?
- * @type {Boolean}
- */
- this.inResult = false;
- // connection step
- /**
- * @type {Boolean}
- */
- this.resultInOut = false;
- this.isExteriorRing = true;
- };
- /**
- * @param{Array.<Number>}p
- * @return {Boolean}
- */
- SweepEvent.prototype.isBelow = function isBelow (p) {
- var p0 = this.point, p1 = this.otherEvent.point;
- return this.left
- ? (p0[0] - p[0]) * (p1[1] - p[1]) - (p1[0] - p[0]) * (p0[1] - p[1]) > 0
- // signedArea(this.point, this.otherEvent.point, p) > 0 :
- : (p1[0] - p[0]) * (p0[1] - p[1]) - (p0[0] - p[0]) * (p1[1] - p[1]) > 0;
- //signedArea(this.otherEvent.point, this.point, p) > 0;
- };
- /**
- * @param{Array.<Number>}p
- * @return {Boolean}
- */
- SweepEvent.prototype.isAbove = function isAbove (p) {
- return !this.isBelow(p);
- };
- /**
- * @return {Boolean}
- */
- SweepEvent.prototype.isVertical = function isVertical () {
- return this.point[0] === this.otherEvent.point[0];
- };
- SweepEvent.prototype.clone = function clone () {
- var copy = new SweepEvent(
- this.point, this.left, this.otherEvent, this.isSubject, this.type);
- copy.inResult = this.inResult;
- copy.prevInResult = this.prevInResult;
- copy.isExteriorRing = this.isExteriorRing;
- copy.inOut = this.inOut;
- copy.otherInOut = this.otherInOut;
- return copy;
- };
- function equals(p1, p2) {
- if (p1[0] === p2[0]) {
- if (p1[1] === p2[1]) {
- return true;
- } else {
- return false;
- }
- }
- return false;
- }
- // const EPSILON = 1e-9;
- // const abs = Math.abs;
- // TODO https://github.com/w8r/martinez/issues/6#issuecomment-262847164
- // Precision problem.
- //
- // module.exports = function equals(p1, p2) {
- // return abs(p1[0] - p2[0]) <= EPSILON && abs(p1[1] - p2[1]) <= EPSILON;
- // };
- /**
- * Signed area of the triangle (p0, p1, p2)
- * @param {Array.<Number>} p0
- * @param {Array.<Number>} p1
- * @param {Array.<Number>} p2
- * @return {Number}
- */
- function signedArea(p0, p1, p2) {
- return (p0[0] - p2[0]) * (p1[1] - p2[1]) - (p1[0] - p2[0]) * (p0[1] - p2[1]);
- }
- /**
- * @param {SweepEvent} e1
- * @param {SweepEvent} e2
- * @return {Number}
- */
- function compareEvents(e1, e2) {
- var p1 = e1.point;
- var p2 = e2.point;
- // Different x-coordinate
- if (p1[0] > p2[0]) { return 1; }
- if (p1[0] < p2[0]) { return -1; }
- // Different points, but same x-coordinate
- // Event with lower y-coordinate is processed first
- if (p1[1] !== p2[1]) { return p1[1] > p2[1] ? 1 : -1; }
- return specialCases(e1, e2, p1, p2);
- }
- /* eslint-disable no-unused-vars */
- function specialCases(e1, e2, p1, p2) {
- // Same coordinates, but one is a left endpoint and the other is
- // a right endpoint. The right endpoint is processed first
- if (e1.left !== e2.left)
- { return e1.left ? 1 : -1; }
- // const p2 = e1.otherEvent.point, p3 = e2.otherEvent.point;
- // const sa = (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
- // Same coordinates, both events
- // are left endpoints or right endpoints.
- // not collinear
- if (signedArea(p1, e1.otherEvent.point, e2.otherEvent.point) !== 0) {
- // the event associate to the bottom segment is processed first
- return (!e1.isBelow(e2.otherEvent.point)) ? 1 : -1;
- }
- return (!e1.isSubject && e2.isSubject) ? 1 : -1;
- }
- /* eslint-enable no-unused-vars */
- /**
- * @param {SweepEvent} se
- * @param {Array.<Number>} p
- * @param {Queue} queue
- * @return {Queue}
- */
- function divideSegment(se, p, queue) {
- var r = new SweepEvent(p, false, se, se.isSubject);
- var l = new SweepEvent(p, true, se.otherEvent, se.isSubject);
- /* eslint-disable no-console */
- if (equals(se.point, se.otherEvent.point)) {
- console.warn('what is that, a collapsed segment?', se);
- }
- /* eslint-enable no-console */
- r.contourId = l.contourId = se.contourId;
- // avoid a rounding error. The left event would be processed after the right event
- if (compareEvents(l, se.otherEvent) > 0) {
- se.otherEvent.left = true;
- l.left = false;
- }
- // avoid a rounding error. The left event would be processed after the right event
- // if (compareEvents(se, r) > 0) {}
- se.otherEvent.otherEvent = l;
- se.otherEvent = r;
- queue.push(l);
- queue.push(r);
- return queue;
- }
- //const EPS = 1e-9;
- /**
- * Finds the magnitude of the cross product of two vectors (if we pretend
- * they're in three dimensions)
- *
- * @param {Object} a First vector
- * @param {Object} b Second vector
- * @private
- * @returns {Number} The magnitude of the cross product
- */
- function crossProduct(a, b) {
- return (a[0] * b[1]) - (a[1] * b[0]);
- }
- /**
- * Finds the dot product of two vectors.
- *
- * @param {Object} a First vector
- * @param {Object} b Second vector
- * @private
- * @returns {Number} The dot product
- */
- function dotProduct(a, b) {
- return (a[0] * b[0]) + (a[1] * b[1]);
- }
- /**
- * Finds the intersection (if any) between two line segments a and b, given the
- * line segments' end points a1, a2 and b1, b2.
- *
- * This algorithm is based on Schneider and Eberly.
- * http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf
- * Page 244.
- *
- * @param {Array.<Number>} a1 point of first line
- * @param {Array.<Number>} a2 point of first line
- * @param {Array.<Number>} b1 point of second line
- * @param {Array.<Number>} b2 point of second line
- * @param {Boolean=} noEndpointTouch whether to skip single touchpoints
- * (meaning connected segments) as
- * intersections
- * @returns {Array.<Array.<Number>>|Null} If the lines intersect, the point of
- * intersection. If they overlap, the two end points of the overlapping segment.
- * Otherwise, null.
- */
- function intersection (a1, a2, b1, b2, noEndpointTouch) {
- // The algorithm expects our lines in the form P + sd, where P is a point,
- // s is on the interval [0, 1], and d is a vector.
- // We are passed two points. P can be the first point of each pair. The
- // vector, then, could be thought of as the distance (in x and y components)
- // from the first point to the second point.
- // So first, let's make our vectors:
- var va = [a2[0] - a1[0], a2[1] - a1[1]];
- var vb = [b2[0] - b1[0], b2[1] - b1[1]];
- // We also define a function to convert back to regular point form:
- /* eslint-disable arrow-body-style */
- function toPoint(p, s, d) {
- return [
- p[0] + s * d[0],
- p[1] + s * d[1]
- ];
- }
- /* eslint-enable arrow-body-style */
- // The rest is pretty much a straight port of the algorithm.
- var e = [b1[0] - a1[0], b1[1] - a1[1]];
- var kross = crossProduct(va, vb);
- var sqrKross = kross * kross;
- var sqrLenA = dotProduct(va, va);
- //const sqrLenB = dotProduct(vb, vb);
- // Check for line intersection. This works because of the properties of the
- // cross product -- specifically, two vectors are parallel if and only if the
- // cross product is the 0 vector. The full calculation involves relative error
- // to account for possible very small line segments. See Schneider & Eberly
- // for details.
- if (sqrKross > 0/* EPS * sqrLenB * sqLenA */) {
- // If they're not parallel, then (because these are line segments) they
- // still might not actually intersect. This code checks that the
- // intersection point of the lines is actually on both line segments.
- var s = crossProduct(e, vb) / kross;
- if (s < 0 || s > 1) {
- // not on line segment a
- return null;
- }
- var t = crossProduct(e, va) / kross;
- if (t < 0 || t > 1) {
- // not on line segment b
- return null;
- }
- if (s === 0 || s === 1) {
- // on an endpoint of line segment a
- return noEndpointTouch ? null : [toPoint(a1, s, va)];
- }
- if (t === 0 || t === 1) {
- // on an endpoint of line segment b
- return noEndpointTouch ? null : [toPoint(b1, t, vb)];
- }
- return [toPoint(a1, s, va)];
- }
- // If we've reached this point, then the lines are either parallel or the
- // same, but the segments could overlap partially or fully, or not at all.
- // So we need to find the overlap, if any. To do that, we can use e, which is
- // the (vector) difference between the two initial points. If this is parallel
- // with the line itself, then the two lines are the same line, and there will
- // be overlap.
- //const sqrLenE = dotProduct(e, e);
- kross = crossProduct(e, va);
- sqrKross = kross * kross;
- if (sqrKross > 0 /* EPS * sqLenB * sqLenE */) {
- // Lines are just parallel, not the same. No overlap.
- return null;
- }
- var sa = dotProduct(va, e) / sqrLenA;
- var sb = sa + dotProduct(va, vb) / sqrLenA;
- var smin = Math.min(sa, sb);
- var smax = Math.max(sa, sb);
- // this is, essentially, the FindIntersection acting on floats from
- // Schneider & Eberly, just inlined into this function.
- if (smin <= 1 && smax >= 0) {
- // overlap on an end point
- if (smin === 1) {
- return noEndpointTouch ? null : [toPoint(a1, smin > 0 ? smin : 0, va)];
- }
- if (smax === 0) {
- return noEndpointTouch ? null : [toPoint(a1, smax < 1 ? smax : 1, va)];
- }
- if (noEndpointTouch && smin === 0 && smax === 1) { return null; }
- // There's overlap on a segment -- two points of intersection. Return both.
- return [
- toPoint(a1, smin > 0 ? smin : 0, va),
- toPoint(a1, smax < 1 ? smax : 1, va)
- ];
- }
- return null;
- }
- /**
- * @param {SweepEvent} se1
- * @param {SweepEvent} se2
- * @param {Queue} queue
- * @return {Number}
- */
- function possibleIntersection (se1, se2, queue) {
- // that disallows self-intersecting polygons,
- // did cost us half a day, so I'll leave it
- // out of respect
- // if (se1.isSubject === se2.isSubject) return;
- var inter = intersection(
- se1.point, se1.otherEvent.point,
- se2.point, se2.otherEvent.point
- );
- var nintersections = inter ? inter.length : 0;
- if (nintersections === 0) { return 0; } // no intersection
- // the line segments intersect at an endpoint of both line segments
- if ((nintersections === 1) &&
- (equals(se1.point, se2.point) ||
- equals(se1.otherEvent.point, se2.otherEvent.point))) {
- return 0;
- }
- if (nintersections === 2 && se1.isSubject === se2.isSubject) {
- // if(se1.contourId === se2.contourId){
- // console.warn('Edges of the same polygon overlap',
- // se1.point, se1.otherEvent.point, se2.point, se2.otherEvent.point);
- // }
- //throw new Error('Edges of the same polygon overlap');
- return 0;
- }
- // The line segments associated to se1 and se2 intersect
- if (nintersections === 1) {
- // if the intersection point is not an endpoint of se1
- if (!equals(se1.point, inter[0]) && !equals(se1.otherEvent.point, inter[0])) {
- divideSegment(se1, inter[0], queue);
- }
- // if the intersection point is not an endpoint of se2
- if (!equals(se2.point, inter[0]) && !equals(se2.otherEvent.point, inter[0])) {
- divideSegment(se2, inter[0], queue);
- }
- return 1;
- }
- // The line segments associated to se1 and se2 overlap
- var events = [];
- var leftCoincide = false;
- var rightCoincide = false;
- if (equals(se1.point, se2.point)) {
- leftCoincide = true; // linked
- } else if (compareEvents(se1, se2) === 1) {
- events.push(se2, se1);
- } else {
- events.push(se1, se2);
- }
- if (equals(se1.otherEvent.point, se2.otherEvent.point)) {
- rightCoincide = true;
- } else if (compareEvents(se1.otherEvent, se2.otherEvent) === 1) {
- events.push(se2.otherEvent, se1.otherEvent);
- } else {
- events.push(se1.otherEvent, se2.otherEvent);
- }
- if ((leftCoincide && rightCoincide) || leftCoincide) {
- // both line segments are equal or share the left endpoint
- se2.type = NON_CONTRIBUTING;
- se1.type = (se2.inOut === se1.inOut)
- ? SAME_TRANSITION : DIFFERENT_TRANSITION;
- if (leftCoincide && !rightCoincide) {
- // honestly no idea, but changing events selection from [2, 1]
- // to [0, 1] fixes the overlapping self-intersecting polygons issue
- divideSegment(events[1].otherEvent, events[0].point, queue);
- }
- return 2;
- }
- // the line segments share the right endpoint
- if (rightCoincide) {
- divideSegment(events[0], events[1].point, queue);
- return 3;
- }
- // no line segment includes totally the other one
- if (events[0] !== events[3].otherEvent) {
- divideSegment(events[0], events[1].point, queue);
- divideSegment(events[1], events[2].point, queue);
- return 3;
- }
- // one line segment includes the other one
- divideSegment(events[0], events[1].point, queue);
- divideSegment(events[3].otherEvent, events[2].point, queue);
- return 3;
- }
- /**
- * @param {SweepEvent} le1
- * @param {SweepEvent} le2
- * @return {Number}
- */
- function compareSegments(le1, le2) {
- if (le1 === le2) { return 0; }
- // Segments are not collinear
- if (signedArea(le1.point, le1.otherEvent.point, le2.point) !== 0 ||
- signedArea(le1.point, le1.otherEvent.point, le2.otherEvent.point) !== 0) {
- // If they share their left endpoint use the right endpoint to sort
- if (equals(le1.point, le2.point)) { return le1.isBelow(le2.otherEvent.point) ? -1 : 1; }
- // Different left endpoint: use the left endpoint to sort
- if (le1.point[0] === le2.point[0]) { return le1.point[1] < le2.point[1] ? -1 : 1; }
- // has the line segment associated to e1 been inserted
- // into S after the line segment associated to e2 ?
- if (compareEvents(le1, le2) === 1) { return le2.isAbove(le1.point) ? -1 : 1; }
- // The line segment associated to e2 has been inserted
- // into S after the line segment associated to e1
- return le1.isBelow(le2.point) ? -1 : 1;
- }
- if (le1.isSubject === le2.isSubject) { // same polygon
- var p1 = le1.point, p2 = le2.point;
- if (p1[0] === p2[0] && p1[1] === p2[1]/*equals(le1.point, le2.point)*/) {
- p1 = le1.otherEvent.point; p2 = le2.otherEvent.point;
- if (p1[0] === p2[0] && p1[1] === p2[1]) { return 0; }
- else { return le1.contourId > le2.contourId ? 1 : -1; }
- }
- } else { // Segments are collinear, but belong to separate polygons
- return le1.isSubject ? -1 : 1;
- }
- return compareEvents(le1, le2) === 1 ? 1 : -1;
- }
- function subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation) {
- var sweepLine = new SplayTree(compareSegments);
- var sortedEvents = [];
- var rightbound = Math.min(sbbox[2], cbbox[2]);
- var prev, next, begin;
- while (eventQueue.length !== 0) {
- var event = eventQueue.pop();
- sortedEvents.push(event);
- // optimization by bboxes for intersection and difference goes here
- if ((operation === INTERSECTION && event.point[0] > rightbound) ||
- (operation === DIFFERENCE && event.point[0] > sbbox[2])) {
- break;
- }
- if (event.left) {
- next = prev = sweepLine.insert(event);
- begin = sweepLine.minNode();
- if (prev !== begin) { prev = sweepLine.prev(prev); }
- else { prev = null; }
- next = sweepLine.next(next);
- var prevEvent = prev ? prev.key : null;
- var prevprevEvent = (void 0);
- computeFields(event, prevEvent, operation);
- if (next) {
- if (possibleIntersection(event, next.key, eventQueue) === 2) {
- computeFields(event, prevEvent, operation);
- computeFields(event, next.key, operation);
- }
- }
- if (prev) {
- if (possibleIntersection(prev.key, event, eventQueue) === 2) {
- var prevprev = prev;
- if (prevprev !== begin) { prevprev = sweepLine.prev(prevprev); }
- else { prevprev = null; }
- prevprevEvent = prevprev ? prevprev.key : null;
- computeFields(prevEvent, prevprevEvent, operation);
- computeFields(event, prevEvent, operation);
- }
- }
- } else {
- event = event.otherEvent;
- next = prev = sweepLine.find(event);
- if (prev && next) {
- if (prev !== begin) { prev = sweepLine.prev(prev); }
- else { prev = null; }
- next = sweepLine.next(next);
- sweepLine.remove(event);
- if (next && prev) {
- possibleIntersection(prev.key, next.key, eventQueue);
- }
- }
- }
- }
- return sortedEvents;
- }
- /**
- * @param {Array.<SweepEvent>} sortedEvents
- * @return {Array.<SweepEvent>}
- */
- function orderEvents(sortedEvents) {
- var event, i, len, tmp;
- var resultEvents = [];
- for (i = 0, len = sortedEvents.length; i < len; i++) {
- event = sortedEvents[i];
- if ((event.left && event.inResult) ||
- (!event.left && event.otherEvent.inResult)) {
- resultEvents.push(event);
- }
- }
- // Due to overlapping edges the resultEvents array can be not wholly sorted
- var sorted = false;
- while (!sorted) {
- sorted = true;
- for (i = 0, len = resultEvents.length; i < len; i++) {
- if ((i + 1) < len &&
- compareEvents(resultEvents[i], resultEvents[i + 1]) === 1) {
- tmp = resultEvents[i];
- resultEvents[i] = resultEvents[i + 1];
- resultEvents[i + 1] = tmp;
- sorted = false;
- }
- }
- }
- for (i = 0, len = resultEvents.length; i < len; i++) {
- event = resultEvents[i];
- event.pos = i;
- }
- // imagine, the right event is found in the beginning of the queue,
- // when his left counterpart is not marked yet
- for (i = 0, len = resultEvents.length; i < len; i++) {
- event = resultEvents[i];
- if (!event.left) {
- tmp = event.pos;
- event.pos = event.otherEvent.pos;
- event.otherEvent.pos = tmp;
- }
- }
- return resultEvents;
- }
- /**
- * @param {Number} pos
- * @param {Array.<SweepEvent>} resultEvents
- * @param {Object>} processed
- * @return {Number}
- */
- function nextPos(pos, resultEvents, processed, origIndex) {
- var newPos = pos + 1;
- var length = resultEvents.length;
- if (newPos > length - 1) { return pos - 1; }
- var p = resultEvents[pos].point;
- var p1 = resultEvents[newPos].point;
- // while in range and not the current one by value
- while (newPos < length && p1[0] === p[0] && p1[1] === p[1]) {
- if (!processed[newPos]) {
- return newPos;
- } else {
- newPos++;
- }
- p1 = resultEvents[newPos].point;
- }
- newPos = pos - 1;
- while (processed[newPos] && newPos >= origIndex) {
- newPos--;
- }
- return newPos;
- }
- /**
- * @param {Array.<SweepEvent>} sortedEvents
- * @return {Array.<*>} polygons
- */
- function connectEdges(sortedEvents, operation) {
- var i, len;
- var resultEvents = orderEvents(sortedEvents);
- // "false"-filled array
- var processed = {};
- var result = [];
- var event;
- for (i = 0, len = resultEvents.length; i < len; i++) {
- if (processed[i]) { continue; }
- var contour = [[]];
- if (!resultEvents[i].isExteriorRing) {
- if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length === 0) {
- result.push(contour);
- } else if (result.length === 0) {
- result.push([[contour]]);
- } else {
- result[result.length - 1].push(contour[0]);
- }
- } else if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length > 1) {
- result[result.length - 1].push(contour[0]);
- } else {
- result.push(contour);
- }
- var ringId = result.length - 1;
- var pos = i;
- var initial = resultEvents[i].point;
- contour[0].push(initial);
- while (pos >= i) {
- event = resultEvents[pos];
- processed[pos] = true;
- if (event.left) {
- event.resultInOut = false;
- event.contourId = ringId;
- } else {
- event.otherEvent.resultInOut = true;
- event.otherEvent.contourId = ringId;
- }
- pos = event.pos;
- processed[pos] = true;
- contour[0].push(resultEvents[pos].point);
- pos = nextPos(pos, resultEvents, processed, i);
- }
- pos = pos === -1 ? i : pos;
- event = resultEvents[pos];
- processed[pos] = processed[event.pos] = true;
- event.otherEvent.resultInOut = true;
- event.otherEvent.contourId = ringId;
- }
- // Handle if the result is a polygon (eg not multipoly)
- // Commented it again, let's see what do we mean by that
- // if (result.length === 1) result = result[0];
- return result;
- }
- var tinyqueue = TinyQueue;
- var default_1 = TinyQueue;
- function TinyQueue(data, compare) {
- var this$1 = this;
- if (!(this instanceof TinyQueue)) { return new TinyQueue(data, compare); }
- this.data = data || [];
- this.length = this.data.length;
- this.compare = compare || defaultCompare;
- if (this.length > 0) {
- for (var i = (this.length >> 1) - 1; i >= 0; i--) { this$1._down(i); }
- }
- }
- function defaultCompare(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
- }
- TinyQueue.prototype = {
- push: function (item) {
- this.data.push(item);
- this.length++;
- this._up(this.length - 1);
- },
- pop: function () {
- if (this.length === 0) { return undefined; }
- var top = this.data[0];
- this.length--;
- if (this.length > 0) {
- this.data[0] = this.data[this.length];
- this._down(0);
- }
- this.data.pop();
- return top;
- },
- peek: function () {
- return this.data[0];
- },
- _up: function (pos) {
- var data = this.data;
- var compare = this.compare;
- var item = data[pos];
- while (pos > 0) {
- var parent = (pos - 1) >> 1;
- var current = data[parent];
- if (compare(item, current) >= 0) { break; }
- data[pos] = current;
- pos = parent;
- }
- data[pos] = item;
- },
- _down: function (pos) {
- var this$1 = this;
- var data = this.data;
- var compare = this.compare;
- var halfLength = this.length >> 1;
- var item = data[pos];
- while (pos < halfLength) {
- var left = (pos << 1) + 1;
- var right = left + 1;
- var best = data[left];
- if (right < this$1.length && compare(data[right], best) < 0) {
- left = right;
- best = data[right];
- }
- if (compare(best, item) >= 0) { break; }
- data[pos] = best;
- pos = left;
- }
- data[pos] = item;
- }
- };
- tinyqueue.default = default_1;
- var max = Math.max;
- var min = Math.min;
- var contourId = 0;
- function processPolygon(contourOrHole, isSubject, depth, Q, bbox, isExteriorRing) {
- var i, len, s1, s2, e1, e2;
- for (i = 0, len = contourOrHole.length - 1; i < len; i++) {
- s1 = contourOrHole[i];
- s2 = contourOrHole[i + 1];
- e1 = new SweepEvent(s1, false, undefined, isSubject);
- e2 = new SweepEvent(s2, false, e1, isSubject);
- e1.otherEvent = e2;
- if (s1[0] === s2[0] && s1[1] === s2[1]) {
- continue; // skip collapsed edges, or it breaks
- }
- e1.contourId = e2.contourId = depth;
- if (!isExteriorRing) {
- e1.isExteriorRing = false;
- e2.isExteriorRing = false;
- }
- if (compareEvents(e1, e2) > 0) {
- e2.left = true;
- } else {
- e1.left = true;
- }
- var x = s1[0], y = s1[1];
- bbox[0] = min(bbox[0], x);
- bbox[1] = min(bbox[1], y);
- bbox[2] = max(bbox[2], x);
- bbox[3] = max(bbox[3], y);
- // Pushing it so the queue is sorted from left to right,
- // with object on the left having the highest priority.
- Q.push(e1);
- Q.push(e2);
- }
- }
- function fillQueue(subject, clipping, sbbox, cbbox, operation) {
- var eventQueue = new tinyqueue(null, compareEvents);
- var polygonSet, isExteriorRing, i, ii, j, jj; //, k, kk;
- for (i = 0, ii = subject.length; i < ii; i++) {
- polygonSet = subject[i];
- for (j = 0, jj = polygonSet.length; j < jj; j++) {
- isExteriorRing = j === 0;
- if (isExteriorRing) { contourId++; }
- processPolygon(polygonSet[j], true, contourId, eventQueue, sbbox, isExteriorRing);
- }
- }
- for (i = 0, ii = clipping.length; i < ii; i++) {
- polygonSet = clipping[i];
- for (j = 0, jj = polygonSet.length; j < jj; j++) {
- isExteriorRing = j === 0;
- if (operation === DIFFERENCE) { isExteriorRing = false; }
- if (isExteriorRing) { contourId++; }
- processPolygon(polygonSet[j], false, contourId, eventQueue, cbbox, isExteriorRing);
- }
- }
- return eventQueue;
- }
- var EMPTY = [];
- function trivialOperation(subject, clipping, operation) {
- var result = null;
- if (subject.length * clipping.length === 0) {
- if (operation === INTERSECTION) {
- result = EMPTY;
- } else if (operation === DIFFERENCE) {
- result = subject;
- } else if (operation === UNION ||
- operation === XOR) {
- result = (subject.length === 0) ? clipping : subject;
- }
- }
- return result;
- }
- function compareBBoxes(subject, clipping, sbbox, cbbox, operation) {
- var result = null;
- if (sbbox[0] > cbbox[2] ||
- cbbox[0] > sbbox[2] ||
- sbbox[1] > cbbox[3] ||
- cbbox[1] > sbbox[3]) {
- if (operation === INTERSECTION) {
- result = EMPTY;
- } else if (operation === DIFFERENCE) {
- result = subject;
- } else if (operation === UNION ||
- operation === XOR) {
- result = subject.concat(clipping);
- }
- }
- return result;
- }
- function boolean(subject, clipping, operation) {
- if (typeof subject[0][0][0] === 'number') {
- subject = [subject];
- }
- if (typeof clipping[0][0][0] === 'number') {
- clipping = [clipping];
- }
- var trivial = trivialOperation(subject, clipping, operation);
- if (trivial) {
- return trivial === EMPTY ? null : trivial;
- }
- var sbbox = [Infinity, Infinity, -Infinity, -Infinity];
- var cbbox = [Infinity, Infinity, -Infinity, -Infinity];
- //console.time('fill queue');
- var eventQueue = fillQueue(subject, clipping, sbbox, cbbox, operation);
- //console.timeEnd('fill queue');
- trivial = compareBBoxes(subject, clipping, sbbox, cbbox, operation);
- if (trivial) {
- return trivial === EMPTY ? null : trivial;
- }
- //console.time('subdivide edges');
- var sortedEvents = subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation);
- //console.timeEnd('subdivide edges');
- //console.time('connect vertices');
- var result = connectEdges(sortedEvents, operation);
- //console.timeEnd('connect vertices');
- return result;
- }
- function union (subject, clipping) {
- return boolean(subject, clipping, UNION);
- }
- function diff (subject, clipping) {
- return boolean(subject, clipping, DIFFERENCE);
- }
- function xor (subject, clipping){
- return boolean(subject, clipping, XOR);
- }
- function intersection$1 (subject, clipping) {
- return boolean(subject, clipping, INTERSECTION);
- }
- /**
- * @enum {Number}
- */
- var operations = { UNION: UNION, DIFFERENCE: DIFFERENCE, INTERSECTION: INTERSECTION, XOR: XOR };
- exports.union = union;
- exports.diff = diff;
- exports.xor = xor;
- exports.intersection = intersection$1;
- exports.operations = operations;
- Object.defineProperty(exports, '__esModule', { value: true });
- })));
- },{}],174:[function(require,module,exports){
- const turf = {
- nearestPointOnLine: require('@turf/nearest-point-on-line').default,
- booleanPointInPolygon: require('@turf/boolean-point-in-polygon').default
- }
- function nearestPointOnGeometry (feature, pt, options) {
- var result
- if (!feature.geometry) {
- return null
- }
- switch (feature.geometry.type) {
- case 'LineString':
- case 'MultiLineString':
- return turf.nearestPointOnLine(feature, pt, options)
- case 'Polygon':
- if (turf.booleanPointInPolygon(pt, feature, options)) {
- let result = JSON.parse(JSON.stringify(pt))
- result.properties = {
- 'dist': 0,
- 'location': 0
- }
- return result
- } else {
- let modifiedFeature = JSON.parse(JSON.stringify(feature))
- modifiedFeature.geometry.type = 'MultiLineString'
- return nearestPointOnGeometry(modifiedFeature, pt, options)
- }
- case 'MultiPolygon':
- result = feature.geometry.coordinates.map(coord => {
- let modifiedFeature = {
- type: 'Feature',
- geometry: {
- type: 'Polygon',
- coordinates: coord
- }
- }
- return nearestPointOnGeometry(modifiedFeature, pt, options)
- })
- result = result.filter(o => o)
- result = result.sort((a, b) => {
- if (!a || !b) {
- return null
- }
- return a.properties.dist - b.properties.dist
- })
- if (result.length > 0) {
- return result[0]
- }
- return
- case 'GeometryCollection':
- result = feature.geometry.geometries.map(geom => {
- let modifiedFeature = {
- type: 'Feature',
- geometry: geom
- }
- return nearestPointOnGeometry(modifiedFeature, pt, options)
- })
- result = result.filter(o => o)
- result = result.sort((a, b) => {
- if (!a || !b) {
- return null
- }
- return a.properties.dist - b.properties.dist
- })
- if (result.length > 0) {
- return result[0]
- }
- return
- default:
- console.log('nearestPointOnGeometry: don\'t know how to handle ' + feature.geometry.type)
- }
- }
- module.exports = nearestPointOnGeometry
- },{"@turf/boolean-point-in-polygon":7,"@turf/nearest-point-on-line":17}],175:[function(require,module,exports){
- module.exports = require('./polygon-features.json')
- },{"./polygon-features.json":176}],176:[function(require,module,exports){
- module.exports=[
- {
- "key": "building",
- "polygon": "all"
- },
- {
- "key": "highway",
- "polygon": "whitelist",
- "values": [
- "services",
- "rest_area",
- "escape",
- "elevator"
- ]
- },
- {
- "key": "natural",
- "polygon": "blacklist",
- "values": [
- "coastline",
- "cliff",
- "ridge",
- "arete",
- "tree_row"
- ]
- },
- {
- "key": "landuse",
- "polygon": "all"
- },
- {
- "key": "waterway",
- "polygon": "whitelist",
- "values": [
- "riverbank",
- "dock",
- "boatyard",
- "dam"
- ]
- },
- {
- "key": "amenity",
- "polygon": "all"
- },
- {
- "key": "leisure",
- "polygon": "all"
- },
- {
- "key": "barrier",
- "polygon": "whitelist",
- "values": [
- "city_wall",
- "ditch",
- "hedge",
- "retaining_wall",
- "wall",
- "spikes"
- ]
- },
- {
- "key": "railway",
- "polygon": "whitelist",
- "values": [
- "station",
- "turntable",
- "roundhouse",
- "platform"
- ]
- },
- {
- "key": "area",
- "polygon": "all"
- },
- {
- "key": "boundary",
- "polygon": "all"
- },
- {
- "key": "man_made",
- "polygon": "blacklist",
- "values": [
- "cutline",
- "embankment",
- "pipeline"
- ]
- },
- {
- "key": "power",
- "polygon": "whitelist",
- "values": [
- "plant",
- "substation",
- "generator",
- "transformer"
- ]
- },
- {
- "key": "place",
- "polygon": "all"
- },
- {
- "key": "shop",
- "polygon": "all"
- },
- {
- "key": "aeroway",
- "polygon": "blacklist",
- "values": [
- "taxiway"
- ]
- },
- {
- "key": "tourism",
- "polygon": "all"
- },
- {
- "key": "historic",
- "polygon": "all"
- },
- {
- "key": "public_transport",
- "polygon": "all"
- },
- {
- "key": "office",
- "polygon": "all"
- },
- {
- "key": "building:part",
- "polygon": "all"
- },
- {
- "key": "military",
- "polygon": "all"
- },
- {
- "key": "ruins",
- "polygon": "all"
- },
- {
- "key": "area:highway",
- "polygon": "all"
- },
- {
- "key": "craft",
- "polygon": "all"
- },
- {
- "key": "golf",
- "polygon": "all"
- },
- {
- "key": "indoor",
- "polygon": "all"
- }
- ]
- },{}],177:[function(require,module,exports){
- var _ = require("./lodash.custom.js");
- var rewind = require("geojson-rewind");
- // see https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features
- var polygonFeatures = {};
- require("osm-polygon-features").forEach(function(tags) {
- if (tags.polygon === "all")
- polygonFeatures[tags.key] = true;
- else {
- var list = (tags.polygon === "whitelist") ? "included_values" : "excluded_values",
- tagValuesObj = {};
- tags.values.forEach(function(value) { tagValuesObj[value] = true; });
- polygonFeatures[tags.key] = {};
- polygonFeatures[tags.key][list] = tagValuesObj;
- }
- });
- // default deduplication helper function
- function default_deduplicator(objectA, objectB) {
- // default deduplication handler:
- // if object versions differ, use highest available version
- if ((objectA.version || objectB.version) &&
- (objectA.version !== objectB.version)) {
- return (+objectA.version || 0) > (+objectB.version || 0)
- ? objectA
- : objectB;
- }
- // otherwise: return merged obj properties
- return _.merge(objectA, objectB);
- }
- var osmtogeojson = {};
- osmtogeojson = function( data, options, featureCallback ) {
- options = _.merge(
- {
- verbose: false,
- flatProperties: true,
- uninterestingTags: {
- "source": true,
- "source_ref": true,
- "source:ref": true,
- "history": true,
- "attribution": true,
- "created_by": true,
- "tiger:county": true,
- "tiger:tlid": true,
- "tiger:upload_uuid": true
- },
- polygonFeatures: polygonFeatures,
- deduplicator: default_deduplicator
- },
- options
- );
- var result;
- if ( ((typeof XMLDocument !== "undefined") && data instanceof XMLDocument ||
- (typeof XMLDocument === "undefined") && data.childNodes) )
- result = _osmXML2geoJSON(data);
- else
- result = _overpassJSON2geoJSON(data);
- return result;
- function _overpassJSON2geoJSON(json) {
- // sort elements
- var nodes = new Array();
- var ways = new Array();
- var rels = new Array();
- // helper functions
- function centerGeometry(object) {
- var pseudoNode = _.clone(object);
- pseudoNode.lat = object.center.lat;
- pseudoNode.lon = object.center.lon;
- pseudoNode.__is_center_placeholder = true;
- nodes.push(pseudoNode);
- }
- function boundsGeometry(object) {
- var pseudoWay = _.clone(object);
- pseudoWay.nodes = [];
- function addPseudoNode(lat,lon,i) {
- var pseudoNode = {
- type:"node",
- id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i,
- lat: lat,
- lon: lon
- }
- pseudoWay.nodes.push(pseudoNode.id);
- nodes.push(pseudoNode);
- }
- addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.minlon,1);
- addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.minlon,2);
- addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.maxlon,3);
- addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.maxlon,4);
- pseudoWay.nodes.push(pseudoWay.nodes[0]);
- pseudoWay.__is_bounds_placeholder = true;
- ways.push(pseudoWay);
- }
- function fullGeometryWay(way) {
- function addFullGeometryNode(lat,lon,id) {
- var geometryNode = {
- type:"node",
- id: id,
- lat: lat,
- lon: lon
- }
- nodes.push(geometryNode);
- }
- if (!_.isArray(way.nodes)) {
- way.nodes = way.geometry.map(function(nd) {
- if (nd !== null) // have to skip ref-less nodes
- return "_anonymous@"+nd.lat+"/"+nd.lon;
- else
- return "_anonymous@unknown_location";
- });
- }
- way.geometry.forEach(function(nd, i) {
- if (nd) {
- addFullGeometryNode(
- nd.lat,
- nd.lon,
- way.nodes[i]
- );
- }
- });
- }
- function fullGeometryRelation(rel) {
- function addFullGeometryNode(lat,lon,id) {
- var geometryNode = {
- type:"node",
- id: id,
- lat: lat,
- lon: lon
- }
- nodes.push(geometryNode);
- }
- function addFullGeometryWay(geometry,id) {
- // shared multipolygon ways cannot be defined multiple times with the same id.
- if (ways.some(function (way) { // todo: this is slow :(
- return way.type == "way" && way.id == id;
- })) return;
- var geometryWay = {
- type: "way",
- id: id,
- nodes:[]
- }
- function addFullGeometryWayPseudoNode(lat,lon) {
- // todo? do not save the same pseudo node multiple times
- var geometryPseudoNode = {
- type:"node",
- id: "_anonymous@"+lat+"/"+lon,
- lat: lat,
- lon: lon
- }
- geometryWay.nodes.push(geometryPseudoNode.id);
- nodes.push(geometryPseudoNode);
- }
- geometry.forEach(function(nd) {
- if (nd) {
- addFullGeometryWayPseudoNode(
- nd.lat,
- nd.lon
- );
- } else {
- geometryWay.nodes.push(undefined);
- }
- });
- ways.push(geometryWay);
- }
- rel.members.forEach(function(member, i) {
- if (member.type == "node") {
- if (member.lat) {
- addFullGeometryNode(
- member.lat,
- member.lon,
- member.ref
- );
- }
- } else if (member.type == "way") {
- if (member.geometry) {
- member.ref = "_fullGeom"+member.ref;
- addFullGeometryWay(
- member.geometry,
- member.ref
- );
- }
- }
- });
- }
- // create copies of individual json objects to make sure the original data doesn't get altered
- // todo: cloning is slow: see if this can be done differently!
- for (var i=0;i<json.elements.length;i++) {
- switch (json.elements[i].type) {
- case "node":
- var node = json.elements[i];
- nodes.push(node);
- break;
- case "way":
- var way = _.clone(json.elements[i]);
- way.nodes = _.clone(way.nodes);
- ways.push(way);
- if (way.center)
- centerGeometry(way);
- if (way.geometry)
- fullGeometryWay(way);
- else if (way.bounds)
- boundsGeometry(way);
- break;
- case "relation":
- var rel = _.clone(json.elements[i]);
- rel.members = _.clone(rel.members);
- rels.push(rel);
- var has_full_geometry = rel.members && rel.members.some(function (member) {
- return member.type == "node" && member.lat ||
- member.type == "way" && member.geometry && member.geometry.length > 0
- });
- if (rel.center)
- centerGeometry(rel);
- if (has_full_geometry)
- fullGeometryRelation(rel);
- else if (rel.bounds)
- boundsGeometry(rel);
- break;
- default:
- // type=area (from coord-query) is an example for this case.
- }
- }
- return _convert2geoJSON(nodes,ways,rels);
- }
- function _osmXML2geoJSON(xml) {
- // sort elements
- var nodes = new Array();
- var ways = new Array();
- var rels = new Array();
- // helper function
- function copy_attribute( x, o, attr ) {
- if (x.hasAttribute(attr))
- o[attr] = x.getAttribute(attr);
- }
- function centerGeometry(object, centroid) {
- var pseudoNode = _.clone(object);
- copy_attribute(centroid, pseudoNode, 'lat');
- copy_attribute(centroid, pseudoNode, 'lon');
- pseudoNode.__is_center_placeholder = true;
- nodes.push(pseudoNode);
- }
- function boundsGeometry(object, bounds) {
- var pseudoWay = _.clone(object);
- pseudoWay.nodes = [];
- function addPseudoNode(lat,lon,i) {
- var pseudoNode = {
- type:"node",
- id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i,
- lat: lat,
- lon: lon
- }
- pseudoWay.nodes.push(pseudoNode.id);
- nodes.push(pseudoNode);
- }
- addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('minlon'),1);
- addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('minlon'),2);
- addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('maxlon'),3);
- addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('maxlon'),4);
- pseudoWay.nodes.push(pseudoWay.nodes[0]);
- pseudoWay.__is_bounds_placeholder = true;
- ways.push(pseudoWay);
- }
- function fullGeometryWay(way, nds) {
- function addFullGeometryNode(lat,lon,id) {
- var geometryNode = {
- type:"node",
- id: id,
- lat: lat,
- lon: lon
- }
- nodes.push(geometryNode);
- return geometryNode.id;
- }
- if (!_.isArray(way.nodes)) {
- way.nodes = [];
- _.each( nds, function( nd, i ) {
- way.nodes.push("_anonymous@"+nd.getAttribute('lat')+"/"+nd.getAttribute('lon'));
- });
- }
- _.each( nds, function( nd, i ) {
- if (nd.getAttribute('lat')) {
- addFullGeometryNode(
- nd.getAttribute('lat'),
- nd.getAttribute('lon'),
- way.nodes[i]
- );
- }
- });
- }
- function fullGeometryRelation(rel, members) {
- function addFullGeometryNode(lat,lon,id) {
- var geometryNode = {
- type:"node",
- id: id,
- lat: lat,
- lon: lon
- }
- nodes.push(geometryNode);
- }
- function addFullGeometryWay(nds,id) {
- // shared multipolygon ways cannot be defined multiple times with the same id.
- if (ways.some(function (way) { // todo: this is slow :(
- return way.type == "way" && way.id == id;
- })) return;
- var geometryWay = {
- type: "way",
- id: id,
- nodes:[]
- }
- function addFullGeometryWayPseudoNode(lat,lon) {
- // todo? do not save the same pseudo node multiple times
- var geometryPseudoNode = {
- type:"node",
- id: "_anonymous@"+lat+"/"+lon,
- lat: lat,
- lon: lon
- }
- geometryWay.nodes.push(geometryPseudoNode.id);
- nodes.push(geometryPseudoNode);
- }
- _.each(nds, function(nd) {
- if (nd.getAttribute('lat')) {
- addFullGeometryWayPseudoNode(
- nd.getAttribute('lat'),
- nd.getAttribute('lon')
- );
- } else {
- geometryWay.nodes.push(undefined);
- }
- });
- ways.push(geometryWay);
- }
- _.each( members, function( member, i ) {
- if (rel.members[i].type == "node") {
- if (member.getAttribute('lat')) {
- addFullGeometryNode(
- member.getAttribute('lat'),
- member.getAttribute('lon'),
- rel.members[i].ref
- );
- }
- } else if (rel.members[i].type == "way") {
- if (member.getElementsByTagName('nd').length > 0) {
- rel.members[i].ref = "_fullGeom"+rel.members[i].ref;
- addFullGeometryWay(
- member.getElementsByTagName('nd'),
- rel.members[i].ref
- );
- }
- }
- });
- }
- // nodes
- _.each( xml.getElementsByTagName('node'), function( node, i ) {
- var tags = {};
- _.each( node.getElementsByTagName('tag'), function( tag ) {
- tags[tag.getAttribute('k')] = tag.getAttribute('v');
- });
- var nodeObject = {
- 'type': 'node'
- };
- copy_attribute( node, nodeObject, 'id' );
- copy_attribute( node, nodeObject, 'lat' );
- copy_attribute( node, nodeObject, 'lon' );
- copy_attribute( node, nodeObject, 'version' );
- copy_attribute( node, nodeObject, 'timestamp' );
- copy_attribute( node, nodeObject, 'changeset' );
- copy_attribute( node, nodeObject, 'uid' );
- copy_attribute( node, nodeObject, 'user' );
- if (!_.isEmpty(tags))
- nodeObject.tags = tags;
- nodes.push(nodeObject);
- });
- // ways
- var centroid,bounds;
- _.each( xml.getElementsByTagName('way'), function( way, i ) {
- var tags = {};
- var wnodes = [];
- _.each( way.getElementsByTagName('tag'), function( tag ) {
- tags[tag.getAttribute('k')] = tag.getAttribute('v');
- });
- var has_full_geometry = false;
- _.each( way.getElementsByTagName('nd'), function( nd, i ) {
- var id;
- if (id = nd.getAttribute('ref'))
- wnodes[i] = id;
- if (!has_full_geometry && nd.getAttribute('lat'))
- has_full_geometry = true;
- });
- var wayObject = {
- "type": "way"
- };
- copy_attribute( way, wayObject, 'id' );
- copy_attribute( way, wayObject, 'version' );
- copy_attribute( way, wayObject, 'timestamp' );
- copy_attribute( way, wayObject, 'changeset' );
- copy_attribute( way, wayObject, 'uid' );
- copy_attribute( way, wayObject, 'user' );
- if (wnodes.length > 0)
- wayObject.nodes = wnodes;
- if (!_.isEmpty(tags))
- wayObject.tags = tags;
- if (centroid = way.getElementsByTagName('center')[0])
- centerGeometry(wayObject,centroid);
- if (has_full_geometry)
- fullGeometryWay(wayObject, way.getElementsByTagName('nd'));
- else if (bounds = way.getElementsByTagName('bounds')[0])
- boundsGeometry(wayObject,bounds);
- ways.push(wayObject);
- });
- // relations
- _.each( xml.getElementsByTagName('relation'), function( relation, i ) {
- var tags = {};
- var members = [];
- _.each( relation.getElementsByTagName('tag'), function( tag ) {
- tags[tag.getAttribute('k')] = tag.getAttribute('v');
- });
- var has_full_geometry = false;
- _.each( relation.getElementsByTagName('member'), function( member, i ) {
- members[i] = {};
- copy_attribute( member, members[i], 'ref' );
- copy_attribute( member, members[i], 'role' );
- copy_attribute( member, members[i], 'type' );
- if (!has_full_geometry &&
- (members[i].type == 'node' && member.getAttribute('lat')) ||
- (members[i].type == 'way' && member.getElementsByTagName('nd').length>0) )
- has_full_geometry = true;
- });
- var relObject = {
- "type": "relation"
- }
- copy_attribute( relation, relObject, 'id' );
- copy_attribute( relation, relObject, 'version' );
- copy_attribute( relation, relObject, 'timestamp' );
- copy_attribute( relation, relObject, 'changeset' );
- copy_attribute( relation, relObject, 'uid' );
- copy_attribute( relation, relObject, 'user' );
- if (members.length > 0)
- relObject.members = members;
- if (!_.isEmpty(tags))
- relObject.tags = tags;
- if (centroid = relation.getElementsByTagName('center')[0])
- centerGeometry(relObject,centroid);
- if (has_full_geometry)
- fullGeometryRelation(relObject, relation.getElementsByTagName('member'));
- else if (bounds = relation.getElementsByTagName('bounds')[0])
- boundsGeometry(relObject,bounds);
- rels.push(relObject);
- });
- return _convert2geoJSON(nodes,ways,rels);
- }
- function _convert2geoJSON(nodes,ways,rels) {
- // helper function that checks if there are any tags other than "created_by", "source", etc. or any tag provided in ignore_tags
- function has_interesting_tags(t, ignore_tags) {
- if (typeof ignore_tags !== "object")
- ignore_tags={};
- if (typeof options.uninterestingTags === "function")
- return !options.uninterestingTags(t, ignore_tags);
- for (var k in t)
- if (!(options.uninterestingTags[k]===true) &&
- !(ignore_tags[k]===true || ignore_tags[k]===t[k]))
- return true;
- return false;
- };
- // helper function to extract meta information
- function build_meta_information(object) {
- var res = {
- "timestamp": object.timestamp,
- "version": object.version,
- "changeset": object.changeset,
- "user": object.user,
- "uid": object.uid
- };
- for (var k in res)
- if (res[k] === undefined)
- delete res[k];
- return res;
- }
- // some data processing (e.g. filter nodes only used for ways)
- var nodeids = new Object();
- var poinids = new Object();
- for (var i=0;i<nodes.length;i++) {
- var node = nodes[i];
- if (nodeids[node.id] !== undefined) {
- // handle input data duplication
- node = options.deduplicator(node, nodeids[node.id]);
- }
- nodeids[node.id] = node;
- if (typeof node.tags != 'undefined' &&
- has_interesting_tags(node.tags)) // this checks if the node has any tags other than "created_by"
- poinids[node.id] = true;
- }
- // todo -> after deduplication of relations??
- for (var i=0;i<rels.length;i++) {
- if (_.isArray(rels[i].members)) {
- for (var j=0;j<rels[i].members.length;j++) {
- if (rels[i].members[j].type == "node")
- poinids[rels[i].members[j].ref] = true;
- }
- }
- }
- var wayids = new Object();
- var waynids = new Object();
- for (var i=0;i<ways.length;i++) {
- var way = ways[i];
- if (wayids[way.id]) {
- // handle input data duplication
- way = options.deduplicator(way, wayids[way.id]);
- }
- wayids[way.id] = way;
- if (_.isArray(way.nodes)) {
- for (var j=0;j<way.nodes.length;j++) {
- if (typeof way.nodes[j] === "object") continue; // ignore already replaced way node objects
- waynids[way.nodes[j]] = true;
- way.nodes[j] = nodeids[way.nodes[j]];
- }
- }
- }
- var pois = new Array();
- for (var id in nodeids) {
- var node = nodeids[id];
- if (!waynids[id] || poinids[id])
- pois.push(node);
- }
- var relids = new Array();
- for (var i=0;i<rels.length;i++) {
- var rel = rels[i];
- if (relids[rel.id]) {
- // handle input data duplication
- rel = options.deduplicator(rel, relids[rel.id]);
- }
- relids[rel.id] = rel;
- }
- var relsmap = {node: {}, way: {}, relation: {}};
- for (var id in relids) {
- var rel = relids[id];
- if (!_.isArray(rel.members)) {
- if (options.verbose) console.warn('Relation',rel.type+'/'+rel.id,'ignored because it has no members');
- continue; // ignore relations without members (e.g. returned by an ids_only query)
- }
- for (var j=0;j<rel.members.length;j++) {
- var m_type = rel.members[j].type;
- var m_ref = rel.members[j].ref;
- if (typeof m_ref !== "number") {
- // de-namespace full geometry content
- m_ref = m_ref.replace("_fullGeom", "");
- }
- if (!relsmap[m_type]) {
- if (options.verbose) console.warn('Relation',rel.type+'/'+rel.id,'member',m_type+'/'+m_ref,'ignored because it has an invalid type');
- continue;
- }
- if (typeof relsmap[m_type][m_ref] === "undefined")
- relsmap[m_type][m_ref] = [];
- relsmap[m_type][m_ref].push({
- "role" : rel.members[j].role,
- "rel" : rel.id,
- "reltags" : rel.tags,
- });
- }
- }
- // construct geojson
- var geojson;
- var geojsonnodes = [];
- for (i=0;i<pois.length;i++) {
- if (typeof pois[i].lon == "undefined" || typeof pois[i].lat == "undefined") {
- if (options.verbose) console.warn('POI',pois[i].type+'/'+pois[i].id,'ignored because it lacks coordinates');
- continue; // lon and lat are required for showing a point
- }
- var feature = {
- "type" : "Feature",
- "id" : pois[i].type+"/"+pois[i].id,
- "properties" : {
- "type" : pois[i].type,
- "id" : pois[i].id,
- "tags" : pois[i].tags || {},
- "relations" : relsmap["node"][pois[i].id] || [],
- "meta": build_meta_information(pois[i])
- },
- "geometry" : {
- "type" : "Point",
- "coordinates" : [+pois[i].lon, +pois[i].lat],
- }
- };
- if (pois[i].__is_center_placeholder)
- feature.properties["geometry"] = "center";
- if (!featureCallback)
- geojsonnodes.push(feature);
- else
- featureCallback(feature);
- }
- var geojsonlines = [];
- var geojsonpolygons = [];
- // process multipolygons
- for (var i=0;i<rels.length;i++) {
- // todo: refactor such that this loops over relids instead of rels?
- if (relids[rels[i].id] !== rels[i]) {
- // skip relation because it's a deduplication artifact
- continue;
- }
- if ((typeof rels[i].tags != "undefined") &&
- (rels[i].tags["type"] == "route" || rels[i].tags["type"] == "waterway")) {
- if (!_.isArray(rels[i].members)) {
- if (options.verbose) console.warn('Route',rels[i].type+'/'+rels[i].id,'ignored because it has no members');
- continue; // ignore relations without members (e.g. returned by an ids_only query)
- }
- rels[i].members.forEach(function(m) {
- if (wayids[m.ref] && !has_interesting_tags(wayids[m.ref].tags))
- wayids[m.ref].is_skippablerelationmember = true;
- });
- feature = construct_multilinestring(rels[i]);
- if (feature === false) {
- if (options.verbose) console.warn('Route relation',rels[i].type+'/'+rels[i].id,'ignored because it has invalid geometry');
- continue; // abort if feature could not be constructed
- }
- if (!featureCallback)
- geojsonpolygons.push(feature);
- else
- featureCallback(rewind(feature));
- function construct_multilinestring(rel) {
- var is_tainted = false;
- // prepare route members
- var members;
- members = rel.members.filter(function(m) {return m.type === "way";});
- members = members.map(function(m) {
- var way = wayids[m.ref];
- if (way === undefined || way.nodes === undefined) { // check for missing ways
- if (options.verbose) console.warn('Route '+rel.type+'/'+rel.id, 'tainted by a missing or incomplete way', m.type+'/'+m.ref);
- is_tainted = true;
- return;
- }
- return { // TODO: this is slow! :(
- id: m.ref,
- role: m.role,
- way: way,
- nodes: way.nodes.filter(function(n) {
- if (n !== undefined)
- return true;
- is_tainted = true;
- if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'tainted by a way', m.type+'/'+m.ref, 'with a missing node');
- return false;
- })
- };
- });
- members = _.compact(members);
- // construct connected linestrings
- var linestrings;
- linestrings = join(members);
- // sanitize mp-coordinates (remove empty clusters or rings, {lat,lon,...} to [lon,lat]
- var coords = [];
- coords = _.compact(linestrings.map(function(linestring) {
- return _.compact(linestring.map(function(node) {
- return [+node.lon,+node.lat];
- }));
- }));
- if (coords.length == 0) {
- if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'contains no coordinates');
- return false; // ignore routes without coordinates
- }
- // mp parsed, now construct the geoJSON
- var feature = {
- "type" : "Feature",
- "id" : rel.type+"/"+rel.id,
- "properties" : {
- "type" : rel.type,
- "id" : rel.id,
- "tags" : rel.tags || {},
- "relations" : relsmap[rel.type][rel.id] || [],
- "meta": build_meta_information(rel)
- },
- "geometry" : {
- "type" : coords.length === 1 ? "LineString" : "MultiLineString",
- "coordinates" : coords.length === 1 ? coords[0] : coords,
- }
- }
- if (is_tainted) {
- if (options.verbose) console.warn('Route', rel.type+'/'+rel.id, 'is tainted');
- feature.properties["tainted"] = true;
- }
- return feature;
- }
- } // end construct multilinestring for route relations
- if ((typeof rels[i].tags != "undefined") &&
- (rels[i].tags["type"] == "multipolygon" || rels[i].tags["type"] == "boundary")) {
- if (!_.isArray(rels[i].members)) {
- if (options.verbose) console.warn('Multipolygon',rels[i].type+'/'+rels[i].id,'ignored because it has no members');
- continue; // ignore relations without members (e.g. returned by an ids_only query)
- }
- var outer_count = 0;
- for (var j=0;j<rels[i].members.length;j++)
- if (rels[i].members[j].role == "outer")
- outer_count++;
- else if (options.verbose && rels[i].members[j].role != "inner")
- console.warn('Multipolygon',rels[i].type+'/'+rels[i].id,'member',rels[i].members[j].type+'/'+rels[i].members[j].ref,'ignored because it has an invalid role: "' + rels[i].members[j].role + '"');
- rels[i].members.forEach(function(m) {
- if (wayids[m.ref]) {
- // this even works in the following corner case:
- // a multipolygon amenity=xxx with outer line tagged amenity=yyy
- // see https://github.com/tyrasd/osmtogeojson/issues/7
- if (m.role==="outer" && !has_interesting_tags(wayids[m.ref].tags,rels[i].tags))
- wayids[m.ref].is_skippablerelationmember = true;
- if (m.role==="inner" && !has_interesting_tags(wayids[m.ref].tags))
- wayids[m.ref].is_skippablerelationmember = true;
- }
- });
- if (outer_count == 0) {
- if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because it has no outer ways');
- continue; // ignore multipolygons without outer ways
- }
- var simple_mp = false;
- if (outer_count == 1 && !has_interesting_tags(rels[i].tags, {"type":true}))
- simple_mp = true;
- var feature = null;
- if (!simple_mp) {
- feature = construct_multipolygon(rels[i], rels[i]);
- } else {
- // simple multipolygon
- var outer_way = rels[i].members.filter(function(m) {return m.role === "outer";})[0];
- outer_way = wayids[outer_way.ref];
- if (outer_way === undefined) {
- if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because outer way', outer_way.type+'/'+outer_way.ref,'is missing');
- continue; // abort if outer way object is not present
- }
- outer_way.is_skippablerelationmember = true;
- feature = construct_multipolygon(outer_way, rels[i]);
- }
- if (feature === false) {
- if (options.verbose) console.warn('Multipolygon relation',rels[i].type+'/'+rels[i].id,'ignored because it has invalid geometry');
- continue; // abort if feature could not be constructed
- }
- if (!featureCallback)
- geojsonpolygons.push(feature);
- else
- featureCallback(rewind(feature));
- function construct_multipolygon(tag_object, rel) {
- var is_tainted = false;
- var mp_geometry = simple_mp ? 'way' : 'relation',
- mp_id = typeof tag_object.id === "number" ? tag_object.id : +(tag_object.id.replace("_fullGeom", ""));
- // prepare mp members
- var members;
- members = rel.members.filter(function(m) {return m.type === "way";});
- members = members.map(function(m) {
- var way = wayids[m.ref];
- if (way === undefined || way.nodes === undefined) { // check for missing ways
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'tainted by a missing or incomplete way', m.type+'/'+m.ref);
- is_tainted = true;
- return;
- }
- return { // TODO: this is slow! :(
- id: m.ref,
- role: m.role || "outer",
- way: way,
- nodes: way.nodes.filter(function(n) {
- if (n !== undefined)
- return true;
- is_tainted = true;
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'tainted by a way', m.type+'/'+m.ref, 'with a missing node');
- return false;
- })
- };
- });
- members = _.compact(members);
- // construct outer and inner rings
- var outers, inners;
- outers = join(members.filter(function(m) {return m.role==="outer";}));
- inners = join(members.filter(function(m) {return m.role==="inner";}));
- // sort rings
- var mp;
- function findOuter(inner) {
- var polygonIntersectsPolygon = function(outer, inner) {
- for (var i=0; i<inner.length; i++)
- if (pointInPolygon(inner[i], outer))
- return true;
- return false;
- }
- var mapCoordinates = function(from) {
- return from.map(function(n) {
- return [+n.lat,+n.lon];
- });
- }
- // stolen from iD/geo.js,
- // based on https://github.com/substack/point-in-polygon,
- // ray-casting algorithm based on http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
- var pointInPolygon = function(point, polygon) {
- var x = point[0], y = point[1], inside = false;
- for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
- var xi = polygon[i][0], yi = polygon[i][1];
- var xj = polygon[j][0], yj = polygon[j][1];
- var intersect = ((yi > y) != (yj > y)) &&
- (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
- if (intersect) inside = !inside;
- }
- return inside;
- };
- // stolen from iD/relation.js
- var o, outer;
- // todo: all this coordinate mapping makes this unneccesarily slow.
- // see the "todo: this is slow! :(" above.
- inner = mapCoordinates(inner);
- /*for (o = 0; o < outers.length; o++) {
- outer = mapCoordinates(outers[o]);
- if (polygonContainsPolygon(outer, inner))
- return o;
- }*/
- for (o = 0; o < outers.length; o++) {
- outer = mapCoordinates(outers[o]);
- if (polygonIntersectsPolygon(outer, inner))
- return o;
- }
- }
- mp = outers.map(function(o) {return [o];});
- for (var j=0; j<inners.length; j++) {
- var o = findOuter(inners[j]);
- if (o !== undefined)
- mp[o].push(inners[j]);
- else
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains an inner ring with no containing outer');
- // so, no outer ring for this inner ring is found.
- // We're going to ignore holes in empty space.
- ;
- }
- // sanitize mp-coordinates (remove empty clusters or rings, {lat,lon,...} to [lon,lat]
- var mp_coords = [];
- mp_coords = _.compact(mp.map(function(cluster) {
- var cl = _.compact(cluster.map(function(ring) {
- if (ring.length < 4) { // todo: is this correct: ring.length < 4 ?
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains a ring with less than four nodes');
- return;
- }
- return _.compact(ring.map(function(node) {
- return [+node.lon,+node.lat];
- }));
- }));
- if (cl.length == 0) {
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains an empty ring cluster');
- return;
- }
- return cl;
- }));
- if (mp_coords.length == 0) {
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'contains no coordinates');
- return false; // ignore multipolygons without coordinates
- }
- var mp_type = "MultiPolygon";
- if (mp_coords.length === 1) {
- mp_type = "Polygon";
- mp_coords = mp_coords[0];
- }
- // mp parsed, now construct the geoJSON
- var feature = {
- "type" : "Feature",
- "id" : tag_object.type+"/"+mp_id,
- "properties" : {
- "type" : tag_object.type,
- "id" : mp_id,
- "tags" : tag_object.tags || {},
- "relations" : relsmap[tag_object.type][tag_object.id] || [],
- "meta": build_meta_information(tag_object)
- },
- "geometry" : {
- "type" : mp_type,
- "coordinates" : mp_coords,
- }
- }
- if (is_tainted) {
- if (options.verbose) console.warn('Multipolygon', mp_geometry+'/'+mp_id, 'is tainted');
- feature.properties["tainted"] = true;
- }
- return feature;
- }
- }
- }
- // process lines and polygons
- for (var i=0;i<ways.length;i++) {
- // todo: refactor such that this loops over wayids instead of ways?
- if (wayids[ways[i].id] !== ways[i]) {
- // skip way because it's a deduplication artifact
- continue;
- }
- if (!_.isArray(ways[i].nodes)) {
- if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'ignored because it has no nodes');
- continue; // ignore ways without nodes (e.g. returned by an ids_only query)
- }
- if (ways[i].is_skippablerelationmember)
- continue; // ignore ways which are already rendered as (part of) a multipolygon
- if (typeof ways[i].id !== "number") {
- // remove full geometry namespace for output
- ways[i].id = +ways[i].id.replace("_fullGeom", "");
- }
- ways[i].tainted = false;
- ways[i].hidden = false;
- var coords = new Array();
- for (j=0;j<ways[i].nodes.length;j++) {
- if (typeof ways[i].nodes[j] == "object")
- coords.push([+ways[i].nodes[j].lon, +ways[i].nodes[j].lat]);
- else {
- if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'is tainted by an invalid node');
- ways[i].tainted = true;
- }
- }
- if (coords.length <= 1) { // invalid way geometry
- if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'ignored because it contains too few nodes');
- continue;
- }
- var way_type = "LineString"; // default
- if (typeof ways[i].nodes[0] != "undefined" && typeof ways[i].nodes[ways[i].nodes.length-1] != "undefined" && // way has its start/end nodes loaded
- ways[i].nodes[0].id === ways[i].nodes[ways[i].nodes.length-1].id && // ... and forms a closed ring
- (
- typeof ways[i].tags != "undefined" && // ... and has tags
- _isPolygonFeature(ways[i].tags) // ... and tags say it is a polygon
- || // or is a placeholder for a bounds geometry
- ways[i].__is_bounds_placeholder
- )
- ) {
- way_type = "Polygon";
- coords = [coords];
- }
- var feature = {
- "type" : "Feature",
- "id" : ways[i].type+"/"+ways[i].id,
- "properties" : {
- "type" : ways[i].type,
- "id" : ways[i].id,
- "tags" : ways[i].tags || {},
- "relations" : relsmap["way"][ways[i].id] || [],
- "meta": build_meta_information(ways[i])
- },
- "geometry" : {
- "type" : way_type,
- "coordinates" : coords,
- }
- }
- if (ways[i].tainted) {
- if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'is tainted');
- feature.properties["tainted"] = true;
- }
- if (ways[i].__is_bounds_placeholder)
- feature.properties["geometry"] = "bounds";
- if (!featureCallback) {
- if (way_type == "LineString")
- geojsonlines.push(feature);
- else
- geojsonpolygons.push(feature);
- } else {
- featureCallback(rewind(feature));
- }
- }
- if (featureCallback)
- return true;
- geojson = {
- "type": "FeatureCollection",
- "features": []
- };
- geojson.features = geojson.features.concat(geojsonpolygons);
- geojson.features = geojson.features.concat(geojsonlines);
- geojson.features = geojson.features.concat(geojsonnodes);
- // optionally, flatten properties
- if (options.flatProperties) {
- geojson.features.forEach(function(f) {
- f.properties = _.merge(
- f.properties.meta,
- f.properties.tags,
- {id: f.properties.type+"/"+f.properties.id}
- );
- });
- }
- // fix polygon winding
- geojson = rewind(geojson);
- return geojson;
- }
- function _isPolygonFeature( tags ) {
- var polygonFeatures = options.polygonFeatures;
- if (typeof polygonFeatures === "function")
- return polygonFeatures(tags);
- // explicitely tagged non-areas
- if ( tags['area'] === 'no' )
- return false;
- // assuming that a typical OSM way has in average less tags than
- // the polygonFeatures list, this way around should be faster
- for ( var key in tags ) {
- var val = tags[key];
- var pfk = polygonFeatures[key];
- // continue with next if tag is unknown or not "categorizing"
- if ( typeof pfk === 'undefined' )
- continue;
- // continue with next if tag is explicitely un-set ("building=no")
- if ( val === 'no' )
- continue;
- // check polygon features for: general acceptance, included or excluded values
- if ( pfk === true )
- return true;
- if ( pfk.included_values && pfk.included_values[val] === true )
- return true;
- if ( pfk.excluded_values && pfk.excluded_values[val] !== true )
- return true;
- }
- // if no tags matched, this ain't no area.
- return false;
- }
- };
- // helper that joins adjacent osm ways into linestrings or linear rings
- function join(ways) {
- var _first = function(arr) {return arr[0]};
- var _last = function(arr) {return arr[arr.length-1]};
- var _fitTogether = function(n1, n2) {
- return n1 !== undefined && n2 !== undefined && n1.id === n2.id;
- }
- // stolen from iD/relation.js
- var joined = [], current, first, last, i, how, what;
- while (ways.length) {
- current = ways.pop().nodes.slice();
- joined.push(current);
- while (ways.length && !_fitTogether(_first(current), _last(current))) {
- first = _first(current);
- last = _last(current);
- for (i = 0; i < ways.length; i++) {
- what = ways[i].nodes;
- if (_fitTogether(last, _first(what))) {
- how = current.push;
- what = what.slice(1);
- break;
- } else if (_fitTogether(last, _last(what))) {
- how = current.push;
- what = what.slice(0, -1).reverse();
- break;
- } else if (_fitTogether(first, _last(what))) {
- how = current.unshift;
- what = what.slice(0, -1);
- break;
- } else if (_fitTogether(first, _first(what))) {
- how = current.unshift;
- what = what.slice(1).reverse();
- break;
- } else {
- what = how = null;
- }
- }
- if (!what)
- break; // Invalid geometry (dangling way, unclosed ring)
- ways.splice(i, 1);
- how.apply(current, what);
- }
- }
- return joined;
- }
- // for backwards compatibility
- osmtogeojson.toGeojson = osmtogeojson;
- module.exports = osmtogeojson;
- },{"./lodash.custom.js":178,"geojson-rewind":45,"osm-polygon-features":175}],178:[function(require,module,exports){
- (function (global){
- /**
- * @license
- * lodash (Custom Build) <https://lodash.com/>
- * Build: `lodash exports="node" include="clone,merge,isEmpty,isArray,compact,each" -d`
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
- * Released under MIT license <https://lodash.com/license>
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
- ;(function() {
- /** Used as a safe reference for `undefined` in pre-ES5 environments. */
- var undefined;
- /** Used as the semantic version number. */
- var VERSION = '4.15.0';
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE = 200;
- /** Used as the `TypeError` message for "Functions" methods. */
- var FUNC_ERROR_TEXT = 'Expected a function';
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
- /** Used to compose bitmasks for comparison styles. */
- var UNORDERED_COMPARE_FLAG = 1,
- PARTIAL_COMPARE_FLAG = 2;
- /** Used as references for various `Number` constants. */
- var INFINITY = 1 / 0,
- MAX_SAFE_INTEGER = 9007199254740991;
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]',
- arrayTag = '[object Array]',
- boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- objectTag = '[object Object]',
- promiseTag = '[object Promise]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- symbolTag = '[object Symbol]',
- weakMapTag = '[object WeakMap]';
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[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 match property names within property paths. */
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
- reIsPlainProp = /^\w*$/,
- reLeadingDot = /^\./,
- rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
- /**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
- /** Used to match backslashes in property paths. */
- var reEscapeChar = /\\(\\)?/g;
- /** Used to match `RegExp` flags from their coerced string values. */
- var reFlags = /\w*$/;
- /** Used to detect host constructors (Safari). */
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
- /** Used to detect unsigned integer values. */
- var reIsUint = /^(?:0|[1-9]\d*)$/;
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
- typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
- typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
- typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
- typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
- typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
- typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
- typedArrayTags[errorTag] = typedArrayTags[funcTag] =
- typedArrayTags[mapTag] = typedArrayTags[numberTag] =
- typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
- typedArrayTags[setTag] = typedArrayTags[stringTag] =
- typedArrayTags[weakMapTag] = false;
- /** Used to identify `toStringTag` values supported by `_.clone`. */
- var cloneableTags = {};
- cloneableTags[argsTag] = cloneableTags[arrayTag] =
- cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
- cloneableTags[boolTag] = cloneableTags[dateTag] =
- cloneableTags[float32Tag] = cloneableTags[float64Tag] =
- cloneableTags[int8Tag] = cloneableTags[int16Tag] =
- cloneableTags[int32Tag] = cloneableTags[mapTag] =
- cloneableTags[numberTag] = cloneableTags[objectTag] =
- cloneableTags[regexpTag] = cloneableTags[setTag] =
- cloneableTags[stringTag] = cloneableTags[symbolTag] =
- cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
- cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
- cloneableTags[errorTag] = cloneableTags[funcTag] =
- cloneableTags[weakMapTag] = false;
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
- /** 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')();
- /** Detect free variable `exports`. */
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && typeof module == '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 {
- return freeProcess && freeProcess.binding('util');
- } catch (e) {}
- }());
- /* Node.js helper references. */
- var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
- /*--------------------------------------------------------------------------*/
- /**
- * Adds the key-value `pair` to `map`.
- *
- * @private
- * @param {Object} map The map to modify.
- * @param {Array} pair The key-value pair to add.
- * @returns {Object} Returns `map`.
- */
- function addMapEntry(map, pair) {
- // Don't return `map.set` because it's not chainable in IE 11.
- map.set(pair[0], pair[1]);
- return map;
- }
- /**
- * Adds `value` to `set`.
- *
- * @private
- * @param {Object} set The set to modify.
- * @param {*} value The value to add.
- * @returns {Object} Returns `set`.
- */
- function addSetEntry(set, value) {
- // Don't return `set.add` because it's not chainable in IE 11.
- set.add(value);
- return set;
- }
- /**
- * 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);
- }
- /**
- * 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 ? array.length : 0;
- while (++index < length) {
- if (iteratee(array[index], index, array) === false) {
- break;
- }
- }
- return array;
- }
- /**
- * 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;
- }
- /**
- * A specialized version of `_.reduce` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {*} [accumulator] The initial value.
- * @param {boolean} [initAccum] Specify using the first element of `array` as
- * the initial value.
- * @returns {*} Returns the accumulated value.
- */
- function arrayReduce(array, iteratee, accumulator, initAccum) {
- var index = -1,
- length = array ? array.length : 0;
- if (initAccum && length) {
- accumulator = array[++index];
- }
- while (++index < length) {
- accumulator = iteratee(accumulator, array[index], index, array);
- }
- return accumulator;
- }
- /**
- * 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 ? array.length : 0;
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 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];
- };
- }
- /**
- * 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;
- }
- /**
- * 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);
- };
- }
- /**
- * 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];
- }
- /**
- * Checks if `value` is a host object in IE < 9.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
- */
- function isHostObject(value) {
- // Many host objects are `Object` objects that can coerce to strings
- // despite having improperly defined `toString` methods.
- var result = false;
- if (value != null && typeof value.toString != 'function') {
- try {
- result = !!(value + '');
- } catch (e) {}
- }
- return result;
- }
- /**
- * 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;
- }
- /**
- * 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));
- };
- }
- /**
- * 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;
- }
- /*--------------------------------------------------------------------------*/
- /** Used for built-in method references. */
- var arrayProto = Array.prototype,
- funcProto = Function.prototype,
- objectProto = Object.prototype;
- /** Used to detect overreaching core-js shims. */
- var coreJsData = root['__core-js_shared__'];
- /** 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) : '';
- }());
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /** Used to infer the `Object` constructor. */
- var objectCtorString = funcToString.call(Object);
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var objectToString = objectProto.toString;
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' +
- funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
- );
- /** Built-in value references. */
- var Buffer = moduleExports ? root.Buffer : undefined,
- Symbol = root.Symbol,
- Uint8Array = root.Uint8Array,
- getPrototype = overArg(Object.getPrototypeOf, Object),
- objectCreate = Object.create,
- propertyIsEnumerable = objectProto.propertyIsEnumerable,
- splice = arrayProto.splice;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols = Object.getOwnPropertySymbols,
- nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
- nativeKeys = overArg(Object.keys, Object),
- nativeMax = Math.max;
- /* Built-in method references that are verified to be native. */
- var DataView = getNative(root, 'DataView'),
- Map = getNative(root, 'Map'),
- Promise = getNative(root, 'Promise'),
- Set = getNative(root, 'Set'),
- WeakMap = getNative(root, 'WeakMap'),
- nativeCreate = getNative(Object, 'create');
- /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
- var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
- /** Used to lookup unminified function names. */
- var realNames = {};
- /** Used to detect maps, sets, and weakmaps. */
- var dataViewCtorString = toSource(DataView),
- mapCtorString = toSource(Map),
- promiseCtorString = toSource(Promise),
- setCtorString = toSource(Set),
- weakMapCtorString = toSource(WeakMap);
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = Symbol ? Symbol.prototype : undefined,
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
- symbolToString = symbolProto ? symbolProto.toString : undefined;
- /*------------------------------------------------------------------------*/
- /**
- * 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 of at least `200` elements
- * and any 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() {
- // No operation performed.
- }
- /*------------------------------------------------------------------------*/
- /**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Hash(entries) {
- var index = -1,
- length = entries ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
- }
- /**
- * 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) {
- return this.has(key) && delete this.__data__[key];
- }
- /**
- * 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 ? undefined : result;
- }
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
- }
- /**
- * 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.call(data, key);
- }
- /**
- * 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__;
- data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
- return this;
- }
- // Add methods to `Hash`.
- Hash.prototype.clear = hashClear;
- Hash.prototype['delete'] = hashDelete;
- Hash.prototype.get = hashGet;
- Hash.prototype.has = hashHas;
- Hash.prototype.set = hashSet;
- /*------------------------------------------------------------------------*/
- /**
- * Creates an list cache object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function ListCache(entries) {
- var index = -1,
- length = entries ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- }
- /**
- * 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);
- }
- return true;
- }
- /**
- * 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];
- }
- /**
- * 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;
- }
- /**
- * 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) {
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
- return this;
- }
- // Add methods to `ListCache`.
- ListCache.prototype.clear = listCacheClear;
- ListCache.prototype['delete'] = listCacheDelete;
- ListCache.prototype.get = listCacheGet;
- ListCache.prototype.has = listCacheHas;
- ListCache.prototype.set = listCacheSet;
- /*------------------------------------------------------------------------*/
- /**
- * 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 ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
- function mapCacheClear() {
- this.__data__ = {
- 'hash': new Hash,
- 'map': new (Map || ListCache),
- 'string': new Hash
- };
- }
- /**
- * 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) {
- return getMapData(this, key)['delete'](key);
- }
- /**
- * 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);
- }
- /**
- * 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);
- }
- /**
- * 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) {
- getMapData(this, key).set(key, value);
- return this;
- }
- // Add methods to `MapCache`.
- MapCache.prototype.clear = mapCacheClear;
- MapCache.prototype['delete'] = mapCacheDelete;
- MapCache.prototype.get = mapCacheGet;
- MapCache.prototype.has = mapCacheHas;
- MapCache.prototype.set = mapCacheSet;
- /*------------------------------------------------------------------------*/
- /**
- *
- * 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 ? values.length : 0;
- this.__data__ = new MapCache;
- while (++index < length) {
- this.add(values[index]);
- }
- }
- /**
- * 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;
- }
- /**
- * 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);
- }
- // Add methods to `SetCache`.
- SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
- SetCache.prototype.has = setCacheHas;
- /*------------------------------------------------------------------------*/
- /**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Stack(entries) {
- this.__data__ = new ListCache(entries);
- }
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new ListCache;
- }
- /**
- * 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) {
- return this.__data__['delete'](key);
- }
- /**
- * 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);
- }
- /**
- * 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);
- }
- /**
- * 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 cache = this.__data__;
- if (cache instanceof ListCache) {
- var pairs = cache.__data__;
- if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
- pairs.push([key, value]);
- return this;
- }
- cache = this.__data__ = new MapCache(pairs);
- }
- cache.set(key, value);
- return this;
- }
- // Add methods to `Stack`.
- Stack.prototype.clear = stackClear;
- Stack.prototype['delete'] = stackDelete;
- Stack.prototype.get = stackGet;
- Stack.prototype.has = stackHas;
- Stack.prototype.set = stackSet;
- /*------------------------------------------------------------------------*/
- /**
- * 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) {
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
- // Safari 9 makes `arguments.length` enumerable in strict mode.
- var result = (isArray(value) || isArguments(value))
- ? baseTimes(value.length, String)
- : [];
- var length = result.length,
- skipIndexes = !!length;
- for (var key in value) {
- if ((inherited || hasOwnProperty.call(value, key)) &&
- !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * This function is like `assignValue` except that it doesn't assign
- * `undefined` values.
- *
- * @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 assignMergeValue(object, key, value) {
- if ((value !== undefined && !eq(object[key], value)) ||
- (typeof key == 'number' && value === undefined && !(key in object))) {
- object[key] = value;
- }
- }
- /**
- * 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.call(object, key) && eq(objValue, value)) ||
- (value === undefined && !(key in object))) {
- object[key] = value;
- }
- }
- /**
- * 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(array[length][0], key)) {
- return length;
- }
- }
- return -1;
- }
- /**
- * 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(source), object);
- }
- /**
- * The base implementation of `_.clone` and `_.cloneDeep` which tracks
- * traversed objects.
- *
- * @private
- * @param {*} value The value to clone.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @param {boolean} [isFull] Specify a clone including 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, isDeep, isFull, customizer, key, object, stack) {
- var result;
- if (customizer) {
- result = object ? customizer(value, key, object, stack) : customizer(value);
- }
- if (result !== undefined) {
- return result;
- }
- if (!isObject(value)) {
- return value;
- }
- var isArr = isArray(value);
- if (isArr) {
- result = initCloneArray(value);
- if (!isDeep) {
- return copyArray(value, result);
- }
- } else {
- var tag = getTag(value),
- isFunc = tag == funcTag || tag == genTag;
- if (isBuffer(value)) {
- return cloneBuffer(value, isDeep);
- }
- if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
- if (isHostObject(value)) {
- return object ? value : {};
- }
- result = initCloneObject(isFunc ? {} : value);
- if (!isDeep) {
- return copySymbols(value, baseAssign(result, value));
- }
- } else {
- if (!cloneableTags[tag]) {
- return object ? value : {};
- }
- result = initCloneByTag(value, tag, baseClone, 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 (!isArr) {
- var props = isFull ? getAllKeys(value) : keys(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, isDeep, isFull, customizer, key, value, stack));
- });
- return result;
- }
- /**
- * The base implementation of `_.create` without support for assigning
- * properties to the created object.
- *
- * @private
- * @param {Object} prototype The object to inherit from.
- * @returns {Object} Returns the new object.
- */
- function baseCreate(proto) {
- return isObject(proto) ? objectCreate(proto) : {};
- }
- /**
- * The base implementation of `_.forEach` without support for iteratee shorthands.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- */
- var baseEach = createBaseEach(baseForOwn);
- /**
- * The base implementation of `baseForOwn` which iterates over `object`
- * properties returned by `keysFunc` and invokes `iteratee` for each property.
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
- var baseFor = createBaseFor();
- /**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
- function baseForOwn(object, iteratee) {
- return object && baseFor(object, iteratee, keys);
- }
- /**
- * 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 = isKey(path, object) ? [path] : castPath(path);
- var index = 0,
- length = path.length;
- while (object != null && index < length) {
- object = object[toKey(path[index++])];
- }
- return (index && index == length) ? object : undefined;
- }
- /**
- * 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(object) ? result : arrayPush(result, symbolsFunc(object));
- }
- /**
- * The base implementation of `getTag`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- function baseGetTag(value) {
- return objectToString.call(value);
- }
- /**
- * 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);
- }
- /**
- * 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 {Function} [customizer] The function to customize comparisons.
- * @param {boolean} [bitmask] The bitmask of comparison flags.
- * The bitmask may be composed of the following flags:
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
- function baseIsEqual(value, other, customizer, bitmask, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
- return value !== value && other !== other;
- }
- return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
- }
- /**
- * 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 {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
- var objIsArr = isArray(object),
- othIsArr = isArray(other),
- objTag = arrayTag,
- othTag = arrayTag;
- if (!objIsArr) {
- objTag = getTag(object);
- objTag = objTag == argsTag ? objectTag : objTag;
- }
- if (!othIsArr) {
- othTag = getTag(other);
- othTag = othTag == argsTag ? objectTag : othTag;
- }
- var objIsObj = objTag == objectTag && !isHostObject(object),
- othIsObj = othTag == objectTag && !isHostObject(other),
- isSameTag = objTag == othTag;
- if (isSameTag && !objIsObj) {
- stack || (stack = new Stack);
- return (objIsArr || isTypedArray(object))
- ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
- : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
- }
- if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
- 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, customizer, bitmask, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new Stack);
- return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
- }
- /**
- * 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, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
- : result
- )) {
- return false;
- }
- }
- }
- return true;
- }
- /**
- * 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(value) || isMasked(value)) {
- return false;
- }
- var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
- return pattern.test(toSource(value));
- }
- /**
- * 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(value) &&
- isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
- }
- /**
- * 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;
- }
- if (typeof value == 'object') {
- return isArray(value)
- ? baseMatchesProperty(value[0], value[1])
- : baseMatches(value);
- }
- return property(value);
- }
- /**
- * 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.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * 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(object)) {
- return nativeKeysIn(object);
- }
- var isProto = isPrototype(object),
- result = [];
- for (var key in object) {
- if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * 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);
- };
- }
- /**
- * 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(object, path);
- return (objValue === undefined && objValue === srcValue)
- ? hasIn(object, path)
- : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
- };
- }
- /**
- * The base implementation of `_.merge` without support for multiple sources.
- *
- * @private
- * @param {Object} object The destination object.
- * @param {Object} source The source object.
- * @param {number} srcIndex The index of `source`.
- * @param {Function} [customizer] The function to customize merged values.
- * @param {Object} [stack] Tracks traversed source values and their merged
- * counterparts.
- */
- function baseMerge(object, source, srcIndex, customizer, stack) {
- if (object === source) {
- return;
- }
- if (!(isArray(source) || isTypedArray(source))) {
- var props = baseKeysIn(source);
- }
- arrayEach(props || source, function(srcValue, key) {
- if (props) {
- key = srcValue;
- srcValue = source[key];
- }
- if (isObject(srcValue)) {
- stack || (stack = new Stack);
- baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
- }
- else {
- var newValue = customizer
- ? customizer(object[key], srcValue, (key + ''), object, source, stack)
- : undefined;
- if (newValue === undefined) {
- newValue = srcValue;
- }
- assignMergeValue(object, key, newValue);
- }
- });
- }
- /**
- * A specialized version of `baseMerge` for arrays and objects which performs
- * deep merges and tracks traversed objects enabling objects with circular
- * references to be merged.
- *
- * @private
- * @param {Object} object The destination object.
- * @param {Object} source The source object.
- * @param {string} key The key of the value to merge.
- * @param {number} srcIndex The index of `source`.
- * @param {Function} mergeFunc The function to merge values.
- * @param {Function} [customizer] The function to customize assigned values.
- * @param {Object} [stack] Tracks traversed source values and their merged
- * counterparts.
- */
- function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
- var objValue = object[key],
- srcValue = source[key],
- stacked = stack.get(srcValue);
- if (stacked) {
- assignMergeValue(object, key, stacked);
- return;
- }
- var newValue = customizer
- ? customizer(objValue, srcValue, (key + ''), object, source, stack)
- : undefined;
- var isCommon = newValue === undefined;
- if (isCommon) {
- newValue = srcValue;
- if (isArray(srcValue) || isTypedArray(srcValue)) {
- if (isArray(objValue)) {
- newValue = objValue;
- }
- else if (isArrayLikeObject(objValue)) {
- newValue = copyArray(objValue);
- }
- else {
- isCommon = false;
- newValue = baseClone(srcValue, true);
- }
- }
- else if (isPlainObject(srcValue) || isArguments(srcValue)) {
- if (isArguments(objValue)) {
- newValue = toPlainObject(objValue);
- }
- else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
- isCommon = false;
- newValue = baseClone(srcValue, true);
- }
- else {
- newValue = objValue;
- }
- }
- else {
- isCommon = false;
- }
- }
- if (isCommon) {
- // Recursively merge objects and arrays (susceptible to call stack limits).
- stack.set(srcValue, newValue);
- mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
- stack['delete'](srcValue);
- }
- assignMergeValue(object, key, newValue);
- }
- /**
- * 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);
- };
- }
- /**
- * The base implementation of `_.rest` which doesn't validate or coerce arguments.
- *
- * @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.
- * @returns {Function} Returns the new function.
- */
- function baseRest(func, start) {
- 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] = array;
- return apply(func, this, otherArgs);
- };
- }
- /**
- * 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 (isSymbol(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
- /**
- * Casts `value` to a path array if it's not one.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {Array} Returns the cast property path array.
- */
- function castPath(value) {
- return isArray(value) ? value : stringToPath(value);
- }
- /**
- * 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 result = new buffer.constructor(buffer.length);
- buffer.copy(result);
- return result;
- }
- /**
- * 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;
- }
- /**
- * 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);
- }
- /**
- * Creates a clone of `map`.
- *
- * @private
- * @param {Object} map The map to clone.
- * @param {Function} cloneFunc The function to clone values.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the cloned map.
- */
- function cloneMap(map, isDeep, cloneFunc) {
- var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
- return arrayReduce(array, addMapEntry, new map.constructor);
- }
- /**
- * 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;
- }
- /**
- * Creates a clone of `set`.
- *
- * @private
- * @param {Object} set The set to clone.
- * @param {Function} cloneFunc The function to clone values.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the cloned set.
- */
- function cloneSet(set, isDeep, cloneFunc) {
- var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
- return arrayReduce(array, addSetEntry, new set.constructor);
- }
- /**
- * 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 ? Object(symbolValueOf.call(symbol)) : {};
- }
- /**
- * 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);
- }
- /**
- * 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;
- }
- /**
- * 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) {
- 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;
- assignValue(object, key, newValue === undefined ? source[key] : newValue);
- }
- return object;
- }
- /**
- * Copies own symbol properties 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);
- }
- /**
- * Creates a function like `_.assign`.
- *
- * @private
- * @param {Function} assigner The function to assign values.
- * @returns {Function} Returns the new assigner function.
- */
- function createAssigner(assigner) {
- return baseRest(function(object, sources) {
- var index = -1,
- length = sources.length,
- customizer = length > 1 ? sources[length - 1] : undefined,
- guard = length > 2 ? sources[2] : undefined;
- customizer = (assigner.length > 3 && typeof customizer == 'function')
- ? (length--, customizer)
- : undefined;
- if (guard && isIterateeCall(sources[0], sources[1], guard)) {
- customizer = length < 3 ? undefined : customizer;
- length = 1;
- }
- object = Object(object);
- while (++index < length) {
- var source = sources[index];
- if (source) {
- assigner(object, source, index, customizer);
- }
- }
- return object;
- });
- }
- /**
- * Creates a `baseEach` or `baseEachRight` function.
- *
- * @private
- * @param {Function} eachFunc The function to iterate over a collection.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseEach(eachFunc, fromRight) {
- return function(collection, iteratee) {
- if (collection == null) {
- return collection;
- }
- if (!isArrayLike(collection)) {
- return eachFunc(collection, iteratee);
- }
- var length = collection.length,
- index = fromRight ? length : -1,
- iterable = Object(collection);
- while ((fromRight ? index-- : ++index < length)) {
- if (iteratee(iterable[index], index, iterable) === false) {
- break;
- }
- }
- return collection;
- };
- }
- /**
- * Creates a base function for methods like `_.forIn` and `_.forOwn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseFor(fromRight) {
- return function(object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
- }
- /**
- * 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 {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
- function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
- var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
- arrLength = array.length,
- othLength = other.length;
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(array);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- var index = -1,
- result = true,
- seen = (bitmask & UNORDERED_COMPARE_FLAG) ? 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 (!seen.has(othIndex) &&
- (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
- return seen.add(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(
- arrValue === othValue ||
- equalFunc(arrValue, othValue, customizer, bitmask, stack)
- )) {
- result = false;
- break;
- }
- }
- stack['delete'](array);
- stack['delete'](other);
- return result;
- }
- /**
- * 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 {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @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, equalFunc, customizer, bitmask, 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(+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 & PARTIAL_COMPARE_FLAG;
- 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 |= UNORDERED_COMPARE_FLAG;
- // Recursively compare objects (susceptible to call stack limits).
- stack.set(object, other);
- var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
- stack['delete'](object);
- return result;
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
- }
- /**
- * 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 {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
- var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
- objProps = keys(object),
- objLength = objProps.length,
- othProps = keys(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.call(other, key))) {
- return false;
- }
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- 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, customizer, bitmask, 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;
- }
- /**
- * 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, getSymbols);
- }
- /**
- * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
- * this function returns the custom method, otherwise it returns `baseIteratee`.
- * If arguments are provided, the chosen function is invoked with them and
- * its result is returned.
- *
- * @private
- * @param {*} [value] The value to convert to an iteratee.
- * @param {number} [arity] The arity of the created iteratee.
- * @returns {Function} Returns the chosen function or its result.
- */
- function getIteratee() {
- var result = lodash.iteratee || iteratee;
- result = result === iteratee ? baseIteratee : result;
- return arguments.length ? result(arguments[0], arguments[1]) : result;
- }
- /**
- * 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;
- }
- /**
- * 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(object),
- length = result.length;
- while (length--) {
- var key = result[length],
- value = object[key];
- result[length] = [key, value, isStrictComparable(value)];
- }
- return result;
- }
- /**
- * 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;
- }
- /**
- * Creates an array of the own enumerable symbol properties of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
- var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
- /**
- * 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,
- // for data views in Edge < 14, and promises in Node.js.
- if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
- (Map && getTag(new Map) != mapTag) ||
- (Promise && getTag(Promise.resolve()) != promiseTag) ||
- (Set && getTag(new Set) != setTag) ||
- (WeakMap && getTag(new WeakMap) != weakMapTag)) {
- getTag = function(value) {
- var result = objectToString.call(value),
- Ctor = result == objectTag ? value.constructor : undefined,
- ctorString = Ctor ? toSource(Ctor) : undefined;
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString: return dataViewTag;
- case mapCtorString: return mapTag;
- case promiseCtorString: return promiseTag;
- case setCtorString: return setTag;
- case weakMapCtorString: return weakMapTag;
- }
- }
- return result;
- };
- }
- /**
- * 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 = isKey(path, object) ? [path] : castPath(path);
- var result,
- index = -1,
- length = path.length;
- while (++index < length) {
- var key = toKey(path[index]);
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
- object = object[key];
- }
- if (result) {
- return result;
- }
- var length = object ? object.length : 0;
- return !!length && isLength(length) && isIndex(key, length) &&
- (isArray(object) || isArguments(object));
- }
- /**
- * 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 = array.constructor(length);
- // Add properties assigned by `RegExp#exec`.
- if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
- result.index = array.index;
- result.input = array.input;
- }
- return result;
- }
- /**
- * 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))
- : {};
- }
- /**
- * Initializes an object clone based on its `toStringTag`.
- *
- * **Note:** This function only supports cloning values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to clone.
- * @param {string} tag The `toStringTag` of the object to clone.
- * @param {Function} cloneFunc The function to clone values.
- * @param {boolean} [isDeep] Specify a deep clone.
- * @returns {Object} Returns the initialized clone.
- */
- function initCloneByTag(object, tag, cloneFunc, isDeep) {
- var Ctor = object.constructor;
- switch (tag) {
- case arrayBufferTag:
- return cloneArrayBuffer(object);
- case boolTag:
- case dateTag:
- return new Ctor(+object);
- case dataViewTag:
- return cloneDataView(object, isDeep);
- case float32Tag: case float64Tag:
- case int8Tag: case int16Tag: case int32Tag:
- case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
- return cloneTypedArray(object, isDeep);
- case mapTag:
- return cloneMap(object, isDeep, cloneFunc);
- case numberTag:
- case stringTag:
- return new Ctor(object);
- case regexpTag:
- return cloneRegExp(object);
- case setTag:
- return cloneSet(object, isDeep, cloneFunc);
- case symbolTag:
- return cloneSymbol(object);
- }
- }
- /**
- * 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) {
- length = length == null ? MAX_SAFE_INTEGER : length;
- return !!length &&
- (typeof value == 'number' || reIsUint.test(value)) &&
- (value > -1 && value % 1 == 0 && value < length);
- }
- /**
- * Checks if the given arguments are from an iteratee call.
- *
- * @private
- * @param {*} value The potential iteratee value argument.
- * @param {*} index The potential iteratee index or key argument.
- * @param {*} object The potential iteratee object argument.
- * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
- * else `false`.
- */
- function isIterateeCall(value, index, object) {
- if (!isObject(object)) {
- return false;
- }
- var type = typeof index;
- if (type == 'number'
- ? (isArrayLike(object) && isIndex(index, object.length))
- : (type == 'string' && index in object)
- ) {
- return eq(object[index], value);
- }
- return false;
- }
- /**
- * 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(value)) {
- return false;
- }
- var type = typeof value;
- if (type == 'number' || type == 'symbol' || type == 'boolean' ||
- value == null || isSymbol(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
- (object != null && value in Object(object));
- }
- /**
- * 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);
- }
- /**
- * 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);
- }
- /**
- * 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;
- return value === proto;
- }
- /**
- * 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(value);
- }
- /**
- * 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)));
- };
- }
- /**
- * 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;
- }
- /**
- * Converts `string` to a property path array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the property path array.
- */
- var stringToPath = memoize(function(string) {
- string = toString(string);
- var result = [];
- if (reLeadingDot.test(string)) {
- result.push('');
- }
- string.replace(rePropName, function(match, number, quote, string) {
- result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
- });
- return result;
- });
- /**
- * 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(value)) {
- return value;
- }
- var result = (value + '');
- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
- }
- /**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to process.
- * @returns {string} Returns the source code.
- */
- function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
- try {
- return (func + '');
- } catch (e) {}
- }
- return '';
- }
- /*------------------------------------------------------------------------*/
- /**
- * Creates an array with all falsey values removed. The values `false`, `null`,
- * `0`, `""`, `undefined`, and `NaN` are falsey.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Array
- * @param {Array} array The array to compact.
- * @returns {Array} Returns the new array of filtered values.
- * @example
- *
- * _.compact([0, 1, false, 2, '', 3]);
- * // => [1, 2, 3]
- */
- function compact(array) {
- var index = -1,
- length = array ? array.length : 0,
- resIndex = 0,
- result = [];
- while (++index < length) {
- var value = array[index];
- if (value) {
- result[resIndex++] = value;
- }
- }
- return result;
- }
- /*------------------------------------------------------------------------*/
- /**
- * Iterates over elements of `collection` and invokes `iteratee` for each element.
- * The iteratee is invoked with three arguments: (value, index|key, collection).
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * **Note:** As with other "Collections" methods, objects with a "length"
- * property are iterated like arrays. To avoid this behavior use `_.forIn`
- * or `_.forOwn` for object iteration.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @alias each
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- * @see _.forEachRight
- * @example
- *
- * _([1, 2]).forEach(function(value) {
- * console.log(value);
- * });
- * // => Logs `1` then `2`.
- *
- * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'a' then 'b' (iteration order is not guaranteed).
- */
- function forEach(collection, iteratee) {
- var func = isArray(collection) ? arrayEach : baseEach;
- return func(collection, getIteratee(iteratee, 3));
- }
- /*------------------------------------------------------------------------*/
- /**
- * 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 `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 && 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);
- return result;
- };
- memoized.cache = new (memoize.Cache || MapCache);
- return memoized;
- }
- // Assign cache to `_.memoize`.
- memoize.Cache = MapCache;
- /*------------------------------------------------------------------------*/
- /**
- * 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, false, true);
- }
- /**
- * 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);
- }
- /**
- * 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
- */
- function isArguments(value) {
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
- return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
- (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
- }
- /**
- * 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 = Array.isArray;
- /**
- * 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(value.length) && !isFunction(value);
- }
- /**
- * This method is like `_.isArrayLike` except that it also checks if `value`
- * is an object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array-like object,
- * else `false`.
- * @example
- *
- * _.isArrayLikeObject([1, 2, 3]);
- * // => true
- *
- * _.isArrayLikeObject(document.body.children);
- * // => true
- *
- * _.isArrayLikeObject('abc');
- * // => false
- *
- * _.isArrayLikeObject(_.noop);
- * // => false
- */
- function isArrayLikeObject(value) {
- return isObjectLike(value) && isArrayLike(value);
- }
- /**
- * 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;
- /**
- * Checks if `value` is an empty object, collection, map, or set.
- *
- * Objects are considered empty if they have no own enumerable string keyed
- * properties.
- *
- * Array-like values such as `arguments` objects, arrays, buffers, strings, or
- * jQuery-like collections are considered empty if they have a `length` of `0`.
- * Similarly, maps and sets are considered empty if they have a `size` of `0`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is empty, else `false`.
- * @example
- *
- * _.isEmpty(null);
- * // => true
- *
- * _.isEmpty(true);
- * // => true
- *
- * _.isEmpty(1);
- * // => true
- *
- * _.isEmpty([1, 2, 3]);
- * // => false
- *
- * _.isEmpty({ 'a': 1 });
- * // => false
- */
- function isEmpty(value) {
- if (isArrayLike(value) &&
- (isArray(value) || typeof value == 'string' ||
- typeof value.splice == 'function' || isBuffer(value) || isArguments(value))) {
- return !value.length;
- }
- var tag = getTag(value);
- if (tag == mapTag || tag == setTag) {
- return !value.size;
- }
- if (nonEnumShadows || isPrototype(value)) {
- return !nativeKeys(value).length;
- }
- for (var key in value) {
- if (hasOwnProperty.call(value, key)) {
- return false;
- }
- }
- return true;
- }
- /**
- * 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) {
- // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 8-9 which returns 'object' for typed array and other constructors.
- var tag = isObject(value) ? objectToString.call(value) : '';
- return tag == funcTag || tag == genTag;
- }
- /**
- * 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;
- }
- /**
- * 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(value) {
- var type = typeof value;
- return !!value && (type == 'object' || type == 'function');
- }
- /**
- * 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 && typeof value == '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(value) ||
- objectToString.call(value) != objectTag || isHostObject(value)) {
- return false;
- }
- var proto = getPrototype(value);
- if (proto === null) {
- return true;
- }
- var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
- return (typeof Ctor == 'function' &&
- Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
- }
- /**
- * 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(value) && objectToString.call(value) == symbolTag);
- }
- /**
- * 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;
- /**
- * Converts `value` to a plain object flattening inherited enumerable string
- * keyed properties of `value` to own properties of the plain object.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {Object} Returns the converted plain object.
- * @example
- *
- * function Foo() {
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.assign({ 'a': 1 }, new Foo);
- * // => { 'a': 1, 'b': 2 }
- *
- * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
- * // => { 'a': 1, 'b': 2, 'c': 3 }
- */
- function toPlainObject(value) {
- return copyObject(value, keysIn(value));
- }
- /**
- * 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 process.
- * @returns {string} Returns the string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? '' : baseToString(value);
- }
- /*------------------------------------------------------------------------*/
- /**
- * 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(object, path, defaultValue) {
- var result = object == null ? undefined : baseGet(object, path);
- return result === undefined ? defaultValue : result;
- }
- /**
- * 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);
- }
- /**
- * 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(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
- /**
- * 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(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
- }
- /**
- * This method is like `_.assign` except that it recursively merges own and
- * inherited enumerable string keyed properties of source objects into the
- * destination object. Source properties that resolve to `undefined` are
- * skipped if a destination value exists. Array and plain object properties
- * are merged recursively. Other objects and value types are overridden by
- * assignment. Source objects are applied from left to right. Subsequent
- * sources overwrite property assignments of previous sources.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 0.5.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = {
- * 'a': [{ 'b': 2 }, { 'd': 4 }]
- * };
- *
- * var other = {
- * 'a': [{ 'c': 3 }, { 'e': 5 }]
- * };
- *
- * _.merge(object, other);
- * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
- */
- var merge = createAssigner(function(object, source, srcIndex) {
- baseMerge(object, source, srcIndex);
- });
- /*------------------------------------------------------------------------*/
- /**
- * 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;
- }
- /**
- * 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, true));
- }
- /**
- * 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);
- }
- /**
- * 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 [];
- }
- /**
- * 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;
- }
- /*------------------------------------------------------------------------*/
- // Add methods that return wrapped values in chain sequences.
- lodash.compact = compact;
- lodash.iteratee = iteratee;
- lodash.keys = keys;
- lodash.keysIn = keysIn;
- lodash.memoize = memoize;
- lodash.merge = merge;
- lodash.property = property;
- lodash.toPlainObject = toPlainObject;
- /*------------------------------------------------------------------------*/
- // Add methods that return unwrapped values in chain sequences.
- lodash.clone = clone;
- lodash.eq = eq;
- lodash.forEach = forEach;
- lodash.get = get;
- lodash.hasIn = hasIn;
- lodash.identity = identity;
- lodash.isArguments = isArguments;
- lodash.isArray = isArray;
- lodash.isArrayLike = isArrayLike;
- lodash.isArrayLikeObject = isArrayLikeObject;
- lodash.isBuffer = isBuffer;
- lodash.isEmpty = isEmpty;
- lodash.isFunction = isFunction;
- lodash.isLength = isLength;
- lodash.isObject = isObject;
- lodash.isObjectLike = isObjectLike;
- lodash.isPlainObject = isPlainObject;
- lodash.isSymbol = isSymbol;
- lodash.isTypedArray = isTypedArray;
- lodash.stubArray = stubArray;
- lodash.stubFalse = stubFalse;
- lodash.toString = toString;
- // Add aliases.
- lodash.each = forEach;
- /*------------------------------------------------------------------------*/
- /**
- * The semantic version number.
- *
- * @static
- * @memberOf _
- * @type {string}
- */
- lodash.VERSION = VERSION;
- /*--------------------------------------------------------------------------*/
- if (freeModule) {
- // Export for Node.js.
- (freeModule.exports = lodash)._ = lodash;
- // Export for CommonJS support.
- freeExports._ = lodash;
- }
- }.call(this));
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],179:[function(require,module,exports){
- const strsearch2regexp = require('strsearch2regexp')
- const filterJoin = require('./filterJoin')
- function qlesc (str) {
- return '"' + str.replace(/"/g, '\\"') + '"'
- }
- function compile (part) {
- if (Array.isArray(part)) {
- return part.map(compile).join('')
- }
- if (part.or) {
- return { or: part.or.map(compile) }
- }
- let keyRegexp = (part.keyRegexp ? '~' : '')
- switch (part.op) {
- case 'has_key':
- if (keyRegexp) {
- return '[~' + qlesc(part.key) + '~"."]'
- } else {
- return '[' + keyRegexp + qlesc(part.key) + ']'
- }
- case '=':
- case '!=':
- case '~':
- case '!~':
- return '[' + keyRegexp + qlesc(part.key) + part.op + qlesc(part.value) + ']'
- case '~i':
- case '!~i':
- return '[' + keyRegexp + qlesc(part.key) + part.op.substr(0, part.op.length - 1) + qlesc(part.value) + ',i]'
- case 'has':
- return '[' + keyRegexp + qlesc(part.key) + '~' + qlesc('^(.*;|)' + part.value + '(|;.*)$') + ']'
- case 'strsearch':
- return '[' + keyRegexp + qlesc(part.key) + '~' + qlesc(strsearch2regexp(part.value)) + ',i]'
- default:
- throw new Error('unknown operator')
- }
- }
- function test (ob, part) {
- if (Array.isArray(part)) {
- return part.every(part => test(ob, part))
- }
- if (part.type) {
- return ob.type === part.type
- }
- if (part.or) {
- return part.or.some(part => test(ob, part))
- }
- if (part.keyRegexp) {
- let regex
- if (part.value) {
- regex = new RegExp(part.value, part.op.match(/i$/) ? 'i' : '')
- }
- for (let k in ob.tags) {
- if (k.match(part.key)) {
- if (regex) {
- if (ob.tags[k].match(regex)) {
- return true
- }
- } else {
- return true
- }
- }
- }
- return false
- }
- switch (part.op) {
- case 'has_key':
- return ob.tags && (part.key in ob.tags)
- case '=':
- return ob.tags && (part.key in ob.tags) && (ob.tags[part.key] === part.value)
- case '!=':
- return ob.tags && (!(part.key in ob.tags) || (ob.tags[part.key] !== part.value))
- case '~':
- return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(part.value))
- case '!~':
- return ob.tags && (!(part.key in ob.tags) || (!ob.tags[part.key].match(part.value)))
- case '~i':
- return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(new RegExp(part.value, 'i')))
- case '!~i':
- return ob.tags && (!(part.key in ob.tags) || !ob.tags[part.key].match(new RegExp(part.value, 'i')))
- case 'has':
- return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].split(/;/).indexOf(part.value) !== -1)
- case 'strsearch':
- return ob.tags && (part.key in ob.tags) && (ob.tags[part.key].match(new RegExp(strsearch2regexp(part.value), 'i')))
- default:
- return false
- }
- }
- function parseString (str) {
- let result = ''
- let chr = str[0]
- str = str.slice(1)
- while (str.length) {
- let m = str.match('^[^\\\\' + chr + ']+')
- if (m) {
- result += m[0]
- str = str.slice(m[0].length)
- } else if (str[0] === '\\') {
- result += str[1]
- str = str.slice(2)
- } else if (str[0] === chr) {
- str = str.slice(1)
- return [ result, str ]
- } else {
- throw new Error("Can't parse string from query: " + str)
- }
- }
- }
- function parse (def) {
- let result = []
- let mode = 0
- let key
- let value
- let op
- let m
- let keyRegexp = false
- while (def.length) {
- if (mode === 0) {
- m = def.match(/^\s*(node|way|relation|rel|nwr|\()/)
- if (m && m[1] === '(') {
- def = def.slice(m[0].length)
- let parts = []
- do {
- let part
- [ part, def ] = parse(def)
- parts.push(part)
- } while (!def.match(/^\s*\)/))
- return [ { or: parts }, def ]
- } else if (m) {
- if (m[1] === 'rel') {
- result.push({ type: 'relation' })
- } else if (m[1] === 'nwr') {
- // nothing
- } else {
- result.push({ type: m[1] })
- }
- mode = 10
- def = def.slice(m[0].length)
- } else {
- throw new Error("Can't parse query, expected type of object (e.g. 'node'): " + def)
- }
- } else if (mode === 10) {
- let m = def.match(/^\s*(\[|;)/)
- if (m && m[1] === '[') {
- def = def.slice(m[0].length)
- mode = 11
- } else if (m && m[1] === ';') {
- def = def.slice(m[0].length)
- return [ result, def ]
- } else if (!m && def.match(/^\s*$/)) {
- return [ result, '' ]
- } else {
- throw new Error("Can't parse query, expected '[' or ';': " + def)
- }
- } else if (mode === 11) {
- m = def.match(/^(\s*)(~\s*)?([a-zA-Z0-9_]+|"|')/)
- if (m && m[2]) {
- keyRegexp = true
- }
- if (m && (m[3] === '"' || m[3] === "'")) {
- def = def.slice(m[1].length + (m[2] || '').length)
- let x = parseString(def)
- key = x[0]
- def = x[1]
- mode = 12
- } else if (m) {
- key = m[3]
- def = def.slice(m[0].length)
- mode = 12
- } else {
- throw new Error("Can't parse query, expected key: " + def)
- }
- } else if (mode === 12) {
- m = def.match(/^\s*(=|!=|~|!~|\^|]|%)/)
- if (m && m[1] === ']') {
- let entry = { key, op: 'has_key' }
- if (keyRegexp) {
- entry.keyRegexp = true
- }
- result.push(entry)
- def = def.slice(m[0].length)
- mode = 10
- } else if (m) {
- op = m[1] === '^' ? 'has'
- : m[1] === '%' ? 'strsearch'
- : m[1]
- mode = 13
- def = def.slice(m[0].length)
- } else {
- throw new Error("Can't parse query, expected operator or ']': " + def)
- }
- } else if (mode === 13) {
- m = def.match(/^(\s*)([a-zA-Z0-9_]+|"|')/)
- if (m && (m[2] === '"' || m[2] === "'")) {
- def = def.slice(m[1].length)
- let x = parseString(def)
- value = x[0]
- def = x[1]
- mode = 14
- } else if (m) {
- value = m[2]
- def = def.slice(m[0].length)
- mode = 14
- } else {
- throw new Error("Can't parse query, expected value: " + def)
- }
- } else if (mode === 14) {
- m = def.match(/^\s*(,i)?\]/)
- if (m) {
- if (m[1] === ',i') {
- if (op === '~' || op === '!~') {
- op += 'i'
- } else {
- throw new Error("Can't parse query, expected ']': " + def)
- }
- }
- let entry = { key, op, value }
- if (keyRegexp) {
- entry.keyRegexp = true
- }
- result.push(entry)
- mode = 10
- def = def.slice(m[0].length)
- } else {
- throw new Error("Can't parse query, expected ']': " + def)
- }
- }
- }
- return [ result, def ]
- }
- /**
- * A Filter into OSM data. A simplified version of <a href='https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL'>Overpass QL</a>.
- *
- * <p>Either a single query (e.g. <tt>node[amenity=restaurant];</tt>) or a combined query (e.g. <tt>(node[amenity=restaurant];way[amenity=restaurant];);</tt>).<br>
- * A single query statement consists of a type (e.g. 'node', 'way', 'relation', 'nwr' (node, way or relation)) and optional filters:<ul>
- * <li>(Not) Equals (=, !=): <tt>[amenity=restaurant]</tt> or <tt>["amenity"="restaurant"]</tt> resp. <tt>["amenity"!="restaurant"]</tt>.
- * <li>Regular Expression: <tt>[amenity~"^(restaurant|cafe)$"]</tt> resp. negated: <tt>[amenity!~"^(restaurant|cafe)$"]</tt>
- * <li>Key regular expression: <tt>[~"cycleway"~"left"]</tt> (key has to match cycleway and its value match left)
- * <li>Key (not) exists: <tt>[amenity]</tt> or <tt>["amenity"]</tt> resp. <tt>[!amenity]</tt>
- * <li>Array search: <tt>[cuisine^kebap]</tt>: search for cuisine tags which exactly include 'kebap' (semicolon-separated values, e.g. <tt>cuisine=kebap;pizza</tt>).
- * <li>String search: <tt>[name%cafe]</tt>: search for name tags which are similar to cafe, e.g. "café". (see https://github.com/plepe/strsearch2regexp for details).
- * </ul>
- * More advanced queries are not supported.</p>
- *
- * @param {string|object} query
- */
- class Filter {
- constructor (def) {
- if (typeof def === 'string') {
- [ this.def ] = parse(def)
- return
- }
- this.def = def
- }
- /**
- * Check if an object matches this filter
- * @param {OverpassNode|OverpassWay|OverpassRelation} ob an object from Overpass API
- * @return {boolean}
- */
- match (ob, def) {
- if (!def) {
- def = this.def
- }
- if (def.or) {
- return def.or.some(part => this.match(ob, part))
- }
- return def.filter(test.bind(this, ob)).length === def.length
- }
- /**
- * Convert query to a string representation
- * @return {string}
- */
- toString (def) {
- let result = ''
- if (!def) {
- def = this.def
- }
- if (def.or) {
- return '(' + def.or.map(part => this.toString(part)).join(';') + ';)'
- }
- let parts = def.filter(part => part.type)
- switch (parts.length) {
- case 0:
- result = 'nwr'
- break
- case 1:
- result = parts[0].type
- break
- default:
- throw new Error('Filter: only one type query allowed!')
- }
- let queries = filterJoin(def
- .filter(part => !part.type)
- .map(compile))
- if (queries.length > 1) {
- return '(' + queries.map(q => result + q).join(';') + ';)'
- } else {
- return result + queries[0]
- }
- }
- /**
- * Convert query to Overpass QL
- * @param {object} [options] Additional options
- * @param {string} [options.inputSet=''] Specify input set (e.g.'.foo').
- * @return {string}
- */
- toQl (options = {}, def) {
- if (!def) {
- def = this.def
- }
- if (!options.inputSet) {
- options.inputSet = ''
- }
- if (def.or) {
- return '(' + def.or.map(part => {
- let r = this.toQl(options, part)
- return r.slice(1, -1)
- }).join('') + ')'
- }
- let parts = def.filter(part => part.type)
- let types
- switch (parts.length) {
- case 0:
- types = [ 'node', 'way', 'relation' ]
- break
- case 1:
- types = [ parts[0].type ]
- break
- default:
- throw new Error('Filter: only one type query allowed!')
- }
- let queries = filterJoin(def
- .filter(part => !part.type)
- .map(compile))
- if (queries.length > 1) {
- return '(' + queries.map(q => types.map(type => type + options.inputSet + q).join(';')).join(';') + ';)'
- } else {
- return '(' + types.map(type => type + options.inputSet + queries[0]).join(';') + ';)'
- }
- }
- /**
- * Convert query to LokiJS query for local database. If the property 'needMatch' is set on the returned object, an additional match() should be executed for each returned object, as the query can't be fully compiled (and the 'needMatch' property removed).
- * @param {object} [options] Additional options
- * @return {object}
- */
- toLokijs (options = {}, def) {
- if (!def) {
- def = this.def
- }
- if (def.or) {
- let needMatch = false
- let r = { $or:
- def.or.map(part => {
- let r = this.toLokijs(options, part)
- if (r.needMatch) {
- needMatch = true
- }
- delete r.needMatch
- return r
- })
- }
- if (needMatch) {
- r.needMatch = true
- }
- return r
- }
- let query = {}
- let orQueries = []
- if (!Array.isArray(def)) {
- def = [ def ]
- }
- def.forEach(filter => {
- let k, v
- if (filter.keyRegexp) {
- k = 'needMatch'
- v = true
- // can't query for key regexp, skip
- } else if (filter.op === '=') {
- k = 'tags.' + filter.key
- v = { $eq: filter.value }
- } else if (filter.op === '!=') {
- k = 'tags.' + filter.key
- v = { $ne: filter.value }
- } else if (filter.op === 'has_key') {
- k = 'tags.' + filter.key
- v = { $exists: true }
- } else if (filter.op === 'has') {
- k = 'tags.' + filter.key
- v = { $regex: '^(.*;|)' + filter.value + '(|;.*)$' }
- } else if ((filter.op === '~') || (filter.op === '~i')) {
- k = 'tags.' + filter.key
- v = { $regex: new RegExp(filter.value, (filter.op === '~i' ? 'i' : '')) }
- } else if ((filter.op === '!~') || (filter.op === '!~i')) {
- k = 'tags.' + filter.key
- v = { $not: { $regex: new RegExp(filter.value, (filter.op === '!~i' ? 'i' : '')) } }
- } else if (filter.op === 'strsearch') {
- k = 'tags.' + filter.key
- v = { $regex: new RegExp(strsearch2regexp(filter.value), 'i') }
- } else if (filter.type) {
- k = 'type'
- v = { $eq: filter.type }
- } else if (filter.or) {
- orQueries.push(filter.or.map(p => {
- let r = this.toLokijs(options, p)
- if (r.needMatch) {
- query.needMatch = true
- delete r.needMatch
- }
- return r
- }))
- } else {
- console.log('unknown filter', filter)
- }
- if (k && v) {
- if (k === 'needMatch') {
- query.needMatch = true
- } else if (k in query) {
- if (!('$and' in query[k])) {
- query[k] = { $and: [ query[k] ] }
- }
- query[k].$and.push(v)
- } else {
- query[k] = v
- }
- }
- })
- orQueries = orQueries.filter(q => Object.keys(q).length)
- if (orQueries.length === 1) {
- query.$or = orQueries[0]
- } else if (orQueries.length > 1) {
- query.$and = orQueries.map(q => { return { $or: q } })
- }
- return query
- }
- }
- module.exports = Filter
- },{"./filterJoin":194,"strsearch2regexp":205}],180:[function(require,module,exports){
- (function (global){
- const ee = require('event-emitter')
- var async = require('async')
- var weightSort = require('weight-sort')
- var BoundingBox = require('boundingbox')
- const LokiJS = require('lokijs')
- var httpLoad = require('./httpLoad')
- var removeNullEntries = require('./removeNullEntries')
- var OverpassObject = require('./OverpassObject')
- var OverpassNode = require('./OverpassNode')
- var OverpassWay = require('./OverpassWay')
- var OverpassRelation = require('./OverpassRelation')
- var RequestGet = require('./RequestGet')
- var RequestBBox = require('./RequestBBox')
- var defines = require('./defines')
- var loadOsmFile = require('./loadOsmFile')
- var copyOsm3sMetaFrom = require('./copyOsm3sMeta')
- const Filter = require('./Filter')
- /**
- * An error occured
- * @event OverpassFrontend#error
- * @param {Error} error
- */
- /**
- * When a file is specified as URL, this event notifies, that the file has been completely loaded. When a Overpass API is used, every time when data has been received.
- * @event OverpassFrontend#load
- * @param {object} osm3sMeta Meta data (not all properties of meta data might be set)
- * @param {number} osm3sMeta.version OpenStreetMap API version (currently 0.6)
- * @param {string} osm3sMeta.generator Data generator
- * @param {string} osm3sMeta.timestamp_osm_base RFC8601 timestamp of OpenStreetMap data
- * @param {string} osm3sMeta.copyright Copyright statement
- */
- /**
- * When an object is updated (e.g. when loaded; additional information loaded; when a member object got loaded)
- * @event OverpassFrontend#update
- * @param {OverpassNode|OverpassWay|OverpassRelation} object The object which got updated.
- */
- /**
- * A connection to an Overpass API Server or an OpenStreetMap file
- * @param {string} url The URL of the API, e.g. 'https://overpass-api.de/api/'. If you omit the protocol, it will use the protocol which is in use for the current page (or https: on nodejs): '//overpass-api.de/api/'. If the url ends in .json, .osm or .osm.bz2 it will load this OpenStreetMap file and use the data from there.
- * @param {object} options Options
- * @param {number} [options.effortPerRequest=1000] To avoid huge requests to the Overpass API, the request will be split into smaller chunks. This value defines, at which effort the request will be sent.
- * @param {number} [options.effortNode=1] The effort for request a node. Default: 1.
- * @param {number} [options.effortWay=4] The effort for request a way.
- * @param {number} [options.effortRelation=64] The effort for request a relation.
- * @param {number} [options.timeGap=10] A short time gap between two requests to the Overpass API (milliseconds).
- * @param {number} [options.loadChunkSize=1000] When loading a file (instead connecting to an Overpass URL) load elements in chunks of n items.
- */
- class OverpassFrontend {
- constructor (url, options) {
- this.url = url
- this.options = {
- effortPerRequest: 1000,
- effortNode: 1,
- effortWay: 4,
- effortRelation: 64,
- timeGap: 10,
- loadChunkSize: 1000
- }
- for (var k in options) {
- this.options[k] = options[k]
- }
- let db = new LokiJS()
- this.db = db.addCollection('osm', { unique: [ 'id' ] })
- this.clearCache()
- this.requests = []
- this.requestIsActive = false
- this.errorCount = 0
- this.pendingNotifyMemberUpdate = {}
- this.pendingUpdateEmit = {}
- if (this.url.match(/\.(json|osm\.bz2|osm)$/)) {
- this.localOnly = true
- this.ready = false
- this._loadFile()
- } else {
- this.remote = true
- this.ready = true
- }
- }
- /**
- * clear all caches
- */
- clearCache () {
- this.cacheElements = {}
- this.cacheElementsMemberOf = {}
- this.cacheBBoxQueries = {}
- this.db.clear()
- }
- _loadFile () {
- let osm3sMeta
- loadOsmFile(this.url,
- (err, result) => {
- if (err) {
- console.log('Error loading file', err)
- return this.emit('error', err)
- }
- osm3sMeta = copyOsm3sMetaFrom(result)
- let chunks = []
- for (var i = 0; i < result.elements.length; i += this.options.loadChunkSize) {
- chunks.push(result.elements.slice(i, i + this.options.loadChunkSize))
- }
- async.eachLimit(
- chunks,
- 1,
- (chunk, done) => {
- chunk.forEach(
- (element) => {
- let ob = this.createOrUpdateOSMObject(element, {
- osm3sMeta,
- properties: OverpassFrontend.TAGS | OverpassFrontend.META | OverpassFrontend.MEMBERS
- })
- // Set objects to fully known, as no more data can be loaded from the file
- ob.properties |= OverpassFrontend.ALL
- }
- )
- global.setTimeout(done, 0)
- },
- (err) => {
- this.pendingNotifies()
- if (err) {
- console.log('Error loading file', err)
- return this.emit('error', err)
- }
- this.emit('load', osm3sMeta)
- this.ready = true
- this._overpassProcess()
- }
- )
- }
- )
- }
- /**
- * @param {string|string[]} ids - Id or array of Ids of OSM map features, e.g. [ 'n123', 'w2345', 'n123' ]. Illegal IDs will not produce an error but generate a 'null' object.
- * @param {object} options Various options, see below
- * @param {number} [options.priority=0] - Priority for loading these objects. The lower the sooner they will be requested.
- * @param {string|boolean} [options.sort=false] - When set to true or "index", the function featureCallback will be called in order of the "ids" array. When set to false or null, the featureCallback will be called as soon as the object is loaded (e.g. immediately, if it is cached). When set to "BBoxDiagonalLength", the objects are ordered by the length of the diagonal of the bounding box.
- * @param {"asc"|"desc"} [options.sortDir="asc"] Sort direction.
- * @param {function} featureCallback Will be called for each object which is passed in parameter 'ids'. Will be passed: 1. err (if an error occured, otherwise null), 2. the object or null, 3. index of the item in parameter ids.
- * @param {function} finalCallback Will be called after the last feature. Will be passed: 1. err (if an error occured, otherwise null).
- * @return {RequestGet}
- */
- get (ids, options, featureCallback, finalCallback) {
- var request = new RequestGet(this, {
- ids: ids,
- options: options,
- featureCallback: featureCallback,
- finalCallback: finalCallback
- })
- this.requests.push(request)
- this._next()
- return request
- }
- /**
- * return an OSM object, if it is already in the cache
- * @param {string} id - Id of an OSM map feature
- * @param {object} options
- * @param {int} [options.properties] - Which properties have to be known (default: OverpassFrontend.DEFAULT)
- * @return {null|false|OverpassObject} - null: does not exist in the database; false: may exist, but has not been loaded yet (or not enough properties known); OverpassObject: sucessful object
- */
- getCached (id, options) {
- if (typeof options === 'undefined') {
- options = {}
- }
- if (typeof options.properties === 'undefined') {
- options.properties = defines.DEFAULT
- }
- if (!(id in this.cacheElements)) {
- return false
- }
- let ob = this.cacheElements[id]
- if (ob.missingObject) {
- return null
- }
- if ((options.properties & ob.properties) !== options.properties) {
- return false
- }
- return ob
- }
- /**
- * Current request context
- * @typedef {Object} OverpassFrontend#Context
- * @property {string} query - The compiled code of all sub requests
- * @property {Request[]} requests - List of all requests in the context
- * @property {Request#SubRequest[]} subRequests - List of all subRequests in the context
- * @property {BoundingBox} bbox - when there are any BBox requests, add this global bbox
- * @property {int} maxEffort - how many queries can we still add to this context
- * @property {object} todo - list of items which should be loaded via get requests to avoid duplicates
- */
- _overpassProcess () {
- // currently active - we'll come back later :-)
- if (this.requestIsActive || !this.ready) {
- return
- }
- // preprocess all requests
- // e.g. call featureCallback for elements which were received in the
- // meantime
- this.requests.forEach(request => {
- if (request) {
- request.preprocess()
- if (request.mayFinish() || this.localOnly) {
- request.finish()
- }
- }
- })
- this.requests = removeNullEntries(this.requests)
- // nothing todo ...
- if (!this.requests.length) {
- return
- }
- // now order all requests by priority
- this.requests = weightSort(this.requests, 'priority')
- this.requestIsActive = true
- var request
- var j
- var context = {
- bbox: null,
- todo: {},
- requests: [],
- subRequests: [],
- query: '',
- minPriority: this.requests[0].priority,
- minEffort: 0,
- maxEffort: 0
- }
- for (j = 0; j < this.requests.length; j++) {
- request = this.requests[j]
- if (request.priority > context.minPriority &&
- (context.maxEffort === null || context.maxEffort > this.options.effortPerRequest)) {
- break
- }
- if (request.willInclude(context)) {
- let { minEffort, maxEffort } = request.minMaxEffort()
- if (context.minEffort > 0 && context.minEffort + minEffort > this.options.effortPerRequest) {
- continue
- }
- context.minEffort += minEffort
- if (maxEffort === null) {
- context.maxEffort = null
- } else if (context.maxEffort !== null) {
- context.maxEffort += maxEffort
- }
- context.requests.push(request)
- }
- }
- var effortAvailable = this.options.effortPerRequest
- for (j = 0; j < context.requests.length; j++) {
- request = context.requests[j]
- let remainingRequestsAtPriority = context.requests.slice(j).filter(r => r.priority === request.priority)
- context.maxEffort = Math.ceil(effortAvailable / remainingRequestsAtPriority.length)
- var subRequest = request.compileQuery(context)
- if (subRequest.parts.length === 0) {
- console.log('subRequest has no parts! Why was willInclude true?', subRequest)
- continue
- }
- context.subRequests.push(subRequest)
- if (context.query !== '') {
- context.query += '\nout count;\n'
- }
- effortAvailable -= subRequest.effort
- context.query += subRequest.query
- if (effortAvailable <= 0) {
- break
- }
- }
- if (context.query === '') {
- return this._next()
- }
- var query = '[out:json]'
- if (context.bbox) {
- query += '[bbox:' + context.bbox.toLatLonString() + ']'
- }
- query += ';\n' + context.query
- setTimeout(function () {
- httpLoad(
- this.url,
- null,
- query,
- this._handleResult.bind(this, context)
- )
- }.bind(this), this.options.timeGap)
- }
- _handleResult (context, err, results) {
- this.requestIsActive = false
- if (err === null && results.remark) {
- err = results.remark
- }
- if (err !== null) {
- this.errorCount++
- if (this.errorCount <= 3) {
- // retry
- this._overpassProcess()
- } else {
- // abort
- // call finalCallback for the request
- context.subRequests.forEach(function (subRequest) {
- subRequest.request.finish(err)
- })
- }
- return
- } else {
- this.errorCount = 0
- }
- let osm3sMeta = copyOsm3sMetaFrom(results)
- this.emit('load', osm3sMeta)
- var subRequestsIndex = 0
- var partIndex = 0
- var subRequest = context.subRequests[0]
- var request = subRequest.request
- var part = subRequest.parts[0]
- if (!('count' in part)) {
- part.count = 0
- }
- for (var i = 0; i < results.elements.length; i++) {
- var el = results.elements[i]
- if (isSeparator(el)) {
- partIndex++
- if (partIndex >= subRequest.parts.length) {
- request.finishSubRequest(subRequest)
- if (request.mayFinish() && !request.finished) {
- request.finish()
- }
- subRequestsIndex++
- partIndex = 0
- subRequest = context.subRequests[subRequestsIndex]
- request = subRequest.request
- part = subRequest.parts[0]
- if (!('count' in part)) {
- part.count = 0
- }
- } else {
- part = subRequest.parts[partIndex]
- }
- continue
- }
- part.osm3sMeta = osm3sMeta
- var ob = this.createOrUpdateOSMObject(el, part)
- delete context.todo[ob.id]
- var members = this.cacheElements[ob.id].memberIds()
- if (members) {
- for (var j = 0; j < members.length; j++) {
- if (!(members[j] in this.cacheElementsMemberOf)) {
- this.cacheElementsMemberOf[members[j]] = [ this.cacheElements[ob.id] ]
- } else {
- this.cacheElementsMemberOf[members[j]].push(this.cacheElements[ob.id])
- }
- }
- }
- part.count++
- if (part.receiveObject) {
- part.receiveObject(ob)
- }
- if (!request.aborted && !request.finished && part.featureCallback) {
- part.featureCallback(err, ob)
- }
- }
- if (!(subRequestsIndex === context.subRequests.length - 1 || partIndex === context.subRequests[subRequestsIndex].parts.length - 1)) {
- console.log('too many parts!!!!')
- }
- for (var id in context.todo) {
- if (!(id in this.cacheElements)) {
- let ob = new OverpassObject()
- ob.id = id
- ob.type = { n: 'node', w: 'way', r: 'relation' }[id.substr(0, 1)]
- ob.osm_id = id.substr(1)
- ob.properties = OverpassFrontend.ALL
- ob.missingObject = true
- this.cacheElements[id] = ob
- this.db.insert(ob.dbInsert())
- } else {
- let ob = this.cacheElements[id]
- ob.missingObject = true
- this.db.update(ob.dbInsert())
- }
- }
- this.pendingNotifies()
- request.finishSubRequest(subRequest)
- this._next()
- }
- /**
- * @param {string} query - Query for requesting objects from Overpass API, e.g. "node[amenity=restaurant]" or "(node[amenity];way[highway~'^(primary|secondary)$];)". See <a href='Filter.html'>Filter</a> for details.
- * @param {BoundingBox} bounds - A Leaflet Bounds object, e.g. from map.getBounds()
- * @param {object} options
- * @param {number} [options.priority=0] - Priority for loading these objects. The lower the sooner they will be requested.
- * @param {boolean|string} [options.sort=false] - If false, it will be called as soon as the features are availabe (e.g. immediately when cached).
- * @param {bit_array} [options.properties] Which properties of the features should be downloaded: OVERPASS_ID_ONLY, OVERPASS_BBOX, OVERPASS_TAGS, OVERPASS_GEOM, OVERPASS_META. Combine by binary OR: ``OVERPASS_ID | OVERPASS_BBOX``. Default: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
- * @param {number} [options.split=0] If more than 'split' elements would be returned, split into several smaller requests, with 'split' elements each. Default: 0 (do not split)
- * @param {boolean} [options.members=false] Query relation members of. Default: false
- * @param {function} [options.memberCallback] For every member, call this callback function. (Requires options.members=true)
- * @param {bit_array} [options.memberProperties] Which properties should be loaded for the members. Default: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
- * @param {number} [options.memberSplit=0] If more than 'memberSplit' member elements would be returned, split into smaller requests (see 'split'). 0 = do not split.
- * @param {string|Filter} [options.filter] Additional filter.
- * @param {boolean} [options.noCacheQuery=false] If true, the local cache will not be queried
- * @param {function} featureCallback Will be called for each matching object. Will be passed: 1. err (if an error occured, otherwise null), 2. the object or null.
- * @param {function} finalCallback Will be called after the last feature. Will be passed: 1. err (if an error occured, otherwise null).
- * @return {RequestBBox}
- */
- BBoxQuery (query, bounds, options, featureCallback, finalCallback) {
- bounds = new BoundingBox(bounds)
- var request = new RequestBBox(this, {
- query: query,
- bounds: bounds,
- remainingBounds: bounds,
- options: options,
- doneFeatures: {},
- featureCallback: featureCallback,
- finalCallback: finalCallback
- })
- this.requests.push(request)
- this._next()
- return request
- }
- clearBBoxQuery (query) {
- let filterId = new Filter(query).toString()
- delete this.cacheBBoxQueries[filterId]
- }
- _abortRequest (request) {
- var p = this.requests.indexOf(request)
- if (p === -1) {
- return
- }
- this.requests[p] = null
- }
- _finishRequest (request) {
- this.requests[this.requests.indexOf(request)] = null
- }
- _next () {
- async.setImmediate(function () {
- this._overpassProcess()
- }.bind(this))
- }
- abortAllRequests () {
- for (var j = 0; j < this.requests.length; j++) {
- if (this.requests[j] === null) {
- continue
- }
- this.requests[j].abort()
- }
- this.requests = []
- }
- removeFromCache (ids) {
- if (typeof ids === 'string') {
- ids = [ ids ]
- }
- for (var i = 0; i < ids.length; i++) {
- if (ids[i] in this.cacheElements) {
- let ob = this.cacheElements[ids[i]]
- // remove all memberOf references
- if (ob.members) {
- ob.members.forEach(member => {
- let memberOb = this.cacheElements[member.id]
- memberOb.memberOf = memberOb.memberOf
- .filter(memberOf => memberOf.id !== ob.id)
- })
- }
- let lokiOb = this.cacheElements[ids[i]].dbData
- delete this.cacheElements[ids[i]]
- this.db.remove(lokiOb)
- }
- }
- }
- notifyMemberUpdates () {
- let todo = this.pendingNotifyMemberUpdate
- this.pendingNotifyMemberUpdate = {}
- for (var k in todo) {
- let ob = this.cacheElements[k]
- ob.notifyMemberUpdate(todo[k])
- this.pendingUpdateEmit[ob.id] = ob
- }
- }
- pendingNotifies () {
- this.notifyMemberUpdates()
- let todo = Object.values(this.pendingUpdateEmit)
- this.pendingUpdateEmit = {}
- todo.forEach(ob => {
- ob.emit('update', ob)
- this.db.update(ob.dbInsert())
- })
- }
- createOrUpdateOSMObject (el, options) {
- var id = el.type.substr(0, 1) + el.id
- var ob = null
- let create = true
- if (id in this.cacheElements && !this.cacheElements[id]) {
- console.log('why can this be null?', id)
- }
- if (id in this.cacheElements && this.cacheElements[id]) {
- ob = this.cacheElements[id]
- create = false
- // no new information -> return
- if (~ob.properties & options.properties === 0) {
- return ob
- }
- } else if (el.type === 'relation') {
- ob = new OverpassRelation(id)
- } else if (el.type === 'way') {
- ob = new OverpassWay(id)
- } else if (el.type === 'node') {
- ob = new OverpassNode(id)
- } else {
- ob = new OverpassObject(id)
- }
- ob.overpass = this
- ob.updateData(el, options)
- ob.memberOf.forEach(entry => {
- if (entry.id in this.pendingNotifyMemberUpdate) {
- this.pendingNotifyMemberUpdate[entry.id].push(ob)
- } else {
- this.pendingNotifyMemberUpdate[entry.id] = [ ob ]
- }
- })
- this.pendingUpdateEmit[ob.id] = ob
- if (create) {
- this.db.insert(ob.dbInsert())
- } else {
- this.db.update(ob.dbInsert())
- }
- this.cacheElements[id] = ob
- return ob
- }
- regexpEscape (str) {
- return str.replace('\\', '\\\\')
- .replace('.', '\\.')
- .replace('|', '\\|')
- .replace('[', '\\[')
- .replace(']', '\\]')
- .replace('(', '\\(')
- .replace(')', '\\)')
- .replace('{', '\\{')
- .replace('}', '\\}')
- .replace('?', '\\?')
- .replace('+', '\\+')
- .replace('*', '\\*')
- .replace('^', '\\^')
- .replace('$', '\\$')
- }
- }
- for (var k in defines) {
- OverpassFrontend[k] = defines[k]
- }
- function isSeparator (el) {
- return ('count' in el || ('type' in el && el.type === 'count'))
- }
- ee(OverpassFrontend.prototype)
- OverpassFrontend.Filter = Filter
- module.exports = OverpassFrontend
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./Filter":179,"./OverpassNode":181,"./OverpassObject":182,"./OverpassRelation":183,"./OverpassWay":184,"./RequestBBox":186,"./RequestGet":188,"./copyOsm3sMeta":192,"./defines":193,"./httpLoad":195,"./loadOsmFile":197,"./removeNullEntries":199,"async":19,"boundingbox":20,"event-emitter":41,"lokijs":172,"weight-sort":208}],181:[function(require,module,exports){
- /* global L:false */
- var OverpassObject = require('./OverpassObject')
- var BoundingBox = require('boundingbox')
- var OverpassFrontend = require('./defines')
- /**
- * A node
- * @extends OverpassObject
- * @property {string} id ID of this object, starting with 'n'.
- * @property {number} osm_id Numeric id.
- * @property {string} type Type: 'node'
- * @property {object} tags OpenStreetMap tags.
- * @property {object} meta OpenStreetMap meta information.
- * @property {Point} geometry of the object
- * @property {object} data Data as loaded from Overpass API.
- * @property {bit_array} properties Which information about this object is known?
- * @property {object[]} memberOf List of ways and relations where this object is member of.
- * @property {string} memberOf.id ID of the way or relation where this way is member of.
- * @property {string} memberOf.role Role of this object in the relation.
- * @property {number} memberOf.sequence This object is the nth member in the way resp. relation.
- * @property {BoundingBox} bounds Bounding box of this object.
- * @property {Point} center Centroid of the bounding box.
- */
- class OverpassNode extends OverpassObject {
- GeoJSON () {
- let result = {
- type: 'Feature',
- id: this.type + '/' + this.osm_id,
- properties: this.GeoJSONProperties()
- }
- if (this.geometry) {
- result.geometry = {
- type: 'Point',
- coordinates: [ this.geometry.lon, this.geometry.lat ]
- }
- }
- return result
- }
- exportOSMXML (options, document, callback) {
- super.exportOSMXML(options, document,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- result.setAttribute('lat', this.geometry.lat)
- result.setAttribute('lon', this.geometry.lon)
- callback(null, result)
- }
- )
- }
- exportOSMJSON (conf, elements, callback) {
- super.exportOSMJSON(conf, elements,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- result.lat = this.geometry.lat
- result.lon = this.geometry.lon
- callback(null, result)
- }
- )
- }
- updateData (data, options) {
- super.updateData(data, options)
- if (data.lat) {
- this.geometry = {
- lat: data.lat,
- lon: data.lon
- }
- this.bounds = new BoundingBox(data)
- this.center = this.bounds.getCenter()
- this.properties = this.properties | OverpassFrontend.GEOM | OverpassFrontend.BBOX | OverpassFrontend.CENTER
- }
- }
- /**
- * return a leaflet feature for this object
- * @param {object} [options] options Options will be passed to the leaflet function
- * @param {string} [options.nodeFeature='CircleMarker'] Which type of object should be returned: 'Marker' (L.marker), 'Circle' (L.circle) or 'CircleMarker' (L.circleMarker).
- * @return {L.layer}
- */
- leafletFeature (options) {
- if (!this.geometry) {
- return null
- }
- switch ('nodeFeature' in options ? options.nodeFeature : null) {
- case 'Marker':
- return L.marker(this.geometry, options)
- case 'Circle':
- return L.circle(this.geometry, options.radius, options)
- case 'CircleMarker':
- default:
- return L.circleMarker(this.geometry, options)
- }
- }
- intersects (bbox) {
- if (!this.bounds) {
- return 1
- }
- return bbox.intersects(this.bounds) ? 2 : 0
- }
- }
- module.exports = OverpassNode
- },{"./OverpassObject":182,"./defines":193,"boundingbox":20}],182:[function(require,module,exports){
- const ee = require('event-emitter')
- var BoundingBox = require('boundingbox')
- var OverpassFrontend = require('./defines')
- var turf = {
- difference: require('@turf/difference'),
- intersect: require('@turf/intersect').default
- }
- /**
- * Base class for representing map features.
- * @property {string} id ID of this object.
- * @property {number} osm_id Numeric id.
- * @property {string} type Type: 'node', 'way' or 'relation'.
- * @property {object} tags OpenStreetMap tags.
- * @property {object} meta OpenStreetMap meta information.
- * @property {object} geometry of the object
- * @property {object} data Data as loaded from Overpass API.
- * @property {bit_array} properties Which information about this object is known?
- * @property {object[]} memberOf List of ways and relations where this object is member of.
- * @property {string} memberOf.id ID of the way or relation where this way is member of.
- * @property {string} memberOf.role Role of this object in the relation.
- * @property {number} memberOf.sequence This object is the nth member in the way resp. relation.
- * @property {BoundingBox} bounds Bounding box of this object.
- * @property {Point} center Centroid of the bounding box.
- */
- class OverpassObject {
- constructor () {
- this.data = {}
- this.properties = 0
- this.memberOf = []
- }
- memberIds () {
- return []
- }
- member_ids () { // eslint-disable-line
- console.log('called deprecated OverpassObject.member_ids() function - replace by memberIds()')
- return this.memberIds()
- }
- notifyMemberOf (relation, role, sequence) {
- this.memberOf.push({ id: relation.id, role, sequence })
- }
- updateData (data, options) {
- if (typeof this.id === 'undefined') {
- this.id = data.type.substr(0, 1) + data.id
- this.type = data.type
- this.osm_id = data.id
- }
- this.osm3sMeta = options.osm3sMeta
- for (var k in data) {
- this.data[k] = data[k]
- }
- if (data.bounds) {
- this.bounds = new BoundingBox(data.bounds)
- this.center = this.bounds.getCenter()
- this.diagonalLength = this.bounds.diagonalLength()
- } else if (data.center) {
- this.bounds = new BoundingBox(data.center)
- this.center = this.bounds.getCenter()
- }
- if (options.bbox) {
- if (!this.bounds || options.bbox.intersects(this.bounds)) {
- this.properties = this.properties | options.properties
- } else {
- this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
- }
- } else {
- this.properties = this.properties | options.properties
- }
- // result of a request with bbox limitation, where the object was outside
- if (options.bboxNoMatch && this.bounds) {
- // this.boundsPossibleMatch: record unsucessful bbox requests for an object
- if (typeof this.boundsPossibleMatch === 'undefined') {
- this.boundsPossibleMatch = this.bounds.toGeoJSON()
- }
- this.boundsPossibleMatch = turf.difference(this.boundsPossibleMatch, options.bbox.toGeoJSON())
- }
- // geometry is known -> no need for this.boundsPossibleMatch
- if (this.geometry) {
- delete this.boundsPossibleMatch
- }
- if (options.properties & OverpassFrontend.TAGS) {
- if (typeof data.tags === 'undefined') {
- this.tags = {}
- } else {
- this.tags = data.tags
- }
- }
- this.errors = []
- if (data.timestamp) {
- this.meta = {
- timestamp: data.timestamp,
- version: data.version,
- changeset: data.changeset,
- user: data.user,
- uid: data.uid
- }
- }
- if (data.tags) {
- this.tags = data.tags
- }
- }
- notifyMemberUpdate (memberObs) {
- }
- /**
- * Title of of this object (default: name, operator or ref or the id of the object)
- * @return {string}
- */
- title () {
- if (!this.tags) {
- return this.id
- }
- return this.tags.name || this.tags.operator || this.tags.ref || this.id
- }
- /**
- * GeoJSON representation of this object
- * @return {object}
- */
- GeoJSON () {
- return {
- type: 'Feature',
- id: this.type + '/' + this.osm_id,
- geometry: null,
- properties: this.GeoJSONProperties()
- }
- }
- GeoJSONProperties () {
- var ret = {}
- var k
- ret['@id'] = this.type + '/' + this.osm_id
- if (this.tags) {
- for (k in this.tags) {
- ret[k] = this.tags[k]
- }
- }
- if (this.meta) {
- for (k in this.meta) {
- ret['@' + k] = this.meta[k]
- }
- }
- for (k in this.osm3sMeta) {
- ret['@osm3s:' + k] = this.osm3sMeta[k]
- }
- return ret
- }
- /**
- * Export object as GeoJSON. Missing geometry will be loaded.
- * @param object options Options
- * @param function callback Function which will be called with (err, result)
- */
- exportGeoJSON (options, callback) {
- this.overpass.get(
- this.id,
- {
- properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META | OverpassFrontend.GEOM
- },
- () => {},
- (err) => {
- if (err) {
- return callback(err)
- }
- callback(null, this.GeoJSON(options))
- }
- )
- }
- /**
- * Export object (and members) as OpenStreetMap XML
- * @param object options Options
- * @param DOMNode parentNode a DOM Node where the object will be appended as child. Depending on object type and options, member objects will also be appended on the same level.
- * @param function callback Function which will be called with (err, dom node)
- */
- exportOSMXML (options, parentNode, callback) {
- if (!parentNode._alreadyIncluded) {
- parentNode._alreadyIncluded = {}
- }
- if (this.id in parentNode._alreadyIncluded) {
- return callback(null)
- }
- parentNode._alreadyIncluded[this.id] = true
- if ((this.properties & (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) !== (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) {
- return this.overpass.get(
- this.id,
- {
- properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META
- },
- () => {},
- (err) => {
- if (err) {
- return callback(err)
- }
- this._exportOSMXML(options, parentNode, callback)
- }
- )
- }
- this._exportOSMXML(options, parentNode, callback)
- }
- _exportOSMXML (options, parentNode, callback) {
- let result = parentNode.ownerDocument.createElement(this.type)
- result.setAttribute('id', this.osm_id)
- if (this.meta) {
- result.setAttribute('version', this.meta.version)
- result.setAttribute('timestamp', this.meta.timestamp)
- result.setAttribute('changeset', this.meta.changeset)
- result.setAttribute('uid', this.meta.uid)
- result.setAttribute('user', this.meta.user)
- }
- if (this.tags) {
- for (var k in this.tags) {
- let tag = parentNode.ownerDocument.createElement('tag')
- tag.setAttribute('k', k)
- tag.setAttribute('v', this.tags[k])
- result.appendChild(tag)
- }
- }
- parentNode.appendChild(result)
- callback(null, result)
- }
- /**
- * Export object (and members) as OpenStreetMap JSON
- * @param object options Options
- * @param object elements All exported elements, include member objects. Pass an empty object. If a member element would be exported multiple times it will appear only once. For the final export, to be compatible to Overpass API, you should convert the object to an array via Object.values().
- * @param function callback Function which will be called with (err, result)
- */
- exportOSMJSON (conf, elements, callback) {
- if (this.id in elements) {
- return callback(null)
- }
- elements[this.id] = {}
- if ((this.properties & (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) !== (OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META)) {
- return this.overpass.get(
- this.id,
- {
- properties: OverpassFrontend.TAGS | OverpassFrontend.MEMBERS | OverpassFrontend.META
- },
- () => {},
- (err) => {
- if (err) {
- return callback(err)
- }
- this._exportOSMJSON(conf, elements, callback)
- }
- )
- }
- this._exportOSMJSON(conf, elements, callback)
- }
- _exportOSMJSON (conf, elements, callback) {
- let result = elements[this.id]
- result.type = this.type
- result.id = this.osm_id
- if (this.meta) {
- result.version = this.meta.version
- result.timestamp = this.meta.timestamp
- result.changeset = this.meta.changeset
- result.uid = this.meta.uid
- result.user = this.meta.user
- }
- if (this.tags && Object.keys(this.tags).length) {
- result.tags = this.tags
- }
- callback(null, result)
- }
- /**
- * Check whether this object intersects (or is within) the specified bounding box. Returns 0 if it does not match; 1 if the exact geometry is not known, but the object's bounding box matches; 2 exact match.
- * @param {boundingbox:BoundingBox} bbox Bounding box
- * @return {number}
- */
- intersects (bbox) {
- if (!this.bounds) {
- return 0
- }
- if (!bbox.intersects(this.bounds)) {
- return 0
- }
- if (this.boundsPossibleMatch) {
- var remaining = turf.intersect(bbox.toGeoJSON(), this.boundsPossibleMatch)
- if (!remaining || remaining.geometry.type !== 'Polygon') {
- // geometry.type != Polygon: bbox matches border of this.boundsPossibleMatch
- return 0
- }
- return 1
- }
- return 1
- }
- /**
- * return a leaflet feature for this object.
- * @param {object} [options] options Options will be passed to the leaflet function
- * @return {L.layer}
- */
- leafletFeature (options) {
- return null
- }
- dbInsert () {
- if (!this.dbData) {
- this.dbData = {}
- }
- this.dbData.tags = this.tags
- this.dbData.osmMeta = this.meta
- this.dbData.id = this.id
- this.dbData.type = this.type
- if (this.bounds && this.bounds.minlat) {
- this.dbData.minlat = this.bounds.minlat
- this.dbData.minlon = this.bounds.minlon
- this.dbData.maxlat = this.bounds.maxlat
- this.dbData.maxlon = this.bounds.maxlon
- }
- return this.dbData
- }
- }
- ee(OverpassObject.prototype)
- module.exports = OverpassObject
- },{"./defines":193,"@turf/difference":9,"@turf/intersect":12,"boundingbox":20,"event-emitter":41}],183:[function(require,module,exports){
- /* global L:false */
- const async = require('async')
- var BoundingBox = require('boundingbox')
- var osmtogeojson = require('osmtogeojson')
- var OverpassObject = require('./OverpassObject')
- var OverpassFrontend = require('./defines')
- var turf = {
- bboxClip: require('@turf/bbox-clip').default
- }
- /**
- * A relation
- * @property {string} id ID of this object, starting with 'r'.
- * @property {number} osm_id Numeric id.
- * @property {string} type Type: 'relation'.
- * @property {object} tags OpenStreetMap tags.
- * @property {object} meta OpenStreetMap meta information.
- * @property {GeoJSON} geometry of the object
- * @property {object} data Data as loaded from Overpass API.
- * @property {bit_array} properties Which information about this object is known?
- * @property {object[]} memberOf List of relations where this object is member of.
- * @property {string} memberOf.id ID of the relation where this object is member of.
- * @property {string} memberOf.role Role of this object in the relation.
- * @property {number} memberOf.sequence This object is the nth member in the relation.
- * @property {null|string} memberOf.connectedPrev null (unknown), 'no' (connected), 'forward' (connected at the front end of this way), 'backward' (connected at the back end of this way)
- * @property {null|string} memberOf.connectedNext null (unknown), 'no' (connected), 'forward' (connected at the back end of this way), 'backward' (connected at the front end of this way)
- * @property {null|string} members.dir null (unknown), 'forward', 'backward'
- * @property {BoundingBox} bounds Bounding box of this object.
- * @property {Point} center Centroid of the bounding box.
- * @property {object[]} members Nodes of the way.
- * @property {string} members.id ID of the member.
- * @property {number} members.ref Numeric ID of the member.
- * @property {string} members.type 'node'.
- * @property {string} members.role Role of the member.
- * @property {null|string} members.connectedPrev null (unknown), 'no' (connected), 'forward' (connected at the front end of this way), 'backward' (connected at the back end of this way)
- * @property {null|string} members.connectedNext null (unknown), 'no' (connected), 'forward' (connected at the back end of this way), 'backward' (connected at the fornt end of this way)
- * @property {null|string} members.dir null (unknown), 'forward', 'backward', 'loop'
- */
- class OverpassRelation extends OverpassObject {
- updateData (data, options) {
- var i
- super.updateData(data, options)
- if ((options.properties & OverpassFrontend.MEMBERS) &&
- data.members) {
- this.members = []
- for (i = 0; i < data.members.length; i++) {
- var member = data.members[i]
- this.members.push(member)
- this.members[i].id = member.type.substr(0, 1) + member.ref
- }
- }
- if (options.properties & OverpassFrontend.MEMBERS) {
- let membersKnown = !!this.memberFeatures
- this.memberFeatures = data.members.map(
- (member, sequence) => {
- let ob = JSON.parse(JSON.stringify(member))
- ob.id = ob.ref
- delete ob.ref
- delete ob.role
- let memberOb = this.overpass.createOrUpdateOSMObject(ob, {
- properties: options.properties & OverpassFrontend.GEOM
- })
- // call notifyMemberOf only once per member
- if (!membersKnown) {
- memberOb.notifyMemberOf(this, member.role, sequence)
- }
- return memberOb
- }
- )
- }
- if ((options.properties & OverpassFrontend.MEMBERS) &&
- (options.properties & OverpassFrontend.GEOM) &&
- data.members) {
- let elements = [ JSON.parse(JSON.stringify(data)) ]
- this.geometry = osmtogeojson({ elements })
- } else if ((options.properties & OverpassFrontend.MEMBERS) &&
- data.members) {
- this.updateGeometry()
- }
- }
- updateGeometry () {
- if (!this.members) {
- return
- }
- let allKnown = true
- let elements = [ {
- type: 'relation',
- id: this.osm_id,
- tags: this.tags,
- members: this.members.map(member => {
- let data = {
- ref: member.ref,
- type: member.type,
- role: member.role
- }
- if (!(member.id in this.overpass.cacheElements)) {
- allKnown = false
- return data
- }
- let ob = this.overpass.cacheElements[member.id]
- if ((ob.properties & OverpassFrontend.GEOM) === 0) {
- allKnown = false
- }
- if (ob.type === 'node') {
- if (ob.geometry) {
- data.lat = ob.geometry.lat
- data.lon = ob.geometry.lon
- }
- } else if (ob.type === 'way') {
- data.geometry = ob.geometry
- }
- return data
- })
- } ]
- this.geometry = osmtogeojson({ elements })
- if (allKnown) {
- this.properties = this.properties | OverpassFrontend.GEOM
- }
- this.members.forEach(
- (member, index) => {
- if (member.type !== 'way') {
- return
- }
- let memberOb = this.overpass.cacheElements[member.id]
- if (!memberOb.members || member.type !== 'way') {
- return
- }
- let firstMemberId = memberOb.members[0].id
- let lastMemberId = memberOb.members[memberOb.members.length - 1].id
- let revMemberOf = memberOb.memberOf.filter(memberOf => memberOf.sequence === index && memberOf.id === this.id)[0]
- if (index > 0) {
- let prevMember = this.overpass.cacheElements[this.members[index - 1].id]
- if (prevMember.type === 'way' && prevMember.members) {
- if (firstMemberId === prevMember.members[0].id || firstMemberId === prevMember.members[prevMember.members.length - 1].id) {
- member.connectedPrev = 'forward'
- } else if (lastMemberId === prevMember.members[0].id || lastMemberId === prevMember.members[prevMember.members.length - 1].id) {
- member.connectedPrev = 'backward'
- } else {
- member.connectedPrev = 'no'
- }
- }
- }
- if (index < this.members.length - 1) {
- let nextMember = this.overpass.cacheElements[this.members[index + 1].id]
- if (nextMember.type === 'way' && nextMember.members) {
- if (firstMemberId === nextMember.members[0].id || firstMemberId === nextMember.members[nextMember.members.length - 1].id) {
- member.connectedNext = 'backward'
- } else if (lastMemberId === nextMember.members[0].id || lastMemberId === nextMember.members[nextMember.members.length - 1].id) {
- member.connectedNext = 'forward'
- } else {
- member.connectedNext = 'no'
- }
- }
- }
- if (!member.connectedPrev || !member.connectedNext) {
- member.dir = member.connectedPrev || member.connectedNext || null
- } else if (member.connectedPrev === member.connectedNext) {
- member.dir = member.connectedPrev || member.connectedNext || null
- } else {
- member.dir = null
- }
- if (revMemberOf) {
- if ('dir' in member) {
- revMemberOf.dir = member.dir
- }
- if ('connectedPrev' in member) {
- revMemberOf.connectedPrev = member.connectedPrev
- }
- if ('connectedNext' in member) {
- revMemberOf.connectedNext = member.connectedNext
- }
- } else {
- console.log('Warning: memberOf reference ' + member.id + ' -> ' + this.id + ' (#' + index + ') does not exist.')
- }
- }
- )
- if (!this.bounds) {
- this.members.forEach(member => {
- let ob = this.overpass.cacheElements[member.id]
- if (ob.bounds) {
- if (this.bounds) {
- this.bounds.extend(ob.bounds)
- } else {
- this.bounds = new BoundingBox(ob.bounds)
- }
- }
- })
- if (this.bounds && allKnown) {
- this.center = this.bounds.getCenter()
- this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
- }
- }
- }
- notifyMemberUpdate (memberObs) {
- super.notifyMemberUpdate(memberObs)
- if (!this.members) {
- return
- }
- this.updateGeometry()
- }
- /**
- * Return list of member ids.
- * @return {string[]}
- */
- memberIds () {
- if (this._memberIds) {
- return this._memberIds
- }
- if (typeof this.data.members === 'undefined') {
- return null
- }
- this._memberIds = []
- for (var i = 0; i < this.data.members.length; i++) {
- var member = this.data.members[i]
- this._memberIds.push(member.type.substr(0, 1) + member.ref)
- }
- return this._memberIds
- }
- member_ids () { // eslint-disable-line
- console.log('called deprecated OverpassRelation.member_ids() function - replace by memberIds()')
- return this.memberIds()
- }
- /**
- * return a leaflet feature for this object.
- * @param {object} [options] options Options will be passed to the leaflet function
- * @return {L.layer}
- */
- leafletFeature (options) {
- if (!this.data.members) {
- return null
- }
- // no geometry? use the member features instead
- if (!this.geometry) {
- let feature = L.featureGroup()
- feature._updateCallbacks = []
- return feature
- }
- var feature = L.geoJSON(this.geometry, {
- pointToLayer: function (options, geoJsonPoint, member) {
- let feature
- switch (options.nodeFeature) {
- case 'Marker':
- feature = L.marker(member, options)
- break
- case 'Circle':
- feature = L.circle(member, options.radius, options)
- break
- case 'CircleMarker':
- default:
- feature = L.circleMarker(member, options)
- }
- return feature
- }.bind(this, options)
- })
- feature.setStyle(options)
- // create an event handler on the 'update' event, so that loading member
- // features will update geometry
- this.memberFeatures.forEach(
- (member, index) => {
- if (!(member.properties & OverpassFrontend.GEOM)) {
- let updFun = member => {
- feature.clearLayers()
- feature.addData(this.geometry)
- feature.setStyle(options)
- }
- member.once('update', updFun)
- }
- }
- )
- return feature
- }
- GeoJSON () {
- var ret = {
- type: 'Feature',
- id: this.type + '/' + this.osm_id,
- properties: this.GeoJSONProperties()
- }
- if (this.members) {
- if (this.geometry.features.length === 1) {
- ret.geometry = this.geometry.features[0].geometry
- } else {
- ret.geometry = {
- type: 'GeometryCollection',
- geometries: this.memberFeatures
- .map(member => {
- let geojson = member.GeoJSON()
- if ('geometry' in geojson) {
- return geojson.geometry
- }
- })
- .filter(member => member)
- }
- }
- }
- return ret
- }
- exportOSMXML (options, parentNode, callback) {
- super.exportOSMXML(options, parentNode,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- if (this.members) {
- async.each(this.members,
- (member, done) => {
- let memberOb = this.overpass.cacheElements[member.id]
- let nd = parentNode.ownerDocument.createElement('member')
- nd.setAttribute('ref', memberOb.osm_id)
- nd.setAttribute('type', memberOb.type)
- nd.setAttribute('role', member.role)
- result.appendChild(nd)
- memberOb.exportOSMXML(options, parentNode, done)
- },
- (err) => {
- callback(err, result)
- }
- )
- } else {
- callback(null, result)
- }
- }
- )
- }
- exportOSMJSON (conf, elements, callback) {
- super.exportOSMJSON(conf, elements,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- if (this.members) {
- result.members = []
- async.each(this.members,
- (member, done) => {
- let memberOb = this.overpass.cacheElements[member.id]
- result.members.push({
- ref: memberOb.osm_id,
- type: memberOb.type,
- role: member.role
- })
- memberOb.exportOSMJSON(conf, elements, done)
- },
- (err) => {
- callback(err, result)
- }
- )
- } else {
- callback(null, result)
- }
- }
- )
- }
- intersects (bbox) {
- var i
- if (this.bounds) {
- if (!bbox.intersects(this.bounds)) {
- return 0
- }
- }
- if (this.geometry) {
- for (i = 0; i < this.geometry.features.length; i++) {
- var g = this.geometry.features[i]
- if (g.geometry.type === 'Point') {
- if (bbox.intersects(g)) {
- return 2
- }
- continue
- }
- var intersects = turf.bboxClip(g, [ bbox.minlon, bbox.minlat, bbox.maxlon, bbox.maxlat ])
- if (g.geometry.type === 'LineString' || g.geometry.type === 'Polygon') {
- if (intersects.geometry.coordinates.length) {
- return 2
- }
- }
- if (g.geometry.type === 'MultiPolygon' || g.geometry.type === 'MultiLineString') {
- for (var j = 0; j < intersects.geometry.coordinates.length; j++) {
- if (intersects.geometry.coordinates[j].length) {
- return 2
- }
- }
- }
- }
- // if there's a relation member (where Overpass does not return the
- // geometry) we can't know if the geometry intersects -> return 1
- for (i = 0; i < this.data.members.length; i++) {
- if (this.data.members[i].type === 'relation') {
- return 1
- }
- }
- // if there's no relation member we can be sure there's no intersection
- return 0
- } else if (this.members) {
- for (i in this.members) {
- let memberId = this.members[i].id
- let member = this.overpass.cacheElements[memberId]
- if (member) {
- if (member.intersects(bbox) === 2) {
- return 2
- }
- }
- }
- }
- return super.intersects(bbox)
- }
- }
- module.exports = OverpassRelation
- },{"./OverpassObject":182,"./defines":193,"@turf/bbox-clip":3,"async":19,"boundingbox":20,"osmtogeojson":177}],184:[function(require,module,exports){
- /* global L:false */
- const async = require('async')
- var BoundingBox = require('boundingbox')
- var OverpassObject = require('./OverpassObject')
- var OverpassFrontend = require('./defines')
- var turf = {
- bboxClip: require('@turf/bbox-clip').default
- }
- /**
- * A way
- * @property {string} id ID of this object, starting with 'w'.
- * @property {number} osm_id Numeric id.
- * @property {string} type Type: 'way'.
- * @property {object} tags OpenStreetMap tags.
- * @property {object} meta OpenStreetMap meta information.
- * @property {Point[]} geometry of the object
- * @property {object} data Data as loaded from Overpass API.
- * @property {bit_array} properties Which information about this object is known?
- * @property {object[]} memberOf List of relations where this object is member of.
- * @property {string} memberOf.id ID of the relation where this way is member of.
- * @property {string} memberOf.role Role of this object in the relation.
- * @property {number} memberOf.sequence This object is the nth member in the relation.
- * @property {BoundingBox} bounds Bounding box of this object.
- * @property {Point} center Centroid of the bounding box.
- * @property {object[]} members Nodes of the way.
- * @property {string} members.id ID of the member.
- * @property {number} members.ref Numeric ID of the member.
- * @property {string} members.type 'node'.
- */
- class OverpassWay extends OverpassObject {
- updateData (data, options) {
- if (data.nodes) {
- this.nodes = data.nodes
- }
- if (data.geometry) {
- this.geometry = data.geometry
- }
- super.updateData(data, options)
- if (typeof this.data.nodes !== 'undefined') {
- this.members = []
- for (var i = 0; i < this.data.nodes.length; i++) {
- this.members.push({
- id: 'n' + this.data.nodes[i],
- ref: this.data.nodes[i],
- type: 'node'
- })
- let obProperties = OverpassFrontend.ID_ONLY
- let ob = {
- id: this.data.nodes[i],
- type: 'node'
- }
- if (data.geometry) {
- obProperties = obProperties | OverpassFrontend.GEOM
- ob.lat = data.geometry[i].lat
- ob.lon = data.geometry[i].lon
- }
- let memberOb = this.overpass.createOrUpdateOSMObject(ob, {
- properties: obProperties
- })
- memberOb.notifyMemberOf(this, null, i)
- }
- if (!this.geometry) {
- this.geometry = this.members.map(
- member => {
- let node = this.overpass.cacheElements[member.id]
- if (node) {
- return node.geometry
- }
- }
- )
- this.geometry = this.geometry.filter(geom => geom)
- if (!this.geometry.length) {
- delete this.geometry
- }
- }
- }
- if (this.geometry && this.geometry.filter(geom => geom).length === this.geometry.length) {
- this.properties = this.properties | OverpassFrontend.GEOM
- if (!this.bounds) {
- this.bounds = new BoundingBox(this.geometry[0])
- this.geometry.slice(1).forEach(geom => this.bounds.extend(geom))
- this.center = this.bounds.getCenter()
- this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.CENTER
- }
- }
- }
- notifyMemberUpdate (memberObs) {
- super.notifyMemberUpdate(memberObs)
- if (!this.members) {
- return
- }
- memberObs.forEach(memberOb => {
- this.members.forEach((member, index) => {
- if (memberOb.id === member.id) {
- if (memberOb.geometry) {
- if (!this.geometry) {
- this.geometry = new Array(this.members.length)
- }
- this.geometry[index] = memberOb.geometry
- }
- }
- if (this.bounds) {
- this.bounds.extend(memberOb.geometry)
- } else {
- this.bounds = new BoundingBox(memberOb.geometry)
- }
- })
- })
- // all nodes known -> set bbox, geom and center
- if (this.geometry && this.geometry.filter(geom => geom).length === this.geometry.length) {
- this.center = this.bounds.getCenter()
- this.properties = this.properties | OverpassFrontend.BBOX | OverpassFrontend.GEOM | OverpassFrontend.CENTER
- }
- }
- memberIds () {
- if (this._memberIds) {
- return this._memberIds
- }
- if (!this.nodes) {
- return null
- }
- this._memberIds = []
- for (var i = 0; i < this.nodes.length; i++) {
- var member = this.nodes[i]
- this._memberIds.push('n' + member)
- }
- return this._memberIds
- }
- member_ids () { // eslint-disable-line
- console.log('called deprecated OverpassWay.member_ids() function - replace by memberIds()')
- return this.memberIds()
- }
- GeoJSON () {
- var result = {
- type: 'Feature',
- id: this.type + '/' + this.osm_id,
- properties: this.GeoJSONProperties()
- }
- if (this.geometry) {
- let coordinates = this.geometry
- .filter(point => point) // discard non-loaded points
- .map(point => [ point.lon, point.lat ])
- let isClosed = this.members && this.members[0].id === this.members[this.members.length - 1].id
- if (isClosed) {
- result.geometry = {
- type: 'Polygon',
- coordinates: [ coordinates ]
- }
- } else {
- result.geometry = {
- type: 'LineString',
- coordinates: coordinates
- }
- }
- }
- return result
- }
- exportOSMXML (options, parentNode, callback) {
- super.exportOSMXML(options, parentNode,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- if (this.members) {
- async.each(this.members,
- (member, done) => {
- let memberOb = this.overpass.cacheElements[member.id]
- let nd = parentNode.ownerDocument.createElement('nd')
- nd.setAttribute('ref', memberOb.osm_id)
- result.appendChild(nd)
- memberOb.exportOSMXML(options, parentNode, done)
- },
- (err) => {
- callback(err, result)
- }
- )
- } else {
- callback(null, result)
- }
- }
- )
- }
- exportOSMJSON (conf, elements, callback) {
- super.exportOSMJSON(conf, elements,
- (err, result) => {
- if (err) {
- return callback(err)
- }
- if (!result) { // already included
- return callback(null)
- }
- if (this.members) {
- result.nodes = []
- async.each(this.members,
- (member, done) => {
- let memberOb = this.overpass.cacheElements[member.id]
- result.nodes.push(memberOb.osm_id)
- memberOb.exportOSMJSON(conf, elements, done)
- },
- (err) => {
- callback(err, result)
- }
- )
- } else {
- callback(null, result)
- }
- }
- )
- }
- /**
- * return a leaflet feature for this object. If the ways is closed, a L.polygon will be returned, otherwise a L.polyline.
- * @param {object} [options] options Options will be passed to the leaflet function
- * @return {L.layer}
- */
- leafletFeature (options) {
- if (!this.geometry) {
- return null
- }
- if (this.geometry[this.geometry.length - 1].lat === this.geometry[0].lat &&
- this.geometry[this.geometry.length - 1].lon === this.geometry[0].lon) {
- return L.polygon(this.geometry, options)
- }
- return L.polyline(this.geometry, options)
- }
- intersects (bbox) {
- if (this.bounds) {
- if (!bbox.intersects(this.bounds)) {
- return 0
- }
- }
- if (this.geometry) {
- var intersects = turf.bboxClip(this.GeoJSON(), [ bbox.minlon, bbox.minlat, bbox.maxlon, bbox.maxlat ])
- return intersects.geometry.coordinates.length ? 2 : 0
- }
- return super.intersects(bbox)
- }
- }
- module.exports = OverpassWay
- },{"./OverpassObject":182,"./defines":193,"@turf/bbox-clip":3,"async":19,"boundingbox":20}],185:[function(require,module,exports){
- const ee = require('event-emitter')
- const SortedCallbacks = require('./SortedCallbacks')
- /**
- * A compiled query
- * @typedef {Object} Request#SubRequest
- * @property {string} query - The compiled code
- * @property {object[]} parts - An entry for each part (separated by the 'out count' separator)
- * @property {int} parts[].properties - The properties which each returned map feature has set (TAGS, BBOX, ...)
- * @property {int} effort - Supposed "effort" of this query
- * @property {Request} request - The request this compiled query belongs to
- */
- /**
- * An unspecified request
- * @param {OverpassFrontend} overpass
- * @param {object} options
- */
- class Request {
- constructor (overpass, data) {
- this.overpass = overpass
- for (var k in data) {
- this[k] = data[k]
- }
- if (!this.options) {
- this.options = {}
- }
- this.priority = 'priority' in this.options ? this.options.priority : 0
- var callbacks = new SortedCallbacks(this.options, this.featureCallback, this.finalCallback)
- this.featureCallback = callbacks.next.bind(callbacks)
- this.finalCallback = callbacks.final.bind(callbacks)
- this.callCount = 0
- }
- /**
- * Request got aborted
- * @event Request#abort
- */
- /**
- * abort this request
- */
- abort () {
- this.aborted = true
- this.emit('abort')
- this.overpass._abortRequest(this)
- }
- /**
- * Request is finished
- * @event Request#finish
- * @param {Error|null} - null if no error occured
- */
- /**
- * request is finished
- * @param {Error|null} err - null if no error occured
- */
- finish (err) {
- if (!this.aborted) {
- this.finalCallback(err)
- }
- this.overpass._finishRequest(this)
- this.finished = true
- this.emit('finish', err)
- }
- /**
- * shall this Request be included in the current call?
- * @param {OverpassFrontend#Context} context - Current context
- * @return {boolean} - yes|no
- */
- willInclude (context) {
- return true
- }
- /**
- * @typedef {Object} Request#minMaxEffortResult
- * @property {number} Remaining minimal effort of this request
- * @property {number|null} Remaining maximum effort (or null if unknown)
- */
- /**
- * how much effort can a call to this request use
- * @return {Request#minMaxEffortResult} - minimum and maximum effort
- */
- minMaxEffort () {
- return { minEffort: 0, maxEffort: 0 }
- }
- /**
- * SubRequest got compiled
- * @event Request#subrequest-compiile
- * @param {Request#SubRequest} subRequest - the sub request
- */
- /**
- * compile the query
- * @param {OverpassFrontend#Context} context - Current context
- * @return {Request#SubRequest} - the compiled query
- */
- compileQuery (context) {
- let subRequest = this._compileQuery(context)
- this.emit('subrequest-compile', subRequest)
- this.callCount++
- return subRequest
- }
- /**
- * receive an object from OverpassFronted -> enter to cache, return to caller
- * @param {OverpassObject} ob - Object which has been received
- * @param {Request#SubRequest} subRequest - sub request which is being handled right now
- * @param {int} partIndex - Which part of the subRequest is being received
- */
- receiveObject (ob) {
- }
- /**
- * SubRequest got finished
- * @event Request#subrequest-finished
- * @param {Request#SubRequest} subRequest - the sub request
- */
- /**
- * the current subrequest is finished -> update caches, check whether request is finished
- * @param {Request#SubRequest} subRequest - the current sub request
- */
- finishSubRequest (subRequest) {
- this.emit('subrequest-finish', subRequest)
- }
- }
- ee(Request.prototype)
- module.exports = Request
- },{"./SortedCallbacks":190,"event-emitter":41}],186:[function(require,module,exports){
- const Request = require('./Request')
- const overpassOutOptions = require('./overpassOutOptions')
- const defines = require('./defines')
- const KnownArea = require('./knownArea')
- const RequestBBoxMembers = require('./RequestBBoxMembers')
- const Filter = require('./Filter')
- /**
- * A BBox request
- * @extends Request
- */
- class RequestBBox extends Request {
- /**
- * @param {OverpassFrontend} overpass
- * @param {object} options
- */
- constructor (overpass, data) {
- super(overpass, data)
- this.type = 'BBoxQuery'
- if (typeof this.options.properties === 'undefined') {
- this.options.properties = defines.DEFAULT
- }
- this.options.properties |= defines.BBOX
- this.options.minEffort = this.options.minEffort || 256
- // make sure the request ends with ';'
- if (!this.query.match(/;\s*$/)) {
- this.query += ';'
- }
- if ((typeof this.options.filter !== 'undefined') && !(this.options.filter instanceof Filter)) {
- this.options.filter = new Filter(this.options.filter)
- }
- let filterId = null
- if (this.options.filter) {
- filterId = this.options.filter.toString()
- }
- if (!('noCacheQuery' in this.options) || !this.options.noCacheQuery) {
- this.filterQuery = new Filter(this.query)
- this.lokiQuery = this.filterQuery.toLokijs()
- this.lokiQueryNeedMatch = !!this.lokiQuery.needMatch
- delete this.lokiQuery.needMatch
- if (this.options.filter) {
- let filterLokiQuery = this.options.filter.toLokijs()
- this.lokiQueryFilterNeedMatch = !!filterLokiQuery.needMatch
- delete filterLokiQuery.needMatch
- this.lokiQuery = { $and: [ this.lokiQuery, filterLokiQuery ] }
- }
- this.lokiQuery.minlat = { $lte: this.bounds.maxlat }
- this.lokiQuery.minlon = { $lte: this.bounds.maxlon }
- this.lokiQuery.maxlat = { $gte: this.bounds.minlat }
- this.lokiQuery.maxlon = { $gte: this.bounds.minlon }
- }
- this.loadFinish = false
- this.lastChecked = 0
- if ('members' in this.options) {
- RequestBBoxMembers(this)
- }
- if (this.query in this.overpass.cacheBBoxQueries) {
- this.cache = this.overpass.cacheBBoxQueries[this.query]
- if (filterId) {
- if (!('filter' in this.cache)) {
- this.cache.filter = {}
- }
- if (!(filterId in this.cache.filter)) {
- this.cache.filter[filterId] = new KnownArea()
- }
- this.cacheFilter = this.cache.filter[filterId]
- }
- } else {
- // otherwise initialize cache
- this.overpass.cacheBBoxQueries[this.query] = {}
- this.cache = this.overpass.cacheBBoxQueries[this.query]
- this.cache.requested = new KnownArea()
- this.cache.timestamp = 0
- if (filterId) {
- this.cache.filter = {}
- this.cache.filter[filterId] = new KnownArea()
- this.cacheFilter = this.cache.filter[filterId]
- }
- }
- }
- /**
- * check if there are any map features which can be returned right now
- */
- preprocess () {
- if (this.lastChecked > this.cache.timestamp) {
- if (!this.needLoad()) {
- return
- }
- }
- this.lastChecked = new Date().getTime()
- var items = []
- if (this.lokiQuery) {
- items = this.overpass.db.find(this.lokiQuery)
- }
- for (var i = 0; i < items.length; i++) {
- var id = items[i].id
- if (!(id in this.overpass.cacheElements)) {
- continue
- }
- var ob = this.overpass.cacheElements[id]
- if (id in this.doneFeatures) {
- continue
- }
- // maybe we need an additional check
- if (this.lokiQueryNeedMatch && !this.filterQuery.match(ob)) {
- continue
- }
- if (this.lokiQueryFilterNeedMatch && !this.options.filter.match(ob)) {
- continue
- }
- // also check the object directly if it intersects the bbox - if possible
- if (ob.intersects(this.bounds) < 2) {
- continue
- }
- if ((this.options.properties & ob.properties) === this.options.properties) {
- this.doneFeatures[id] = ob
- this.featureCallback(null, ob)
- }
- }
- }
- /**
- * shall this Request be included in the current call?
- * @param {OverpassFrontend#Context} context - Current context
- * @return {boolean|int[]} - yes|no - or [ minEffort, maxEffort ]
- */
- willInclude (context) {
- if (this.loadFinish) {
- return false
- }
- if (context.bbox && context.bbox.toLatLonString() !== this.bounds.toLatLonString()) {
- return false
- }
- context.bbox = this.bounds
- for (let i in context.requests) {
- let request = context.requests[i]
- if (request instanceof RequestBBox && request.query === this.query) {
- return false
- }
- }
- return true
- }
- /**
- * how much effort can a call to this request use
- * @return {Request#minMaxEffortResult} - minimum and maximum effort
- */
- minMaxEffort () {
- if (this.loadFinish) {
- return { minEffort: 0, maxEffort: 0 }
- }
- return { minEffort: this.options.minEffort, maxEffort: null }
- }
- /**
- * compile the query
- * @param {OverpassFrontend#Context} context - Current context
- * @return {Request#SubRequest|false} - the compiled query or false if the bbox does not match
- */
- _compileQuery (context) {
- if (this.loadFinish || (context.bbox && context.bbox.toLatLonString() !== this.bounds.toLatLonString())) {
- return {
- query: '',
- request: this,
- parts: [],
- effort: 0
- }
- }
- let effortAvailable = Math.max(context.maxEffort, this.options.minEffort)
- // if the context already has a bbox and it differs from this, we can't add
- // ours
- var query = '(' + this.query + ')->.result;\n'
- var queryRemoveDoneFeatures = ''
- var countRemoveDoneFeatures = 0
- for (var id in this.doneFeatures) {
- var ob = this.doneFeatures[id]
- if (countRemoveDoneFeatures % 1000 === 999) {
- query += '(' + queryRemoveDoneFeatures + ')->.done;\n'
- queryRemoveDoneFeatures = '.done;'
- }
- queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
- countRemoveDoneFeatures++
- }
- if (countRemoveDoneFeatures) {
- query += '(' + queryRemoveDoneFeatures + ')->.done;\n'
- query += '(.result; - .done;)->.result;\n'
- }
- if (this.options.filter) {
- query += this.options.filter.toQl({
- inputSet: '.result'
- }) + '->.result;\n'
- }
- if (!('split' in this.options)) {
- this.options.effortSplit = Math.ceil(effortAvailable / 4)
- }
- query += '.result out ' + overpassOutOptions(this.options) + ';'
- var subRequest = {
- query,
- request: this,
- parts: [
- {
- properties: this.options.properties,
- receiveObject: this.receiveObject.bind(this),
- featureCallback: this.featureCallback
- }
- ],
- effort: this.options.split ? this.options.split * 4 : effortAvailable // TODO: configure bbox effort
- }
- return subRequest
- }
- /**
- * receive an object from OverpassFronted -> enter to cache, return to caller
- * @param {OverpassObject} ob - Object which has been received
- * @param {Request#SubRequest} subRequest - sub request which is being handled right now
- * @param {int} partIndex - Which part of the subRequest is being received
- */
- receiveObject (ob) {
- this.doneFeatures[ob.id] = ob
- }
- /**
- * the current subrequest is finished -> update caches, check whether request is finished
- * @param {Request#SubRequest} subRequest - the current sub request
- */
- finishSubRequest (subRequest) {
- super.finishSubRequest(subRequest)
- this.cache.timestamp = new Date().getTime()
- if (('effortSplit' in this.options && this.options.effortSplit > subRequest.parts[0].count) ||
- (this.options.split > subRequest.parts[0].count)) {
- this.loadFinish = true
- if (this.options.filter) {
- this.cacheFilter.add(this.remainingBounds)
- } else {
- this.cache.requested.add(this.remainingBounds)
- }
- }
- }
- /**
- * check if we need to call Overpass API. Maybe whole area is cached anyway?
- * @return {boolean} - true, if we need to call Overpass API
- */
- needLoad () {
- if (this.loadFinish) {
- return false
- }
- // check if we need to call Overpass API (whole area known?)
- if (this.options.filter && this.cacheFilter.check(this.bounds)) {
- return false
- }
- return !this.cache.requested.check(this.bounds)
- }
- mayFinish () {
- return !this.needLoad()
- }
- }
- module.exports = RequestBBox
- },{"./Filter":179,"./Request":185,"./RequestBBoxMembers":187,"./defines":193,"./knownArea":196,"./overpassOutOptions":198}],187:[function(require,module,exports){
- const defines = require('./defines')
- const overpassOutOptions = require('./overpassOutOptions')
- const each = require('lodash/forEach')
- const map = require('lodash/map')
- const keys = require('lodash/keys')
- const BoundingBox = require('boundingbox')
- const SortedCallbacks = require('./SortedCallbacks')
- class RequestBBoxMembers {
- constructor (request) {
- this.master = request
- this.options = this.master.options
- this.overpass = this.master.overpass
- this.options.properties |= defines.MEMBERS
- this.options.memberProperties = this.options.memberProperties || defines.DEFAULT
- this.options.memberProperties |= defines.BBOX
- if (this.options.memberBounds) {
- this.bounds = new BoundingBox(this.options.memberBounds)
- }
- this.master._compileQuery = this._compileQuery.bind(this, this.master._compileQuery)
- this.master.needLoad = this.needLoad.bind(this, this.master.needLoad)
- this.master.mayFinish = this.mayFinish.bind(this, this.master.mayFinish)
- this.master.preprocess = this.preprocess.bind(this, this.master.preprocess)
- this.master.willInclude = this.willInclude.bind(this, this.master.willInclude)
- this.master.minMaxEffort = this.minMaxEffort.bind(this, this.master.minMaxEffort)
- this.master.finishSubRequest = this.finishSubRequest.bind(this, this.master.finishSubRequest)
- this.master.featureCallback = this.receiveMasterObject.bind(this, this.master.featureCallback)
- this.doneFeatures = {}
- this.relations = {}
- this.currentRelations = []
- this.todo = {}
- this.loadFinish = true
- var callbacks = new SortedCallbacks(this.options, this.options.memberCallback, this.finalCallback)
- this.options.memberCallback = callbacks.next.bind(callbacks)
- this.finalCallback = callbacks.final.bind(callbacks)
- }
- willInclude (fun, context) {
- let result = fun.call(this.master, context)
- if (!this.loadFinish) {
- return true
- }
- return result
- }
- minMaxEffort (fun) {
- let { minEffort, maxEffort } = fun.call(this.master)
- if (!this.loadFinish) {
- minEffort += 64
- maxEffort = null
- }
- return { minEffort, maxEffort }
- }
- preprocess (fun) {
- fun.call(this.master)
- this.todo = {}
- each(this.relations, ob => {
- each(ob.members, member => {
- if (!(member.id in this.doneFeatures)) {
- this.todo[member.id] = undefined
- }
- })
- })
- each(this.todo, (value, id) => {
- if (id in this.overpass.cacheElements) {
- var ob = this.overpass.cacheElements[id]
- if (this.bounds && !ob.intersects(this.bounds)) {
- return
- }
- if ((this.options.memberProperties & ob.properties) === this.options.memberProperties) {
- this.doneFeatures[id] = ob
- this.options.memberCallback(null, ob)
- }
- }
- })
- return
- }
- _compileQuery (fun, context) {
- var subRequest = fun.call(this.master, context)
- if (keys(this.relations).length === 0) {
- return subRequest
- }
- let query = '(\n'
- query += map(this.relations, ob => {
- if (ob.type === 'relation') {
- return 'relation(' + ob.osm_id + ');\n'
- }
- return ''
- }).join('')
- query += ')->.result;'
- this.currentRelations = keys(this.relations)
- let BBoxString = ''
- if (this.bounds) {
- BBoxString = '(' + this.bounds.toLatLonString() + ')'
- }
- query += '(\n' +
- ' node(r.result)' + BBoxString + ';\n' +
- ' way(r.result)' + BBoxString + ';\n' +
- ' relation(r.result)' + BBoxString + ';\n' +
- ')->.resultMembers;\n'
- var queryRemoveDoneFeatures = ''
- var countRemoveDoneFeatures = 0
- for (var id in this.doneFeatures) {
- var ob = this.doneFeatures[id]
- if (countRemoveDoneFeatures % 1000 === 999) {
- query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
- queryRemoveDoneFeatures = '.doneMembers;'
- }
- queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
- countRemoveDoneFeatures++
- }
- if (countRemoveDoneFeatures) {
- query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
- query += '(.resultMembers; - .doneMembers;)->.resultMembers;\n'
- }
- this.part = {
- properties: this.options.memberProperties,
- receiveObject: this.receiveObject.bind(this),
- featureCallback: this.options.memberCallback,
- count: 0
- }
- query += '.resultMembers out ' + overpassOutOptions(this.part) + ';'
- this.loadFinish = true
- if (subRequest.parts.length) {
- subRequest.query += '\nout count;\n'
- }
- subRequest.query += query
- subRequest.parts.push(this.part)
- return subRequest
- }
- receiveMasterObject (fun, err, result, index) {
- this.relations[result.id] = result
- this.loadFinish = false
- fun(err, result, index)
- }
- receiveObject (ob) {
- this.doneFeatures[ob.id] = ob
- }
- finishSubRequest (fun, subRequest) {
- fun.call(this.master, subRequest)
- if (keys(this.relations).length !== this.currentRelations.length) {
- this.loadFinish = false
- }
- }
- needLoad (fun) {
- var result = fun.call(this.master)
- if (result === true) {
- return true
- }
- return !this.loadFinish
- }
- mayFinish (fun) {
- var result = fun.call(this.master)
- if (result === false) {
- return false
- }
- return this.loadFinish
- }
- }
- module.exports = function (request) {
- return new RequestBBoxMembers(request)
- }
- },{"./SortedCallbacks":190,"./defines":193,"./overpassOutOptions":198,"boundingbox":20,"lodash/forEach":150,"lodash/keys":164,"lodash/map":165}],188:[function(require,module,exports){
- const Request = require('./Request')
- const defines = require('./defines')
- const BoundingBox = require('boundingbox')
- const overpassOutOptions = require('./overpassOutOptions')
- const RequestGetMembers = require('./RequestGetMembers')
- /**
- * A get request (request list of map features by id)
- * @extends Request
- */
- class RequestGet extends Request {
- /**
- * @param {OverpassFrontend} overpass
- * @param {data} data
- */
- constructor (overpass, data) {
- super(overpass, data)
- this.type = 'get'
- if (typeof this.ids === 'string') {
- this.ids = [ this.ids ]
- } else {
- this.ids = this.ids.concat()
- }
- if (typeof this.options.properties === 'undefined') {
- this.options.properties = defines.DEFAULT
- }
- for (var i = 0; i < this.ids.length; i++) {
- if (this.ids[i] in this.overpass.cacheElements && this.overpass.cacheElements[this.ids[i]] === false) {
- delete this.overpass.cacheElements[this.ids[i]]
- }
- }
- if (this.options.bbox) {
- this.options.bbox = new BoundingBox(this.options.bbox)
- }
- // option 'split' not available for get requests -> use effort instead
- delete this.options.split
- this.done = {}
- if ('members' in this.options) {
- RequestGetMembers(this)
- }
- }
- _effortForId (id) {
- if (!id) {
- return null
- }
- var type = id.substr(0, 1)
- switch (type) {
- case 'n':
- return this.overpass.options.effortNode
- case 'w':
- return this.overpass.options.effortWay
- case 'r':
- return this.overpass.options.effortRelation
- }
- }
- /**
- * how much effort can a call to this request use
- * @return {Request#minMaxEffortResult} - minimum and maximum effort
- */
- minMaxEffort () {
- var todo = this.ids.filter(x => x)
- if (todo.length === 0) {
- return { minEffort: 0, maxEffort: 0 }
- }
- let minEffort = Math.min.apply(this, todo.map(id => this._effortForId(id)))
- let maxEffort = todo.map(id => this._effortForId(id)).reduce((a, b) => a + b)
- return { minEffort, maxEffort }
- }
- /**
- * check if there are any map features which can be returned right now
- */
- preprocess () {
- this.allFound = true
- for (var i = 0; i < this.ids.length; i++) {
- var id = this.ids[i]
- if (id === null) {
- continue
- }
- if (id in this.overpass.cacheElements) {
- var ob = this.overpass.cacheElements[id]
- var ready = true
- // Feature does not exists!
- if (ob.missingObject) {
- this.featureCallback(null, null, i)
- this.ids[i] = null
- continue
- }
- // for bbox option, if object is (partly) loaded, but outside call
- // featureCallback with 'false'
- if (this.options.bbox && !ob.intersects(this.options.bbox)) {
- this.featureCallback(null, false, i)
- this.ids[i] = null
- continue
- }
- // not fully loaded
- if ((ob !== false && ob !== null) && (this.options.properties & ob.properties) !== this.options.properties) {
- ready = false
- }
- // if sort is set in options maybe defer calling featureCallback
- if (ready) {
- this.featureCallback(null, ob, i)
- this.ids[i] = null
- continue
- }
- } else {
- // Illegal ID
- if (id !== null && !id.match(/^[nwr][0-9]+$/)) {
- this.featureCallback(null, null, i)
- this.ids[i] = null
- continue
- }
- }
- this.allFound = false
- }
- }
- /**
- * compile the query
- * @param {OverpassFrontend#Context} context - Current context
- * @return {Request#SubRequest} - the compiled query
- */
- _compileQuery (context) {
- var query = ''
- var nodeQuery = ''
- var wayQuery = ''
- var relationQuery = ''
- var BBoxQuery = ''
- var effort = 0
- if (this.options.bbox) {
- BBoxQuery = '(' + this.options.bbox.toLatLonString() + ')'
- }
- for (var i = 0; i < this.ids.length; i++) {
- var id = this.ids[i]
- var outOptions = overpassOutOptions(this.options)
- if (effort > context.maxEffort) {
- break
- }
- if (id === null) {
- continue
- }
- // don't load objects multiple times in same context
- if (id in context.todo) {
- continue
- }
- if (this.options.bbox) {
- // check if we already know the bbox of the element; if yes, don't try
- // to load object if it does not intersect bounds
- if (id in this.overpass.cacheElements && (this.overpass.cacheElements[id].properties & defines.BBOX)) {
- if (!this.overpass.cacheElements[id].intersects(this.options.bbox)) {
- continue
- }
- }
- }
- switch (id.substr(0, 1)) {
- case 'n':
- nodeQuery += 'node(' + id.substr(1) + ');\n'
- effort += this.overpass.options.effortNode
- break
- case 'w':
- wayQuery += 'way(' + id.substr(1) + ');\n'
- effort += this.overpass.options.effortWay
- break
- case 'r':
- relationQuery += 'relation(' + id.substr(1) + ');\n'
- effort += this.overpass.options.effortRelation
- break
- }
- context.todo[id] = true
- }
- if (nodeQuery !== '') {
- query += '((' + nodeQuery + ');)->.n;\n'
- if (BBoxQuery) {
- query += '(node.n; - node.n' + BBoxQuery + '->.n;);\nout ids bb qt;\n'
- }
- }
- if (wayQuery !== '') {
- query += '((' + wayQuery + ');)->.w;\n'
- if (BBoxQuery) {
- query += '(way.w; - way.w' + BBoxQuery + '->.w;);\nout ids bb qt;\n'
- }
- }
- if (relationQuery !== '') {
- query += '((' + relationQuery + ');)->.r;\n'
- if (BBoxQuery) {
- query += '(relation.r; - relation.r' + BBoxQuery + '->.r;);\nout ids bb qt;\n'
- }
- }
- var requestParts = []
- if (BBoxQuery && (nodeQuery !== '' || wayQuery !== '' || relationQuery !== '')) {
- // additional separator to separate objects outside bbox from inside bbox
- query += 'out count;\n'
- requestParts.push({
- properties: defines.BBOX,
- bbox: this.options.bbox,
- bboxNoMatch: true
- })
- }
- if (nodeQuery !== '') {
- query += '.n out ' + outOptions + ';\n'
- }
- if (wayQuery !== '') {
- query += '.w out ' + outOptions + ';\n'
- }
- if (relationQuery !== '') {
- query += '.r out ' + outOptions + ';\n'
- }
- if (query) {
- requestParts.push({
- properties: this.options.properties,
- receiveObject: this.receiveObject.bind(this),
- featureCallback: this._featureCallback.bind(this, this.featureCallback)
- })
- }
- var subRequest = {
- query,
- effort: effort,
- request: this,
- parts: requestParts
- }
- return subRequest
- }
- _featureCallback (fun, err, ob) {
- var indexes = []
- var p
- while ((p = this.ids.indexOf(ob.id)) !== -1) {
- this.ids[p] = null
- indexes.push(p)
- }
- if (this.options.bbox && !ob.intersects(this.options.bbox)) {
- indexes.forEach(p => fun(null, false, p))
- return
- }
- indexes.forEach(p => fun(null, ob, p))
- }
- needLoad () {
- this.preprocess()
- return this.allFound
- }
- mayFinish () {
- return this.allFound
- }
- }
- module.exports = RequestGet
- },{"./Request":185,"./RequestGetMembers":189,"./defines":193,"./overpassOutOptions":198,"boundingbox":20}],189:[function(require,module,exports){
- const defines = require('./defines')
- const overpassOutOptions = require('./overpassOutOptions')
- const each = require('lodash/forEach')
- const map = require('lodash/map')
- const keys = require('lodash/keys')
- const BoundingBox = require('boundingbox')
- class RequestGetMembers {
- constructor (request) {
- this.master = request
- this.options = this.master.options
- this.overpass = this.master.overpass
- this.options.properties |= defines.MEMBERS
- this.options.memberProperties = this.options.memberProperties || defines.DEFAULT
- this.options.memberProperties |= defines.BBOX
- if (this.options.memberBounds) {
- this.bounds = new BoundingBox(this.options.memberBounds)
- }
- this.master._compileQuery = this._compileQuery.bind(this, this.master._compileQuery)
- this.master.needLoad = this.needLoad.bind(this, this.master.needLoad)
- this.master.mayFinish = this.mayFinish.bind(this, this.master.mayFinish)
- this.master.preprocess = this.preprocess.bind(this, this.master.preprocess)
- this.master.willInclude = this.willInclude.bind(this, this.master.willInclude)
- this.master.minMaxEffort = this.minMaxEffort.bind(this, this.master.minMaxEffort)
- this.master.finishSubRequest = this.finishSubRequest.bind(this, this.master.finishSubRequest)
- this.master.featureCallback = this.receiveMasterObject.bind(this, this.master.featureCallback)
- this.doneFeatures = {}
- this.relations = {}
- this.currentRelations = []
- this.todo = {}
- }
- willInclude (fun, context) {
- let result = fun.call(this.master, context)
- if (this.loadFinish) {
- return false
- }
- if (!result) {
- return false
- }
- if (!('extMembersList' in context)) {
- context.extMembersList = this.relations
- context.extMembersRequests = [ this ]
- context.extMembersPriority = this.master.priority
- return true
- } else if (this.master.priority <= context.extMembersPriority) {
- keys(this.relations).forEach(id => {
- context.extMembersList[id] = this.relations[id]
- })
- context.extMembersRequests.push(this)
- return false
- }
- }
- minMaxEffort (fun) {
- let { minEffort, maxEffort } = fun.call(this.master)
- if (!this.loadFinish) {
- minEffort += 64
- maxEffort = null
- }
- return { minEffort, maxEffort }
- }
- preprocess (fun) {
- fun.call(this.master)
- this.todo = {}
- each(this.relations, ob => {
- each(ob.members, member => {
- if (!(member.id in this.doneFeatures)) {
- this.todo[member.id] = undefined
- }
- })
- })
- each(this.todo, (value, id) => {
- if (id in this.overpass.cacheElements) {
- var ob = this.overpass.cacheElements[id]
- if (this.bounds && !ob.intersects(this.bounds)) {
- return
- }
- if ((this.options.memberProperties & ob.properties) === this.options.memberProperties) {
- this.doneFeatures[id] = ob
- this.options.memberCallback(null, ob)
- }
- }
- })
- return
- }
- _compileQuery (fun, context) {
- var subRequest = fun.call(this.master, context)
- if (keys(this.relations).length === 0) {
- return subRequest
- }
- let query = '(\n'
- query += map(context.extMembersList, ob => {
- if (ob.type === 'relation') {
- return 'relation(' + ob.osm_id + ');\n'
- }
- return ''
- }).join('')
- query += ')->.result;'
- this.currentRelations = keys(this.relations)
- let BBoxString = ''
- if (this.bounds) {
- BBoxString = '(' + this.bounds.toLatLonString() + ')'
- }
- query += '(\n' +
- ' node(r.result)' + BBoxString + ';\n' +
- ' way(r.result)' + BBoxString + ';\n' +
- ' relation(r.result)' + BBoxString + ';\n' +
- ')->.resultMembers;\n'
- var queryRemoveDoneFeatures = ''
- var countRemoveDoneFeatures = 0
- var listedDoneFeatures = {}
- context.extMembersRequests.forEach(request => {
- for (var id in request.doneFeatures) {
- if (id in listedDoneFeatures) {
- continue
- }
- var ob = request.doneFeatures[id]
- if (countRemoveDoneFeatures % 1000 === 999) {
- query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
- queryRemoveDoneFeatures = '.doneMembers;'
- }
- queryRemoveDoneFeatures += ob.type + '(' + ob.osm_id + ');'
- countRemoveDoneFeatures++
- listedDoneFeatures[id] = true
- }
- request.loadFinish = true
- })
- if (countRemoveDoneFeatures) {
- query += '(' + queryRemoveDoneFeatures + ')->.doneMembers;\n'
- query += '(.resultMembers; - .doneMembers;)->.resultMembers;\n'
- }
- this.part = {
- properties: this.options.memberProperties,
- receiveObject: this.receiveObject.bind(this),
- featureCallback: this.options.memberCallback,
- count: 0
- }
- query += '.resultMembers out ' + overpassOutOptions(this.part) + ';'
- if (subRequest.parts.length) {
- subRequest.query += '\nout count;\n'
- }
- subRequest.query += query
- subRequest.parts.push(this.part)
- return subRequest
- }
- receiveMasterObject (fun, err, result, index) {
- this.relations[result.id] = result
- this.loadFinish = false
- fun(err, result, index)
- }
- receiveObject (ob) {
- this.doneFeatures[ob.id] = ob
- }
- finishSubRequest (fun, subRequest) {
- fun.call(this.master, subRequest)
- if (keys(this.relations).length !== this.currentRelations.length) {
- this.loadFinish = false
- }
- }
- needLoad (fun) {
- var result = fun.call(this.master)
- if (result === true) {
- return true
- }
- return !this.loadFinish
- }
- mayFinish (fun) {
- var result = fun.call(this.master)
- if (result === false) {
- return false
- }
- return this.loadFinish
- }
- }
- module.exports = function (request) {
- return new RequestGetMembers(request)
- }
- },{"./defines":193,"./overpassOutOptions":198,"boundingbox":20,"lodash/forEach":150,"lodash/keys":164,"lodash/map":165}],190:[function(require,module,exports){
- var async = require('async')
- var weightSort = require('weight-sort')
- var OverpassFrontend = require('./defines')
- class SortedCallbacks {
- constructor (options, featureCallback, finalCallback) {
- this.list = []
- this.lastIndex = -1
- this.featureCallback = featureCallback
- this.finalCallback = finalCallback
- this.options = options
- if (!('sort' in this.options) || this.options.sort === false) {
- this.options.sort = null
- }
- if (!('sortDir' in this.options)) {
- this.options.sortDir = 'asc'
- }
- if (this.options.sort === true) {
- this.options.sort = 'index'
- }
- if (this.options.sort === 'BBoxDiagonalLength') {
- this.options.properties |= OverpassFrontend.BBOX
- }
- }
- next (err, feature, index) {
- if (typeof index === 'undefined') {
- index = this.list.length
- }
- this.list[index] = {
- err: err,
- feature: feature,
- index: index
- }
- if ((this.options.sort === null) ||
- (this.options.sort === 'index' && this.options.sortDir === 'asc' && index === this.lastIndex + 1)) {
- async.setImmediate(function () {
- this.featureCallback(this.list[index].err, this.list[index].feature, index)
- }.bind(this))
- this.lastIndex = index
- }
- }
- final (err) {
- if (this.options.sort === 'BBoxDiagonalLength') {
- for (var i = 0; i < this.list.length; i++) {
- var feature = this.list[i].feature
- if (feature && feature.bounds) {
- this.list[i].weight = feature.bounds.diagonalLength()
- }
- }
- this.list = weightSort(this.list)
- }
- if (this.options.sortDir === 'desc') {
- this.list.reverse()
- }
- async.setImmediate(function () {
- if (this.options.sort !== null) {
- for (var i = this.lastIndex + 1; i < this.list.length; i++) {
- // if a request got aborted, the entry in list is missing
- if (this.list[i]) {
- this.featureCallback(this.list[i].err, this.list[i].feature, i)
- }
- }
- }
- this.finalCallback(err)
- }.bind(this))
- }
- }
- module.exports = SortedCallbacks
- },{"./defines":193,"async":19,"weight-sort":208}],191:[function(require,module,exports){
- module.exports = function convertFromXML (xml) {
- let result = {
- version: parseFloat(xml.getAttribute('version')),
- generator: xml.getAttribute('generator'),
- osm3s: {},
- elements: []
- }
- let notes = xml.getElementsByTagName('note')
- if (notes.length) {
- result.osm3s.copyright = notes[0].textContent
- }
- let metas = xml.getElementsByTagName('meta')
- if (metas.length) {
- result.osm3s['timestamp_osm_base'] = metas[0].getAttribute('osm_base')
- if (metas[0].hasAttribute('areas')) {
- result.osm3s['timestamp_areas_base'] = metas[0].getAttribute('areas')
- }
- }
- let current = xml.firstChild
- while (current) {
- let element = {}
- if (current.nodeName === 'node' || current.nodeName === 'way' || current.nodeName === 'relation') {
- element.type = current.nodeName
- element.id = parseInt(current.getAttribute('id'))
- element.changeset = parseInt(current.getAttribute('changeset'))
- element.timestamp = current.getAttribute('timestamp')
- element.user = current.getAttribute('user')
- element.uid = parseInt(current.getAttribute('uid'))
- element.version = parseInt(current.getAttribute('version'))
- if (element.type === 'node') {
- element.lat = parseFloat(current.getAttribute('lat'))
- element.lon = parseFloat(current.getAttribute('lon'))
- } else if (element.type === 'way') {
- element.nodes = []
- } else if (element.type === 'relation') {
- element.members = []
- }
- let child = current.firstChild
- while (child) {
- if (child.nodeName === 'tag') {
- if (!('tags' in element)) {
- element.tags = {}
- }
- element.tags[child.getAttribute('k')] = child.getAttribute('v')
- } else if (child.nodeName === 'member') {
- element.members.push({
- type: child.getAttribute('type'),
- ref: parseInt(child.getAttribute('ref')),
- role: child.getAttribute('role')
- })
- } else if (child.nodeName === 'nd') {
- element.nodes.push(parseInt(child.getAttribute('ref')))
- }
- child = child.nextSibling
- }
- result.elements.push(element)
- }
- current = current.nextSibling
- }
- return result
- }
- },{}],192:[function(require,module,exports){
- module.exports = function copyOsm3sMetaFrom (results) {
- let osm3sMeta = {}
- for (let k in results) {
- if (k !== 'elements' && k !== 'osm3s') {
- osm3sMeta[k] = results[k]
- }
- }
- if (results.osm3s) {
- for (let k in results.osm3s) {
- osm3sMeta[k] = results.osm3s[k]
- }
- }
- return osm3sMeta
- }
- },{}],193:[function(require,module,exports){
- module.exports = {
- 'ID_ONLY': 0,
- 'TAGS': 1,
- 'META': 2,
- 'MEMBERS': 4,
- 'BBOX': 8,
- 'GEOM': 16,
- 'CENTER': 32,
- 'ALL': 63,
- 'DEFAULT': 13
- }
- },{}],194:[function(require,module,exports){
- module.exports = function filterJoin (def) {
- let result = [ '' ]
- if (!Array.isArray(def)) {
- def = [ def ]
- }
- def.forEach(
- d => {
- if (d.or) {
- let sub = d.or.map(e => filterJoin(e))
- let newResult = []
- result.forEach(r => { newResult = newResult.concat(sub.map(s => r + s)) })
- result = newResult
- } else {
- result = result.map(r => r + d)
- }
- }
- )
- return result
- }
- },{}],195:[function(require,module,exports){
- (function (global){
- /* global location:false */
- if (typeof XMLHttpRequest === 'undefined') {
- global.XMLHttpRequest = (typeof window !== "undefined" ? window['XMLHttpRequest'] : typeof global !== "undefined" ? global['XMLHttpRequest'] : null).XMLHttpRequest
- }
- function httpLoad (url, getParam, postParam, callback) {
- var req = new global.XMLHttpRequest()
- req.onreadystatechange = function () {
- var data = null
- var err = null
- if (req.readyState === 4) {
- if (req.status === 200) {
- try {
- data = JSON.parse(req.responseText)
- } catch (err) {
- // err already set
- }
- callback(err, data)
- } else {
- try {
- err = JSON.parse(req.responseText)
- } catch (err) {
- if (req.responseText.search('OSM3S Response') !== -1) {
- var lines = req.responseText.split(/\n/)
- var e = ''
- for (var i = 0; i < lines.length; i++) {
- var m
- if ((m = lines[i].match(/<p><strong style="color:#FF0000">Error<\/strong>: (.*)<\/p>/))) {
- e += m[1] + '\n'
- }
- }
- // Could not parse error message - create alternative
- if (e === '') {
- e = 'Got error ' + req.status
- }
- callback(e, null)
- } else {
- callback(req.responseText, null)
- }
- }
- }
- }
- }
- var reqType = 'GET'
- var postData = null
- if (postParam) {
- reqType = 'POST'
- postData = postParam
- }
- if (url.substr(0, 2) === '//') {
- if (typeof location === 'undefined') {
- url = 'https:' + url
- } else {
- url = location.protocol + url
- }
- }
- req.open(reqType, url, true)
- try {
- req.send(postData)
- } catch (err) {
- callback(err, null)
- }
- }
- module.exports = httpLoad
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],196:[function(require,module,exports){
- const BoundingBox = require('boundingbox')
- const turf = require('./turf')
- /**
- * When loading area after area of a map, it will be more and more complete.
- * This class manages which area is already known and which not.
- */
- class KnownArea {
- constructor (area = null) {
- this.area = area
- }
- /**
- * make another part of the map known
- */
- add (bbox) {
- bbox = new BoundingBox(bbox).toGeoJSON()
- if (this.area === null) {
- this.area = bbox
- } else {
- this.area = turf.union(bbox, this.area)
- }
- }
- /**
- * is the whole area known?
- */
- check (bbox) {
- if (this.area === null) {
- return false
- }
- bbox = new BoundingBox(bbox).toGeoJSON()
- let remaining = turf.difference(bbox, this.area)
- // console.log(JSON.stringify(this.area), JSON.stringify(bbox), !remaining)
- return !remaining
- }
- /**
- * return area as (multi)polygon
- */
- toGeoJSON () {
- return this.area
- }
- }
- module.exports = KnownArea
- },{"./turf":200,"boundingbox":20}],197:[function(require,module,exports){
- const fs = require('fs')
- const DOMParser = require('xmldom').DOMParser
- const bzip2 = require('bzip2')
- const convertFromXML = require('./convertFromXML')
- module.exports = function loadOsmFile (url, callback) {
- if (typeof location === 'undefined' && !url.match(/^(http:|https:|)\/\//)) {
- fs.readFile(url,
- (err, content) => {
- let data
- if (err) {
- return callback(err)
- }
- if (url.match(/\.osm(\.bz2)?$/)) {
- if (url.match(/\.osm\.bz2$/)) {
- data = bzip2.simple(bzip2.array(content))
- content = ''
- for (let i = 0; i < data.byteLength; i++) {
- content += String.fromCharCode(data[i])
- }
- content = decodeURIComponent(escape(content))
- }
- data = new DOMParser().parseFromString(content.toString(), 'text/xml')
- data = convertFromXML(data.getElementsByTagName('osm')[0])
- } else {
- data = JSON.parse(content)
- }
- callback(null, data)
- }
- )
- return
- }
- let req = new window.XMLHttpRequest()
- req.onreadystatechange = function () {
- if (req.readyState === 4) {
- if (req.status === 200) {
- let data
- if (url.match(/\.osm\.bz2$/)) {
- let content = new Uint8Array(req.response)
- data = bzip2.simple(bzip2.array(content))
- content = ''
- for (let i = 0; i < data.byteLength; i++) {
- content += String.fromCharCode(data[i])
- }
- content = decodeURIComponent(escape(content))
- data = new DOMParser().parseFromString(content.toString(), 'text/xml')
- data = convertFromXML(data.getElementsByTagName('osm')[0])
- } else if (req.responseXML) {
- data = convertFromXML(req.responseXML.firstChild)
- } else {
- data = JSON.parse(req.responseText)
- }
- callback(null, data)
- } else {
- callback(req)
- }
- }
- }
- if (url.substr(0, 2) === '//') {
- if (typeof location === 'undefined') {
- url = 'https:' + url
- } else {
- url = window.location.protocol + url
- }
- }
- if (url.match(/\.osm\.bz2$/)) {
- req.responseType = 'arraybuffer'
- }
- req.open('GET', url)
- req.send()
- }
- },{"./convertFromXML":191,"bzip2":24,"fs":23,"xmldom":210}],198:[function(require,module,exports){
- var defines = require('./defines')
- function overpassOutOptions (options, optionsOverride) {
- var outOptions = ''
- if ('split' in options && options.split > 0) {
- outOptions += options.split + ' '
- } else if ('effortSplit' in options) {
- outOptions += options.effortSplit + ' '
- }
- if (options.properties & defines.META) {
- outOptions += 'meta '
- } else if (options.properties & defines.TAGS) {
- if (options.properties & defines.MEMBERS) {
- outOptions += 'body '
- } else {
- outOptions += 'tags '
- }
- } else if (options.properties & defines.MEMBERS) {
- outOptions += 'skel '
- } else {
- outOptions += 'ids '
- }
- if (options.properties & defines.GEOM) {
- outOptions += 'geom '
- } else if (options.properties & defines.BBOX) {
- outOptions += 'bb '
- } else if (options.properties & defines.CENTER) {
- outOptions += 'center '
- }
- outOptions += 'qt'
- return outOptions
- }
- module.exports = overpassOutOptions
- },{"./defines":193}],199:[function(require,module,exports){
- function removeNullEntries (arr) {
- var p
- while ((p = arr.indexOf(null)) !== -1) {
- arr.splice(p, 1)
- }
- return arr
- }
- module.exports = removeNullEntries
- },{}],200:[function(require,module,exports){
- module.exports = {
- difference: require('@turf/difference'),
- union: require('@turf/union').default
- }
- },{"@turf/difference":9,"@turf/union":18}],201:[function(require,module,exports){
- (function (process){
- // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
- // backported and transplited with Babel, with backwards-compat fixes
- // 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.
- // resolves . and .. elements in a path array with directory names there
- // must be no slashes, empty elements, or device names (c:\) in the array
- // (so also no leading and trailing slashes - it does not distinguish
- // relative and absolute paths)
- function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
- return parts;
- }
- // path.resolve([from ...], to)
- // posix version
- exports.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : process.cwd();
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
- };
- // path.normalize(path)
- // posix version
- exports.normalize = function(path) {
- var isAbsolute = exports.isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isAbsolute).join('/');
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
- return (isAbsolute ? '/' : '') + path;
- };
- // posix version
- exports.isAbsolute = function(path) {
- return path.charAt(0) === '/';
- };
- // posix version
- exports.join = function() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
- };
- // path.relative(from, to)
- // posix version
- exports.relative = function(from, to) {
- from = exports.resolve(from).substr(1);
- to = exports.resolve(to).substr(1);
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
- return outputParts.join('/');
- };
- exports.sep = '/';
- exports.delimiter = ':';
- exports.dirname = function (path) {
- if (typeof path !== 'string') path = path + '';
- if (path.length === 0) return '.';
- var code = path.charCodeAt(0);
- var hasRoot = code === 47 /*/*/;
- var end = -1;
- var matchedSlash = true;
- for (var i = path.length - 1; i >= 1; --i) {
- code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- if (!matchedSlash) {
- end = i;
- break;
- }
- } else {
- // We saw the first non-path separator
- matchedSlash = false;
- }
- }
- if (end === -1) return hasRoot ? '/' : '.';
- if (hasRoot && end === 1) {
- // return '//';
- // Backwards-compat fix:
- return '/';
- }
- return path.slice(0, end);
- };
- function basename(path) {
- if (typeof path !== 'string') path = path + '';
- var start = 0;
- var end = -1;
- var matchedSlash = true;
- var i;
- for (i = path.length - 1; i >= 0; --i) {
- if (path.charCodeAt(i) === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- start = i + 1;
- break;
- }
- } else if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // path component
- matchedSlash = false;
- end = i + 1;
- }
- }
- if (end === -1) return '';
- return path.slice(start, end);
- }
- // Uses a mixed approach for backwards-compatibility, as ext behavior changed
- // in new Node.js versions, so only basename() above is backported here
- exports.basename = function (path, ext) {
- var f = basename(path);
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
- };
- exports.extname = function (path) {
- if (typeof path !== 'string') path = path + '';
- var startDot = -1;
- var startPart = 0;
- var end = -1;
- var matchedSlash = true;
- // Track the state of characters (if any) we see before our first dot and
- // after any path separator we find
- var preDotState = 0;
- for (var i = path.length - 1; i >= 0; --i) {
- var code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- startPart = i + 1;
- break;
- }
- continue;
- }
- if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // extension
- matchedSlash = false;
- end = i + 1;
- }
- if (code === 46 /*.*/) {
- // If this is our first dot, mark it as the start of our extension
- if (startDot === -1)
- startDot = i;
- else if (preDotState !== 1)
- preDotState = 1;
- } else if (startDot !== -1) {
- // We saw a non-dot and non-path separator before our dot, so we should
- // have a good chance at having a non-empty extension
- preDotState = -1;
- }
- }
- if (startDot === -1 || end === -1 ||
- // We saw a non-dot character immediately before the dot
- preDotState === 0 ||
- // The (right-most) trimmed path component is exactly '..'
- preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
- return '';
- }
- return path.slice(startDot, end);
- };
- function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
- }
- // String.prototype.substr - negative index don't work in IE8
- var substr = 'ab'.substr(-1) === 'b'
- ? function (str, start, len) { return str.substr(start, len) }
- : function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
- ;
- }).call(this,require('_process'))
- },{"_process":202}],202:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.prependListener = noop;
- process.prependOnceListener = noop;
- process.listeners = function (name) { return [] }
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],203:[function(require,module,exports){
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global.quickselect = factory());
- }(this, (function () { 'use strict';
- function quickselect(arr, k, left, right, compare) {
- quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
- }
- function quickselectStep(arr, k, left, right, compare) {
- while (right > left) {
- if (right - left > 600) {
- var n = right - left + 1;
- var m = k - left + 1;
- var z = Math.log(n);
- var s = 0.5 * Math.exp(2 * z / 3);
- var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
- var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
- var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
- quickselectStep(arr, k, newLeft, newRight, compare);
- }
- var t = arr[k];
- var i = left;
- var j = right;
- swap(arr, left, k);
- if (compare(arr[right], t) > 0) swap(arr, left, right);
- while (i < j) {
- swap(arr, i, j);
- i++;
- j--;
- while (compare(arr[i], t) < 0) i++;
- while (compare(arr[j], t) > 0) j--;
- }
- if (compare(arr[left], t) === 0) swap(arr, left, j);
- else {
- j++;
- swap(arr, j, right);
- }
- if (j <= k) left = j + 1;
- if (k <= j) right = j - 1;
- }
- }
- function swap(arr, i, j) {
- var tmp = arr[i];
- arr[i] = arr[j];
- arr[j] = tmp;
- }
- function defaultCompare(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
- }
- return quickselect;
- })));
- },{}],204:[function(require,module,exports){
- 'use strict';
- module.exports = rbush;
- module.exports.default = rbush;
- var quickselect = require('quickselect');
- function rbush(maxEntries, format) {
- if (!(this instanceof rbush)) return new rbush(maxEntries, format);
- // max entries in a node is 9 by default; min node fill is 40% for best performance
- this._maxEntries = Math.max(4, maxEntries || 9);
- this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
- if (format) {
- this._initFormat(format);
- }
- this.clear();
- }
- rbush.prototype = {
- all: function () {
- return this._all(this.data, []);
- },
- search: function (bbox) {
- var node = this.data,
- result = [],
- toBBox = this.toBBox;
- if (!intersects(bbox, node)) return result;
- var nodesToSearch = [],
- i, len, child, childBBox;
- while (node) {
- for (i = 0, len = node.children.length; i < len; i++) {
- child = node.children[i];
- childBBox = node.leaf ? toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf) result.push(child);
- else if (contains(bbox, childBBox)) this._all(child, result);
- else nodesToSearch.push(child);
- }
- }
- node = nodesToSearch.pop();
- }
- return result;
- },
- collides: function (bbox) {
- var node = this.data,
- toBBox = this.toBBox;
- if (!intersects(bbox, node)) return false;
- var nodesToSearch = [],
- i, len, child, childBBox;
- while (node) {
- for (i = 0, len = node.children.length; i < len; i++) {
- child = node.children[i];
- childBBox = node.leaf ? toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf || contains(bbox, childBBox)) return true;
- nodesToSearch.push(child);
- }
- }
- node = nodesToSearch.pop();
- }
- return false;
- },
- load: function (data) {
- if (!(data && data.length)) return this;
- if (data.length < this._minEntries) {
- for (var i = 0, len = data.length; i < len; i++) {
- this.insert(data[i]);
- }
- return this;
- }
- // recursively build the tree with the given data from scratch using OMT algorithm
- var node = this._build(data.slice(), 0, data.length - 1, 0);
- if (!this.data.children.length) {
- // save as is if tree is empty
- this.data = node;
- } else if (this.data.height === node.height) {
- // split root if trees have the same height
- this._splitRoot(this.data, node);
- } else {
- if (this.data.height < node.height) {
- // swap trees if inserted one is bigger
- var tmpNode = this.data;
- this.data = node;
- node = tmpNode;
- }
- // insert the small tree into the large tree at appropriate level
- this._insert(node, this.data.height - node.height - 1, true);
- }
- return this;
- },
- insert: function (item) {
- if (item) this._insert(item, this.data.height - 1);
- return this;
- },
- clear: function () {
- this.data = createNode([]);
- return this;
- },
- remove: function (item, equalsFn) {
- if (!item) return this;
- var node = this.data,
- bbox = this.toBBox(item),
- path = [],
- indexes = [],
- i, parent, index, goingUp;
- // depth-first iterative tree traversal
- while (node || path.length) {
- if (!node) { // go up
- node = path.pop();
- parent = path[path.length - 1];
- i = indexes.pop();
- goingUp = true;
- }
- if (node.leaf) { // check current node
- index = findItem(item, node.children, equalsFn);
- if (index !== -1) {
- // item found, remove the item and condense tree upwards
- node.children.splice(index, 1);
- path.push(node);
- this._condense(path);
- return this;
- }
- }
- if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
- path.push(node);
- indexes.push(i);
- i = 0;
- parent = node;
- node = node.children[0];
- } else if (parent) { // go right
- i++;
- node = parent.children[i];
- goingUp = false;
- } else node = null; // nothing found
- }
- return this;
- },
- toBBox: function (item) { return item; },
- compareMinX: compareNodeMinX,
- compareMinY: compareNodeMinY,
- toJSON: function () { return this.data; },
- fromJSON: function (data) {
- this.data = data;
- return this;
- },
- _all: function (node, result) {
- var nodesToSearch = [];
- while (node) {
- if (node.leaf) result.push.apply(result, node.children);
- else nodesToSearch.push.apply(nodesToSearch, node.children);
- node = nodesToSearch.pop();
- }
- return result;
- },
- _build: function (items, left, right, height) {
- var N = right - left + 1,
- M = this._maxEntries,
- node;
- if (N <= M) {
- // reached leaf level; return leaf
- node = createNode(items.slice(left, right + 1));
- calcBBox(node, this.toBBox);
- return node;
- }
- if (!height) {
- // target height of the bulk-loaded tree
- height = Math.ceil(Math.log(N) / Math.log(M));
- // target number of root entries to maximize storage utilization
- M = Math.ceil(N / Math.pow(M, height - 1));
- }
- node = createNode([]);
- node.leaf = false;
- node.height = height;
- // split the items into M mostly square tiles
- var N2 = Math.ceil(N / M),
- N1 = N2 * Math.ceil(Math.sqrt(M)),
- i, j, right2, right3;
- multiSelect(items, left, right, N1, this.compareMinX);
- for (i = left; i <= right; i += N1) {
- right2 = Math.min(i + N1 - 1, right);
- multiSelect(items, i, right2, N2, this.compareMinY);
- for (j = i; j <= right2; j += N2) {
- right3 = Math.min(j + N2 - 1, right2);
- // pack each entry recursively
- node.children.push(this._build(items, j, right3, height - 1));
- }
- }
- calcBBox(node, this.toBBox);
- return node;
- },
- _chooseSubtree: function (bbox, node, level, path) {
- var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
- while (true) {
- path.push(node);
- if (node.leaf || path.length - 1 === level) break;
- minArea = minEnlargement = Infinity;
- for (i = 0, len = node.children.length; i < len; i++) {
- child = node.children[i];
- area = bboxArea(child);
- enlargement = enlargedArea(bbox, child) - area;
- // choose entry with the least area enlargement
- if (enlargement < minEnlargement) {
- minEnlargement = enlargement;
- minArea = area < minArea ? area : minArea;
- targetNode = child;
- } else if (enlargement === minEnlargement) {
- // otherwise choose one with the smallest area
- if (area < minArea) {
- minArea = area;
- targetNode = child;
- }
- }
- }
- node = targetNode || node.children[0];
- }
- return node;
- },
- _insert: function (item, level, isNode) {
- var toBBox = this.toBBox,
- bbox = isNode ? item : toBBox(item),
- insertPath = [];
- // find the best node for accommodating the item, saving all nodes along the path too
- var node = this._chooseSubtree(bbox, this.data, level, insertPath);
- // put the item into the node
- node.children.push(item);
- extend(node, bbox);
- // split on node overflow; propagate upwards if necessary
- while (level >= 0) {
- if (insertPath[level].children.length > this._maxEntries) {
- this._split(insertPath, level);
- level--;
- } else break;
- }
- // adjust bboxes along the insertion path
- this._adjustParentBBoxes(bbox, insertPath, level);
- },
- // split overflowed node into two
- _split: function (insertPath, level) {
- var node = insertPath[level],
- M = node.children.length,
- m = this._minEntries;
- this._chooseSplitAxis(node, m, M);
- var splitIndex = this._chooseSplitIndex(node, m, M);
- var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
- newNode.height = node.height;
- newNode.leaf = node.leaf;
- calcBBox(node, this.toBBox);
- calcBBox(newNode, this.toBBox);
- if (level) insertPath[level - 1].children.push(newNode);
- else this._splitRoot(node, newNode);
- },
- _splitRoot: function (node, newNode) {
- // split root node
- this.data = createNode([node, newNode]);
- this.data.height = node.height + 1;
- this.data.leaf = false;
- calcBBox(this.data, this.toBBox);
- },
- _chooseSplitIndex: function (node, m, M) {
- var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
- minOverlap = minArea = Infinity;
- for (i = m; i <= M - m; i++) {
- bbox1 = distBBox(node, 0, i, this.toBBox);
- bbox2 = distBBox(node, i, M, this.toBBox);
- overlap = intersectionArea(bbox1, bbox2);
- area = bboxArea(bbox1) + bboxArea(bbox2);
- // choose distribution with minimum overlap
- if (overlap < minOverlap) {
- minOverlap = overlap;
- index = i;
- minArea = area < minArea ? area : minArea;
- } else if (overlap === minOverlap) {
- // otherwise choose distribution with minimum area
- if (area < minArea) {
- minArea = area;
- index = i;
- }
- }
- }
- return index;
- },
- // sorts node children by the best axis for split
- _chooseSplitAxis: function (node, m, M) {
- var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
- compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
- xMargin = this._allDistMargin(node, m, M, compareMinX),
- yMargin = this._allDistMargin(node, m, M, compareMinY);
- // if total distributions margin value is minimal for x, sort by minX,
- // otherwise it's already sorted by minY
- if (xMargin < yMargin) node.children.sort(compareMinX);
- },
- // total margin of all possible split distributions where each node is at least m full
- _allDistMargin: function (node, m, M, compare) {
- node.children.sort(compare);
- var toBBox = this.toBBox,
- leftBBox = distBBox(node, 0, m, toBBox),
- rightBBox = distBBox(node, M - m, M, toBBox),
- margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
- i, child;
- for (i = m; i < M - m; i++) {
- child = node.children[i];
- extend(leftBBox, node.leaf ? toBBox(child) : child);
- margin += bboxMargin(leftBBox);
- }
- for (i = M - m - 1; i >= m; i--) {
- child = node.children[i];
- extend(rightBBox, node.leaf ? toBBox(child) : child);
- margin += bboxMargin(rightBBox);
- }
- return margin;
- },
- _adjustParentBBoxes: function (bbox, path, level) {
- // adjust bboxes along the given tree path
- for (var i = level; i >= 0; i--) {
- extend(path[i], bbox);
- }
- },
- _condense: function (path) {
- // go through the path, removing empty nodes and updating bboxes
- for (var i = path.length - 1, siblings; i >= 0; i--) {
- if (path[i].children.length === 0) {
- if (i > 0) {
- siblings = path[i - 1].children;
- siblings.splice(siblings.indexOf(path[i]), 1);
- } else this.clear();
- } else calcBBox(path[i], this.toBBox);
- }
- },
- _initFormat: function (format) {
- // data format (minX, minY, maxX, maxY accessors)
- // uses eval-type function compilation instead of just accepting a toBBox function
- // because the algorithms are very sensitive to sorting functions performance,
- // so they should be dead simple and without inner calls
- var compareArr = ['return a', ' - b', ';'];
- this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
- this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
- this.toBBox = new Function('a',
- 'return {minX: a' + format[0] +
- ', minY: a' + format[1] +
- ', maxX: a' + format[2] +
- ', maxY: a' + format[3] + '};');
- }
- };
- function findItem(item, items, equalsFn) {
- if (!equalsFn) return items.indexOf(item);
- for (var i = 0; i < items.length; i++) {
- if (equalsFn(item, items[i])) return i;
- }
- return -1;
- }
- // calculate node's bbox from bboxes of its children
- function calcBBox(node, toBBox) {
- distBBox(node, 0, node.children.length, toBBox, node);
- }
- // min bounding rectangle of node children from k to p-1
- function distBBox(node, k, p, toBBox, destNode) {
- if (!destNode) destNode = createNode(null);
- destNode.minX = Infinity;
- destNode.minY = Infinity;
- destNode.maxX = -Infinity;
- destNode.maxY = -Infinity;
- for (var i = k, child; i < p; i++) {
- child = node.children[i];
- extend(destNode, node.leaf ? toBBox(child) : child);
- }
- return destNode;
- }
- function extend(a, b) {
- a.minX = Math.min(a.minX, b.minX);
- a.minY = Math.min(a.minY, b.minY);
- a.maxX = Math.max(a.maxX, b.maxX);
- a.maxY = Math.max(a.maxY, b.maxY);
- return a;
- }
- function compareNodeMinX(a, b) { return a.minX - b.minX; }
- function compareNodeMinY(a, b) { return a.minY - b.minY; }
- function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
- function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
- function enlargedArea(a, b) {
- return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
- (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
- }
- function intersectionArea(a, b) {
- var minX = Math.max(a.minX, b.minX),
- minY = Math.max(a.minY, b.minY),
- maxX = Math.min(a.maxX, b.maxX),
- maxY = Math.min(a.maxY, b.maxY);
- return Math.max(0, maxX - minX) *
- Math.max(0, maxY - minY);
- }
- function contains(a, b) {
- return a.minX <= b.minX &&
- a.minY <= b.minY &&
- b.maxX <= a.maxX &&
- b.maxY <= a.maxY;
- }
- function intersects(a, b) {
- return b.minX <= a.maxX &&
- b.minY <= a.maxY &&
- b.maxX >= a.minX &&
- b.maxY >= a.minY;
- }
- function createNode(children) {
- return {
- children: children,
- height: 1,
- leaf: true,
- minX: Infinity,
- minY: Infinity,
- maxX: -Infinity,
- maxY: -Infinity
- };
- }
- // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
- // combines selection algorithm with binary divide & conquer approach
- function multiSelect(arr, left, right, n, compare) {
- var stack = [left, right],
- mid;
- while (stack.length) {
- right = stack.pop();
- left = stack.pop();
- if (right - left <= n) continue;
- mid = left + Math.ceil((right - left) / n / 2) * n;
- quickselect(arr, mid, left, right, compare);
- stack.push(left, mid, mid, right);
- }
- }
- },{"quickselect":203}],205:[function(require,module,exports){
- module.exports = function strsearch2regexp (str) {
- return str
- .replace('.', '\\.')
- .replace(' ', '.*')
- .replace('a', '[aàáâãäå]')
- .replace('A', '[AÀÁÂÃÄÅ]')
- .replace('C', '[CÇ]')
- .replace('c', '[cç]')
- .replace('E', '[EÉÊË]')
- .replace('I', '[IÌÍÎÏ]')
- .replace('D', '[DÐ]')
- .replace('N', '[NÑ]')
- .replace('O', '[OÒÓÔÕÖØ]')
- .replace('X', '[X×]')
- .replace('U', '[UÙÚÛÜ]')
- .replace('Y', '[YÝ]')
- .replace('s', '[sß]')
- .replace('e', '[eèeéêëė]')
- .replace('i', '[iìíîï]')
- .replace('d', '[dð]')
- .replace('n', '[nñ]')
- .replace('o', '[oòóôõöø]')
- .replace('u', '[uùúûü]')
- .replace('y', '[yýÿ]')
- }
- },{}],206:[function(require,module,exports){
- (function (setImmediate,clearImmediate){
- var nextTick = require('process/browser.js').nextTick;
- var apply = Function.prototype.apply;
- var slice = Array.prototype.slice;
- var immediateIds = {};
- var nextImmediateId = 0;
- // DOM APIs, for completeness
- exports.setTimeout = function() {
- return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
- };
- exports.setInterval = function() {
- return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
- };
- exports.clearTimeout =
- exports.clearInterval = function(timeout) { timeout.close(); };
- function Timeout(id, clearFn) {
- this._id = id;
- this._clearFn = clearFn;
- }
- Timeout.prototype.unref = Timeout.prototype.ref = function() {};
- Timeout.prototype.close = function() {
- this._clearFn.call(window, this._id);
- };
- // Does not start the time, just sets up the members needed.
- exports.enroll = function(item, msecs) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = msecs;
- };
- exports.unenroll = function(item) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = -1;
- };
- exports._unrefActive = exports.active = function(item) {
- clearTimeout(item._idleTimeoutId);
- var msecs = item._idleTimeout;
- if (msecs >= 0) {
- item._idleTimeoutId = setTimeout(function onTimeout() {
- if (item._onTimeout)
- item._onTimeout();
- }, msecs);
- }
- };
- // That's not how node.js implements it but the exposed api is the same.
- exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
- var id = nextImmediateId++;
- var args = arguments.length < 2 ? false : slice.call(arguments, 1);
- immediateIds[id] = true;
- nextTick(function onNextTick() {
- if (immediateIds[id]) {
- // fn.call() is faster so we optimize for the common use-case
- // @see http://jsperf.com/call-apply-segu
- if (args) {
- fn.apply(null, args);
- } else {
- fn.call(null);
- }
- // Prevent ids from leaking
- exports.clearImmediate(id);
- }
- });
- return id;
- };
- exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
- delete immediateIds[id];
- };
- }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
- },{"process/browser.js":202,"timers":206}],207:[function(require,module,exports){
- (function (global,__dirname){
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Twig=t():e.Twig=t()}(global,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=27)}([function(e,t){e.exports=require("path")},function(e,t,r){"use strict";e.exports=function(){var e=arguments,t=0,r=function(e,t,r,n){r||(r=" ");var o=e.length>=t?"":new Array(1+t-e.length>>>0).join(r);return n?e+o:o+e},n=function(e,t,n,o,i,s){var a=o-e.length;return a>0&&(e=n||!i?r(e,o,s,n):[e.slice(0,t.length),r("",a,"0",!0),e.slice(t.length)].join("")),e},o=function(e,t,o,i,s,a,p){var c=e>>>0;return e=(o=o&&c&&{2:"0b",8:"0",16:"0x"}[t]||"")+r(c.toString(t),a||0,"0",!1),n(e,o,i,s,p)},i=function(e,t,r,o,i,s){return null!==o&&void 0!==o&&(e=e.slice(0,o)),n(e,"",t,r,i,s)};return e[t++].replace(/%%|%(\d+\$)?([-+'#0 ]*)(\*\d+\$|\*|\d+)?(?:\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g,function(s,a,p,c,l,u){var f,h,y,d,g;if("%%"===s)return"%";var m,x=!1,v="",b=!1,w=!1,k=" ",_=p.length;for(m=0;m<_;m++)switch(p.charAt(m)){case" ":v=" ";break;case"+":v="+";break;case"-":x=!0;break;case"'":k=p.charAt(m+1);break;case"0":b=!0,k="0";break;case"#":w=!0}if((c=c?"*"===c?+e[t++]:"*"===c.charAt(0)?+e[c.slice(1,-1)]:+c:0)<0&&(c=-c,x=!0),!isFinite(c))throw new Error("sprintf: (minimum-)width must be finite");switch(l=l?"*"===l?+e[t++]:"*"===l.charAt(0)?+e[l.slice(1,-1)]:+l:"fFeE".indexOf(u)>-1?6:"d"===u?0:void 0,g=a?e[a.slice(0,-1)]:e[t++],u){case"s":return i(g+"",x,c,l,b,k);case"c":return i(String.fromCharCode(+g),x,c,l,b);case"b":return o(g,2,w,x,c,l,b);case"o":return o(g,8,w,x,c,l,b);case"x":return o(g,16,w,x,c,l,b);case"X":return o(g,16,w,x,c,l,b).toUpperCase();case"u":return o(g,10,w,x,c,l,b);case"i":case"d":return f=+g||0,g=(h=(f=Math.round(f-f%1))<0?"-":v)+r(String(Math.abs(f)),l,"0",!1),n(g,h,x,c,b);case"e":case"E":case"f":case"F":case"g":case"G":return h=(f=+g)<0?"-":v,y=["toExponential","toFixed","toPrecision"]["efg".indexOf(u.toLowerCase())],d=["toString","toUpperCase"]["eEfFgG".indexOf(u)%2],g=h+Math.abs(f)[y](l),n(g,h,x,c,b)[d]();default:return s}})}},function(e,t){e.exports=function(e){"use strict";return e.exports={VERSION:e.VERSION},e.exports.twig=function(t){var r=t.id,n={strict_variables:t.strict_variables||!1,autoescape:null!=t.autoescape&&t.autoescape||!1,allowInlineIncludes:t.allowInlineIncludes||!1,rethrow:t.rethrow||!1,namespaces:t.namespaces};if(e.cache&&r&&e.validateId(r),void 0!==t.debug&&(e.debug=t.debug),void 0!==t.trace&&(e.trace=t.trace),void 0!==t.data)return e.Templates.parsers.twig({data:t.data,path:t.hasOwnProperty("path")?t.path:void 0,module:t.module,id:r,options:n});if(void 0!==t.ref){if(void 0!==t.id)throw new e.Error("Both ref and id cannot be set on a twig.js template.");return e.Templates.load(t.ref)}if(void 0!==t.method){if(!e.Templates.isRegisteredLoader(t.method))throw new e.Error('Loader for "'+t.method+'" is not defined.');return e.Templates.loadRemote(t.name||t.href||t.path||r||void 0,{id:r,method:t.method,parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error)}return void 0!==t.href?e.Templates.loadRemote(t.href,{id:r,method:"ajax",parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error):void 0!==t.path?e.Templates.loadRemote(t.path,{id:r,method:"fs",parser:t.parser||"twig",base:t.base,module:t.module,precompiled:t.precompiled,async:t.async,options:n},t.load,t.error):void 0},e.exports.extendFilter=function(t,r){e.filter.extend(t,r)},e.exports.extendFunction=function(t,r){e._function.extend(t,r)},e.exports.extendTest=function(t,r){e.test.extend(t,r)},e.exports.extendTag=function(t){e.logic.extend(t)},e.exports.extend=function(t){t(e)},e.exports.compile=function(t,r){var n,o=r.filename,i=r.filename;return n=new e.Template({data:t,path:i,id:o,options:r.settings["twig options"]}),function(e){return n.render(e)}},e.exports.renderFile=function(t,r,n){"function"==typeof r&&(n=r,r={});var o=(r=r||{}).settings||{},i={path:t,base:o.views,load:function(e){n(null,""+e.render(r))}},s=o["twig options"];if(s)for(var a in s)s.hasOwnProperty(a)&&(i[a]=s[a]);e.exports.twig(i)},e.exports.__express=e.exports.renderFile,e.exports.cache=function(t){e.cache=t},e.exports.path=e.path,e.exports.filters=e.filters,e.exports.Promise=e.Promise,e}},function(e,t){e.exports=function(e){"use strict";var t=1,r=2;return e.parseAsync=function(t,r){return e.parse.call(this,t,r,!0)},e.expression.parseAsync=function(t,r,n){return e.expression.parse.call(this,t,r,n,!0)},e.logic.parseAsync=function(t,r,n){return e.logic.parse.call(this,t,r,n,!0)},e.Template.prototype.renderAsync=function(e,t){return this.render(e,t,!0)},e.async={},e.isPromise=function(e){return e&&e.then&&"function"==typeof e.then},e.async.potentiallyAsync=function(t,r,n){return r?e.Promise.resolve(n.call(t)):function(t,r,n){var o=n.call(t),i=null,s=!0;if(!e.isPromise(o))return o;if(o.then(function(e){o=e,s=!1}).catch(function(e){i=e}),null!==i)throw i;if(s)throw new e.Error("You are using Twig.js in sync mode in combination with async extensions.");return o}(t,0,n)},e.Thenable=function(e,t,r){this.then=e,this._value=r?t:null,this._state=r||0},e.Thenable.prototype.catch=function(e){return this._state==t?this:this.then(null,e)},e.Thenable.resolvedThen=function(t){try{return e.Promise.resolve(t(this._value))}catch(t){return e.Promise.reject(t)}},e.Thenable.rejectedThen=function(t,r){if(!r||"function"!=typeof r)return this;var n=this._value,o=e.attempt(function(){return r(n)},e.Promise.reject);return e.Promise.resolve(o)},e.Promise=function(n){var o=0,i=null,s=function(e,t){o=e,i=t};return function(e,t,r){try{e(t,r)}catch(e){r(e)}}(n,function(e){s(t,e)},function(e){s(r,e)}),o===t?e.Promise.resolve(i):o===r?e.Promise.reject(i):(s=e.FullPromise()).promise},e.FullPromise=function(){var r=null;function n(e){e(a._value)}function o(e,t){t(a._value)}var i=function(e,t){r=function(e,t,r){var n=[t,r,-2];return e?-2==e[2]?e=[e,n]:e.push(n):e=n,e}(r,e,t)};function s(s,p){a._state||(a._value=p,a._state=s,i=s==t?n:o,r&&(-2===r[2]&&(i(r[0],r[1]),r=null),e.forEach(r,function(e){i(e[0],e[1])}),r=null))}var a=new e.Thenable(function(r,n){var o="function"==typeof r;if(a._state==t&&!o)return e.Promise.resolve(a._value);if(a._state===t)return e.attempt(function(){return e.Promise.resolve(r(a._value))},e.Promise.reject);var s="function"==typeof n;return e.Promise(function(t,a){i(o?function(n){e.attempt(function(){t(r(n))},a)}:t,s?function(r){e.attempt(function(){t(n(r))},a)}:a)})});return s.promise=a,s},e.Promise.defaultResolved=new e.Thenable(e.Thenable.resolvedThen,void 0,t),e.Promise.emptyStringResolved=new e.Thenable(e.Thenable.resolvedThen,"",t),e.Promise.resolve=function(r){return arguments.length<1||void 0===r?e.Promise.defaultResolved:e.isPromise(r)?r:""===r?e.Promise.emptyStringResolved:new e.Thenable(e.Thenable.resolvedThen,r,t)},e.Promise.reject=function(t){return new e.Thenable(e.Thenable.rejectedThen,t,r)},e.Promise.all=function(r){var n=new Array(r.length);return e.async.forEach(r,function(r,o){if(e.isPromise(r)){if(r._state!=t)return r.then(function(e){n[o]=e});n[o]=r._value}else n[o]=r}).then(function(){return n})},e.async.forEach=function(r,n){var o=r.length,i=0;return function s(){var a=null;do{if(i==o)return e.Promise.resolve();a=n(r[i],i),i++}while(!a||!e.isPromise(a)||a._state==t);return a.then(s)}()},e}},function(e,t){e.exports=function(e){"use strict";return e.tests={empty:function(e){if(null===e||void 0===e)return!0;if("number"==typeof e)return!1;if(e.length&&e.length>0)return!1;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},odd:function(e){return e%2==1},even:function(e){return e%2==0},divisibleby:function(e,t){return e%t[0]==0},defined:function(e){return void 0!==e},none:function(e){return null===e},null:function(e){return this.none(e)},"same as":function(e,t){return e===t[0]},sameas:function(t,r){return console.warn("`sameas` is deprecated use `same as`"),e.tests["same as"](t,r)},iterable:function(t){return t&&(e.lib.is("Array",t)||e.lib.is("Object",t))}},e.test=function(t,r,n){if(!e.tests[t])throw"Test "+t+" is not defined.";return e.tests[t](r,n)},e.test.extend=function(t,r){e.tests[t]=r},e}},function(e,t,r){e.exports=function(e){"use strict";e.path={};var t=/.::/,n=/@/;return e.path.parsePath=function(r,o){var i=null,s=r.options.namespaces,a=o||"";if(s&&"object"==typeof s){for(i in s)t.test(a)?a=a.replace(i+"::",s[i]):n.test(a)&&(a=a.replace("@"+i,s[i]));return a}return e.path.relativePath(r,a)},e.path.relativePath=function(t,n){var o,i,s,a="/",p=[];n=n||"";if(t.url)o=void 0!==t.base?t.base+("/"===t.base.charAt(t.base.length-1)?"":"/"):t.url;else if(t.path){var c=r(0),l=c.sep||a,u=new RegExp("^\\.{1,2}"+l.replace("\\","\\\\"));n=n.replace(/\//g,l),void 0!==t.base&&null==n.match(u)?(n=n.replace(t.base,""),o=t.base+l):o=c.normalize(t.path),o=o.replace(l+l,l),a=l}else{if(!t.name&&!t.id||!t.method||"fs"===t.method||"ajax"===t.method)throw new e.Error("Cannot extend an inline template.");o=t.base||t.name||t.id}for((i=o.split(a)).pop(),i=i.concat(n.split(a));i.length>0;)"."==(s=i.shift())||(".."==s&&p.length>0&&".."!=p[p.length-1]?p.pop():p.push(s));return p.join(a)},e}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerParser("twig",function(t){return new e.Template(t)})}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerParser("source",function(e){return e.data||""})}},function(e,t){e.exports=function(e){"use strict";for(e.logic={},e.logic.type={if_:"Twig.logic.type.if",endif:"Twig.logic.type.endif",for_:"Twig.logic.type.for",endfor:"Twig.logic.type.endfor",else_:"Twig.logic.type.else",elseif:"Twig.logic.type.elseif",set:"Twig.logic.type.set",setcapture:"Twig.logic.type.setcapture",endset:"Twig.logic.type.endset",filter:"Twig.logic.type.filter",endfilter:"Twig.logic.type.endfilter",shortblock:"Twig.logic.type.shortblock",block:"Twig.logic.type.block",endblock:"Twig.logic.type.endblock",extends_:"Twig.logic.type.extends",use:"Twig.logic.type.use",include:"Twig.logic.type.include",spaceless:"Twig.logic.type.spaceless",endspaceless:"Twig.logic.type.endspaceless",macro:"Twig.logic.type.macro",endmacro:"Twig.logic.type.endmacro",import_:"Twig.logic.type.import",from:"Twig.logic.type.from",embed:"Twig.logic.type.embed",endembed:"Twig.logic.type.endembed",with:"Twig.logic.type.with",endwith:"Twig.logic.type.endwith"},e.logic.definitions=[{type:e.logic.type.if_,regex:/^if\s+([\s\S]+)$/,next:[e.logic.type.else_,e.logic.type.elseif,e.logic.type.endif],open:!0,compile:function(t){var r=t.match[1];return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(i){return n=!0,e.lib.boolval(i)?(n=!1,e.parseAsync.call(o,t.output,r)):""}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.elseif,regex:/^elseif\s+([^\s].*)$/,next:[e.logic.type.else_,e.logic.type.elseif,e.logic.type.endif],open:!1,compile:function(t){var r=t.match[1];return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(i){return n&&e.lib.boolval(i)?(n=!1,e.parseAsync.call(o,t.output,r)):""}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.else_,regex:/^else$/,next:[e.logic.type.endif,e.logic.type.endfor],open:!1,parse:function(t,r,n){var o=e.Promise.resolve("");return n&&(o=e.parseAsync.call(this,t.output,r)),o.then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endif,regex:/^endif$/,next:[],open:!1},{type:e.logic.type.for_,regex:/^for\s+([a-zA-Z0-9_,\s]+)\s+in\s+([^\s].*?)(?:\s+if\s+([^\s].*))?$/,next:[e.logic.type.else_,e.logic.type.endfor],open:!0,compile:function(t){var r=t.match[1],n=t.match[2],o=t.match[3],i=null;if(t.key_var=null,t.value_var=null,r.indexOf(",")>=0){if(2!==(i=r.split(",")).length)throw new e.Error("Invalid expression in for loop: "+r);t.key_var=i[0].trim(),t.value_var=i[1].trim()}else t.value_var=r;return t.expression=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,o&&(t.conditional=e.expression.compile.call(this,{type:e.expression.type.expression,value:o}).stack),delete t.match,t},parse:function(t,r,n){var o,i,s=[],a=0,p=this,c=t.conditional,l=function(n,i){var l=e.ChildContext(r);return l[t.value_var]=i,t.key_var&&(l[t.key_var]=n),l.loop=function(e,t){var n=void 0!==c;return{index:e+1,index0:e,revindex:n?void 0:t-e,revindex0:n?void 0:t-e-1,first:0===e,last:n?void 0:e===t-1,length:n?void 0:t,parent:r}}(a,o),(void 0===c?e.Promise.resolve(!0):e.expression.parseAsync.call(p,c,l)).then(function(r){if(r)return e.parseAsync.call(p,t.output,l).then(function(e){s.push(e),a+=1})}).then(function(){delete l.loop,delete l[t.value_var],delete l[t.key_var],e.merge(r,l,!0)})};return e.expression.parseAsync.call(this,t.expression,r).then(function(t){return e.lib.isArray(t)?(o=t.length,e.async.forEach(t,function(e){return l(a,e)})):e.lib.is("Object",t)?(i=void 0!==t._keys?t._keys:Object.keys(t),o=i.length,e.async.forEach(i,function(e){if("_keys"!==e)return l(e,t[e])})):void 0}).then(function(){return{chain:0===s.length,output:e.output.call(p,s)}})}},{type:e.logic.type.endfor,regex:/^endfor$/,next:[],open:!1},{type:e.logic.type.set,regex:/^set\s+([a-zA-Z0-9_,\s]+)\s*=\s*([\s\S]+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim(),n=t.match[2],o=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack;return t.key=r,t.expression=o,delete t.match,t},parse:function(t,r,n){var o=t.key;return e.expression.parseAsync.call(this,t.expression,r).then(function(t){return t===r&&(t=e.lib.copy(t)),r[o]=t,{chain:n,context:r}})}},{type:e.logic.type.setcapture,regex:/^set\s+([a-zA-Z0-9_,\s]+)$/,next:[e.logic.type.endset],open:!0,compile:function(e){var t=e.match[1].trim();return e.key=t,delete e.match,e},parse:function(t,r,n){var o=this,i=t.key;return e.parseAsync.call(this,t.output,r).then(function(e){return o.context[i]=e,r[i]=e,{chain:n,context:r}})}},{type:e.logic.type.endset,regex:/^endset$/,next:[],open:!1},{type:e.logic.type.filter,regex:/^filter\s+(.+)$/,next:[e.logic.type.endfilter],open:!0,compile:function(t){var r="|"+t.match[1].trim();return t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,delete t.match,t},parse:function(t,r,n){var o=this;return e.parseAsync.call(this,t.output,r).then(function(n){var i=[{type:e.expression.type.string,value:n}].concat(t.stack);return e.expression.parseAsync.call(o,i,r)}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endfilter,regex:/^endfilter$/,next:[],open:!1},{type:e.logic.type.block,regex:/^block\s+([a-zA-Z0-9_]+)$/,next:[e.logic.type.endblock],open:!0,compile:function(e){return e.block=e.match[1].trim(),delete e.match,e},parse:function(t,r,n){var o,i=this,s=e.Promise.resolve(),a=e.indexOf(this.importedBlocks,t.block)>-1,p=this.blocks[t.block]&&e.indexOf(this.blocks[t.block],e.placeholders.parent)>-1;return e.forEach(this.parseStack,function(r){r.type==e.logic.type.for_&&(t.overwrite=!0)}),(void 0===this.blocks[t.block]||a||p||t.overwrite)&&(s=(s=t.expression?e.expression.parseAsync.call(this,t.output,r).then(function(t){return e.expression.parseAsync.call(i,{type:e.expression.type.string,value:t},r)}):e.parseAsync.call(this,t.output,r).then(function(t){return e.expression.parseAsync.call(i,{type:e.expression.type.string,value:t},r)})).then(function(r){a&&i.importedBlocks.splice(i.importedBlocks.indexOf(t.block),1),i.blocks[t.block]=p?e.Markup(i.blocks[t.block].replace(e.placeholders.parent,r)):r,i.originalBlockTokens[t.block]={type:t.type,block:t.block,output:t.output,overwrite:!0}})),s.then(function(){return o=i.child.blocks[t.block]?i.child.blocks[t.block]:i.blocks[t.block],{chain:n,output:o}})}},{type:e.logic.type.shortblock,regex:/^block\s+([a-zA-Z0-9_]+)\s+(.+)$/,next:[],open:!0,compile:function(t){return t.expression=t.match[2].trim(),t.output=e.expression.compile({type:e.expression.type.expression,value:t.expression}).stack,t.block=t.match[1].trim(),delete t.match,t},parse:function(t,r,n){for(var o=new Array(arguments.length),i=arguments.length;i-- >0;)o[i]=arguments[i];return e.logic.handler[e.logic.type.block].parse.apply(this,o)}},{type:e.logic.type.endblock,regex:/^endblock(?:\s+([a-zA-Z0-9_]+))?$/,next:[],open:!1},{type:e.logic.type.extends_,regex:/^extends\s+(.+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim();return delete t.match,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i=e.ChildContext(r);return e.expression.parseAsync.call(this,t.stack,r).then(function(t){return o.extend=t,(t instanceof e.Template?t:o.importFile(t)).renderAsync(i)}).then(function(){return e.lib.extend(r,i),{chain:n,output:""}})}},{type:e.logic.type.use,regex:/^use\s+(.+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim();return delete t.match,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this;return e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importBlocks(e),{chain:n,output:""}})}},{type:e.logic.type.include,regex:/^include\s+(.+?)(?:\s|$)(ignore missing(?:\s|$))?(?:with\s+([\S\s]+?))?(?:\s|$)(only)?$/,next:[],open:!0,compile:function(t){var r=t.match,n=r[1].trim(),o=void 0!==r[2],i=r[3],s=void 0!==r[4]&&r[4].length;return delete t.match,t.only=s,t.ignoreMissing=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,void 0!==i&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:i.trim()}).stack),t},parse:function(t,r,n){var o=t.only?{}:e.ChildContext(r),i=t.ignoreMissing,s=this,a={chain:n,output:""};return(void 0!==t.withStack?e.expression.parseAsync.call(this,t.withStack,r).then(function(t){e.lib.extend(o,t)}):e.Promise.resolve()).then(function(){return e.expression.parseAsync.call(s,t.stack,r)}).then(function(t){if(t instanceof e.Template)return t.renderAsync(o);try{return s.importFile(t).renderAsync(o)}catch(e){if(i)return"";throw e}}).then(function(e){return""!==e&&(a.output=e),a})}},{type:e.logic.type.spaceless,regex:/^spaceless$/,next:[e.logic.type.endspaceless],open:!0,parse:function(t,r,n){return e.parseAsync.call(this,t.output,r).then(function(t){var r=t.replace(/>\s+</g,"><").trim();return r=e.Markup(r),{chain:n,output:r}})}},{type:e.logic.type.endspaceless,regex:/^endspaceless$/,next:[],open:!1},{type:e.logic.type.macro,regex:/^macro\s+([a-zA-Z0-9_]+)\s*\(\s*((?:[a-zA-Z0-9_]+(?:\s*=\s*([\s\S]+))?(?:,\s*)?)*)\s*\)$/,next:[e.logic.type.endmacro],open:!0,compile:function(t){var r=t.match[1],n=t.match[2].split(/\s*,\s*/),o=n.map(function(e){return e.split(/\s*=\s*/)[0]}),i=o.length;if(i>1)for(var s={},a=0;a<i;a++){var p=o[a];if(s[p])throw new e.Error("Duplicate arguments for parameter: "+p);s[p]=1}return t.macroName=r,t.parameters=o,t.defaults=n.reduce(function(t,r){var n=r.split(/\s*=\s*/),o=n[0],i=n[1];return t[o]=i?e.expression.compile.call(this,{type:e.expression.type.expression,value:i}).stack:void 0,t},{}),delete t.match,t},parse:function(t,r,n){var o=this;return this.macros[t.macroName]=function(){var n={_self:o.macros},i=Array.prototype.slice.call(arguments);return e.async.forEach(t.parameters,function(o,s){return void 0!==i[s]?(n[o]=i[s],!0):void 0!==t.defaults[o]?e.expression.parseAsync.call(this,t.defaults[o],r).then(function(t){return n[o]=t,e.Promise.resolve()}):(n[o]=void 0,!0)}).then(function(){return e.parseAsync.call(o,t.output,n)})},{chain:n,output:""}}},{type:e.logic.type.endmacro,regex:/^endmacro$/,next:[],open:!1},{type:e.logic.type.import_,regex:/^import\s+(.+)\s+as\s+([a-zA-Z0-9_]+)$/,next:[],open:!0,compile:function(t){var r=t.match[1].trim(),n=t.match[2].trim();return delete t.match,t.expression=r,t.contextName=n,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i={chain:n,output:""};return"_self"===t.expression?(r[t.contextName]=this.macros,e.Promise.resolve(i)):e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importFile(e||t.expression)}).then(function(e){return r[t.contextName]=e.renderAsync({},{output:"macros"}),i})}},{type:e.logic.type.from,regex:/^from\s+(.+)\s+import\s+([a-zA-Z0-9_, ]+)$/,next:[],open:!0,compile:function(t){for(var r=t.match[1].trim(),n=t.match[2].trim().split(/\s*,\s*/),o={},i=0;i<n.length;i++){var s=n[i],a=s.match(/^([a-zA-Z0-9_]+)\s+as\s+([a-zA-Z0-9_]+)$/);a?o[a[1].trim()]=a[2].trim():s.match(/^([a-zA-Z0-9_]+)$/)&&(o[s]=s)}return delete t.match,t.expression=r,t.macroNames=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:r}).stack,t},parse:function(t,r,n){var o=this,i=e.Promise.resolve(this.macros);return"_self"!==t.expression&&(i=e.expression.parseAsync.call(this,t.stack,r).then(function(e){return o.importFile(e||t.expression)}).then(function(e){return e.renderAsync({},{output:"macros"})})),i.then(function(e){for(var o in t.macroNames)e.hasOwnProperty(o)&&(r[t.macroNames[o]]=e[o]);return{chain:n,output:""}})}},{type:e.logic.type.embed,regex:/^embed\s+(.+?)(?:\s+(ignore missing))?(?:\s+with\s+([\S\s]+?))?(?:\s+(only))?$/,next:[e.logic.type.endembed],open:!0,compile:function(t){var r=t.match,n=r[1].trim(),o=void 0!==r[2],i=r[3],s=void 0!==r[4]&&r[4].length;return delete t.match,t.only=s,t.ignoreMissing=o,t.stack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n}).stack,void 0!==i&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:i.trim()}).stack),t},parse:function(t,r,n){var o,i,s={},a=this,p=e.Promise.resolve();if(!t.only)for(o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);return void 0!==t.withStack&&(p=e.expression.parseAsync.call(this,t.withStack,r).then(function(e){for(o in e)e.hasOwnProperty(o)&&(s[o]=e[o])})),p.then(function(){return p=null,e.expression.parseAsync.call(a,t.stack,s)}).then(function(r){if(r instanceof e.Template)i=r;else try{i=a.importFile(r)}catch(e){if(t.ignoreMissing)return"";throw a=null,e}return a._blocks=e.lib.copy(a.blocks),a.blocks={},e.parseAsync.call(a,t.output,s).then(function(){return i.renderAsync(s,{blocks:a.blocks})})}).then(function(t){return a.blocks=e.lib.copy(a._blocks),{chain:n,output:t}})}},{type:e.logic.type.endembed,regex:/^endembed$/,next:[],open:!1},{type:e.logic.type.with,regex:/^(?:with\s+([\S\s]+?))(?:\s|$)(only)?$/,next:[e.logic.type.endwith],open:!0,compile:function(t){var r=t.match,n=r[1],o=void 0!==r[2]&&r[2].length;return delete t.match,t.only=o,void 0!==n&&(t.withStack=e.expression.compile.call(this,{type:e.expression.type.expression,value:n.trim()}).stack),t},parse:function(t,r,n){var o,i={},s=this,a=e.Promise.resolve();return t.only||(i=e.ChildContext(r)),void 0!==t.withStack&&(a=e.expression.parseAsync.call(this,t.withStack,r).then(function(e){for(o in e)e.hasOwnProperty(o)&&(i[o]=e[o])})),a.then(function(){return e.parseAsync.call(s,t.output,i)}).then(function(e){return{chain:n,output:e}})}},{type:e.logic.type.endwith,regex:/^endwith$/,next:[],open:!1}],e.logic.handler={},e.logic.extendType=function(t,r){r=r||"Twig.logic.type"+t,e.logic.type[t]=r},e.logic.extend=function(t){if(!t.type)throw new e.Error("Unable to extend logic definition. No type provided for "+t);e.logic.extendType(t.type),e.logic.handler[t.type]=t};e.logic.definitions.length>0;)e.logic.extend(e.logic.definitions.shift());return e.logic.compile=function(t){var r=t.value.trim(),n=e.logic.tokenize.call(this,r),o=e.logic.handler[n.type];return o.compile&&(n=o.compile.call(this,n),e.log.trace("Twig.logic.compile: ","Compiled logic token to ",n)),n},e.logic.tokenize=function(t){var r=null,n=null,o=null,i=null,s=null,a=null,p=null;for(r in t=t.trim(),e.logic.handler)for(n=e.logic.handler[r].type,i=o=e.logic.handler[r].regex,e.lib.isArray(o)||(i=[o]),s=i.length,a=0;a<s;a++)if(null!==(p=i[a].exec(t)))return e.log.trace("Twig.logic.tokenize: ","Matched a ",n," regular expression of ",p),{type:n,match:p};throw new e.Error("Unable to parse '"+t.trim()+"'")},e.logic.parse=function(t,r,n,o){return e.async.potentiallyAsync(this,o,function(){e.log.debug("Twig.logic.parse: ","Parsing logic token ",t);var o,i=e.logic.handler[t.type],s=this;return i.parse?(s.parseStack.unshift(t),o=i.parse.call(s,t,r||{},n),e.isPromise(o)?o=o.then(function(e){return s.parseStack.shift(),e}):s.parseStack.shift(),o):""})},e}},function(e,t){e.exports=require("fs")},function(e,t,r){e.exports=function(e){"use strict";var t,n;try{t=r(9),n=r(0)}catch(e){}e.Templates.registerLoader("fs",function(r,o,i,s){var a,p=null,c=o.precompiled,l=this.parsers[o.parser]||this.parser.twig;if(!t||!n)throw new e.Error('Unsupported platform: Unable to load from file because there is no "fs" or "path" implementation');var u=function(e,t){e?"function"==typeof s&&s(e):(!0===c&&(t=JSON.parse(t)),o.data=t,o.path=o.path||r,a=l.call(this,o),"function"==typeof i&&i(a))};if(o.path=o.path||r,o.async)return t.stat(o.path,function(r,n){!r&&n.isFile()?t.readFile(o.path,"utf8",u):"function"==typeof s&&s(new e.Error("Unable to find template file "+o.path))}),!0;try{if(!t.statSync(o.path).isFile())throw new e.Error("Unable to find template file "+o.path)}catch(t){throw new e.Error("Unable to find template file "+o.path)}return p=t.readFileSync(o.path,"utf8"),u(void 0,p),a})}},function(e,t){e.exports=function(e){"use strict";e.Templates.registerLoader("ajax",function(t,r,n,o){var i,s,a=r.precompiled,p=this.parsers[r.parser]||this.parser.twig;if("undefined"==typeof XMLHttpRequest)throw new e.Error('Unsupported platform: Unable to do ajax requests because there is no "XMLHTTPRequest" implementation');return(s=new XMLHttpRequest).onreadystatechange=function(){var c=null;4===s.readyState&&(200===s.status||window.cordova&&0==s.status?(e.log.debug("Got template ",s.responseText),c=!0===a?JSON.parse(s.responseText):s.responseText,r.url=t,r.data=c,i=p.call(this,r),"function"==typeof n&&n(i)):"function"==typeof o&&o(s))},s.open("GET",t,!!r.async),s.send(),!!r.async||i})}},function(e,t,r){"use strict";e.exports=function(e){return!1!==e&&(0!==e&&0!==e&&(""!==e&&"0"!==e&&((!Array.isArray(e)||0!==e.length)&&(null!==e&&void 0!==e))))}},function(e,t,r){"use strict";e.exports=function(e,t){var r,n,o=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur","January","February","March","April","May","June","July","August","September","October","November","December"],i=/\\?(.?)/gi,s=function(e,t){return n[e]?n[e]():t},a=function(e,t){for(e=String(e);e.length<t;)e="0"+e;return e};n={d:function(){return a(n.j(),2)},D:function(){return n.l().slice(0,3)},j:function(){return r.getDate()},l:function(){return o[n.w()]+"day"},N:function(){return n.w()||7},S:function(){var e=n.j(),t=e%10;return t<=3&&1===parseInt(e%100/10,10)&&(t=0),["st","nd","rd"][t-1]||"th"},w:function(){return r.getDay()},z:function(){var e=new Date(n.Y(),n.n()-1,n.j()),t=new Date(n.Y(),0,1);return Math.round((e-t)/864e5)},W:function(){var e=new Date(n.Y(),n.n()-1,n.j()-n.N()+3),t=new Date(e.getFullYear(),0,4);return a(1+Math.round((e-t)/864e5/7),2)},F:function(){return o[6+n.n()]},m:function(){return a(n.n(),2)},M:function(){return n.F().slice(0,3)},n:function(){return r.getMonth()+1},t:function(){return new Date(n.Y(),n.n(),0).getDate()},L:function(){var e=n.Y();return e%4==0&e%100!=0|e%400==0},o:function(){var e=n.n(),t=n.W();return n.Y()+(12===e&&t<9?1:1===e&&t>9?-1:0)},Y:function(){return r.getFullYear()},y:function(){return n.Y().toString().slice(-2)},a:function(){return r.getHours()>11?"pm":"am"},A:function(){return n.a().toUpperCase()},B:function(){var e=3600*r.getUTCHours(),t=60*r.getUTCMinutes(),n=r.getUTCSeconds();return a(Math.floor((e+t+n+3600)/86.4)%1e3,3)},g:function(){return n.G()%12||12},G:function(){return r.getHours()},h:function(){return a(n.g(),2)},H:function(){return a(n.G(),2)},i:function(){return a(r.getMinutes(),2)},s:function(){return a(r.getSeconds(),2)},u:function(){return a(1e3*r.getMilliseconds(),6)},e:function(){throw new Error("Not supported (see source code of date() for timezone on how to add support)")},I:function(){return new Date(n.Y(),0)-Date.UTC(n.Y(),0)!=new Date(n.Y(),6)-Date.UTC(n.Y(),6)?1:0},O:function(){var e=r.getTimezoneOffset(),t=Math.abs(e);return(e>0?"-":"+")+a(100*Math.floor(t/60)+t%60,4)},P:function(){var e=n.O();return e.substr(0,3)+":"+e.substr(3,2)},T:function(){return"UTC"},Z:function(){return 60*-r.getTimezoneOffset()},c:function(){return"Y-m-d\\TH:i:sP".replace(i,s)},r:function(){return"D, d M Y H:i:s O".replace(i,s)},U:function(){return r/1e3|0}};return function(e,t){return r=void 0===t?new Date:t instanceof Date?new Date(t):new Date(1e3*t),e.replace(i,s)}(e,t)}},function(e,t,r){"use strict";e.exports=function(e,t){var r,n,o,i,s,a,p,c,l,u,f;if(!e)return!1;e=e.replace(/^\s+|\s+$/g,"").replace(/\s{2,}/g," ").replace(/[\t\r\n]/g,"").toLowerCase();var h=new RegExp(["^(\\d{1,4})","([\\-\\.\\/:])","(\\d{1,2})","([\\-\\.\\/:])","(\\d{1,4})","(?:\\s(\\d{1,2}):(\\d{2})?:?(\\d{2})?)?","(?:\\s([A-Z]+)?)?$"].join(""));if((n=e.match(h))&&n[2]===n[4])if(n[1]>1901)switch(n[2]){case"-":return!(n[3]>12||n[5]>31)&&new Date(n[1],parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3;case".":return!1;case"/":return!(n[3]>12||n[5]>31)&&new Date(n[1],parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3}else if(n[5]>1901)switch(n[2]){case"-":case".":return!(n[3]>12||n[1]>31)&&new Date(n[5],parseInt(n[3],10)-1,n[1],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3;case"/":return!(n[1]>12||n[3]>31)&&new Date(n[5],parseInt(n[1],10)-1,n[3],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3}else switch(n[2]){case"-":return!(n[3]>12||n[5]>31||n[1]<70&&n[1]>38)&&(i=n[1]>=0&&n[1]<=38?+n[1]+2e3:n[1],new Date(i,parseInt(n[3],10)-1,n[5],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3);case".":return n[5]>=70?!(n[3]>12||n[1]>31)&&new Date(n[5],parseInt(n[3],10)-1,n[1],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3:n[5]<60&&!n[6]&&(!(n[1]>23||n[3]>59)&&(o=new Date,new Date(o.getFullYear(),o.getMonth(),o.getDate(),n[1]||0,n[3]||0,n[5]||0,n[9]||0)/1e3));case"/":return!(n[1]>12||n[3]>31||n[5]<70&&n[5]>38)&&(i=n[5]>=0&&n[5]<=38?+n[5]+2e3:n[5],new Date(i,parseInt(n[1],10)-1,n[3],n[6]||0,n[7]||0,n[8]||0,n[9]||0)/1e3);case":":return!(n[1]>23||n[3]>59||n[5]>59)&&(o=new Date,new Date(o.getFullYear(),o.getMonth(),o.getDate(),n[1]||0,n[3]||0,n[5]||0)/1e3)}if("now"===e)return null===t||isNaN(t)?(new Date).getTime()/1e3|0:0|t;if(!isNaN(r=Date.parse(e)))return r/1e3|0;if(h=new RegExp(["^([0-9]{4}-[0-9]{2}-[0-9]{2})","[ t]","([0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?)","([\\+-][0-9]{2}(:[0-9]{2})?|z)"].join("")),(n=e.match(h))&&("z"===n[4]?n[4]="Z":n[4].match(/^([+-][0-9]{2})$/)&&(n[4]=n[4]+":00"),!isNaN(r=Date.parse(n[1]+"T"+n[2]+n[4]))))return r/1e3|0;function y(e){var t=e.split(" "),r=t[0],n=t[1].substring(0,3),o=/\d+/.test(r),i="ago"===t[2],c=("last"===r?-1:1)*(i?-1:1);if(o&&(c*=parseInt(r,10)),p.hasOwnProperty(n)&&!t[1].match(/^mon(day|\.)?$/i))return s["set"+p[n]](s["get"+p[n]]()+c);if("wee"===n)return s.setDate(s.getDate()+7*c);if("next"===r||"last"===r)!function(e,t,r){var n,o=a[t];void 0!==o&&(0==(n=o-s.getDay())?n=7*r:n>0&&"last"===e?n-=7:n<0&&"next"===e&&(n+=7),s.setDate(s.getDate()+n))}(r,n,c);else if(!o)return!1;return!0}if(s=t?new Date(1e3*t):new Date,a={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6},p={yea:"FullYear",mon:"Month",day:"Date",hou:"Hours",min:"Minutes",sec:"Seconds"},u="([+-]?\\d+\\s"+(l="(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)")+"|(last|next)\\s"+l+")(\\sago)?",!(n=e.match(new RegExp(u,"gi"))))return!1;for(f=0,c=n.length;f<c;f++)if(!y(n[f]))return!1;return s.getTime()/1e3}},function(e,t,r){"use strict";e.exports=function(e,t){t=(((t||"")+"").toLowerCase().match(/<[a-z][a-z0-9]*>/g)||[]).join("");return e.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi,"").replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,function(e,r){return t.indexOf("<"+r.toLowerCase()+">")>-1?e:""})}},function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.exports=function(){var e,t,r,o=0,i=arguments,s=i.length,a=function(e){if("[object Array]"===Object.prototype.toString.call(e))return e;var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t},p=function e(t,r){var o=0,i=0,s=0,p=0,c=0;if(t===r)return 0;if("object"===(void 0===t?"undefined":n(t))){if("object"===(void 0===r?"undefined":n(r))){if(t=a(t),r=a(r),c=t.length,(p=r.length)>c)return 1;if(p<c)return-1;for(o=0,i=c;o<i;++o){if(1===(s=e(t[o],r[o])))return 1;if(-1===s)return-1}return 0}return-1}return"object"===(void 0===r?"undefined":n(r))?1:isNaN(r)&&!isNaN(t)?0===t?0:t<0?1:-1:isNaN(t)&&!isNaN(r)?0===r?0:r>0?1:-1:r===t?0:r>t?1:-1};if(0===s)throw new Error("At least one value should be passed to min()");if(1===s){if("object"!==n(i[0]))throw new Error("Wrong parameter count for min()");if(0===(e=a(i[0])).length)throw new Error("Array must contain at least one element for min()")}else e=i;for(t=e[0],o=1,r=e.length;o<r;++o)-1===p(t,e[o])&&(t=e[o]);return t}},function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};e.exports=function(){var e,t,r,o=0,i=arguments,s=i.length,a=function(e){if("[object Array]"===Object.prototype.toString.call(e))return e;var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t},p=function e(t,r){var o=0,i=0,s=0,p=0,c=0;if(t===r)return 0;if("object"===(void 0===t?"undefined":n(t))){if("object"===(void 0===r?"undefined":n(r))){if(t=a(t),r=a(r),c=t.length,(p=r.length)>c)return 1;if(p<c)return-1;for(o=0,i=c;o<i;++o){if(1===(s=e(t[o],r[o])))return 1;if(-1===s)return-1}return 0}return-1}return"object"===(void 0===r?"undefined":n(r))?1:isNaN(r)&&!isNaN(t)?0===t?0:t<0?1:-1:isNaN(t)&&!isNaN(r)?0===r?0:r>0?1:-1:r===t?0:r>t?1:-1};if(0===s)throw new Error("At least one value should be passed to max()");if(1===s){if("object"!==n(i[0]))throw new Error("Wrong parameter count for max()");if(0===(e=a(i[0])).length)throw new Error("Array must contain at least one element for max()")}else e=i;for(t=e[0],o=1,r=e.length;o<r;++o)1===p(t,e[o])&&(t=e[o]);return t}},function(e,t,r){"use strict";e.exports=function(e,t,r){var n,o,i,s;if(t|=0,i=(e*=n=Math.pow(10,t))%1==.5*(s=e>0|-(e<0)),o=Math.floor(e),i)switch(r){case"PHP_ROUND_HALF_DOWN":e=o+(s<0);break;case"PHP_ROUND_HALF_EVEN":e=o+o%2*s;break;case"PHP_ROUND_HALF_ODD":e=o+!(o%2);break;default:e=o+(s>0)}return(i?e:Math.round(e))/n}},function(e,t,r){"use strict";e.exports=function(e,t){return r(1).apply(this,[e].concat(t))}},function(e,t,r){e.exports=function(e){e.lib={},e.lib.sprintf=r(1),e.lib.vsprintf=r(19),e.lib.round=r(18),e.lib.max=r(17),e.lib.min=r(16),e.lib.strip_tags=r(15),e.lib.strtotime=r(14),e.lib.date=r(13),e.lib.boolval=r(12);var t=Object.prototype.toString;return e.lib.is=function(e,r){return void 0!==r&&null!==r&&("Array"===e&&Array.isArray?Array.isArray(r):t.call(r).slice(8,-1)===e)},e.lib.isArray=Array.isArray||function(e){return"Array"===t.call(e).slice(8,-1)},e.lib.copy=function(e){var t,r={};for(t in e)r[t]=e[t];return r},e.lib.extend=function(e,t){var r,n=Object.keys(t);for(r=n.length;r--;)e[n[r]]=t[n[r]];return e},e.lib.replaceAll=function(e,t,r){return e.split(t).join(r)},e.lib.chunkArray=function(t,r){var n=[],o=0,i=t.length;if(r<1||!e.lib.is("Array",t))return[];for(;o<i;)n.push(t.slice(o,o+=r));return n},e}},function(e,t){e.exports=function(t){return t.functions={range:function(e,t,r){var n,o,i=[],s=r||1,a=!1;if(isNaN(e)||isNaN(t)?isNaN(e)&&isNaN(t)?(a=!0,n=e.charCodeAt(0),o=t.charCodeAt(0)):(n=isNaN(e)?0:e,o=isNaN(t)?0:t):(n=parseInt(e,10),o=parseInt(t,10)),!(n>o))for(;n<=o;)i.push(a?String.fromCharCode(n):n),n+=s;else for(;n>=o;)i.push(a?String.fromCharCode(n):n),n-=s;return i},cycle:function(e,t){return e[t%e.length]},dump:function(){var e=arguments.length;for(args=new Array(e);e-- >0;)args[e]=arguments[e];var r=0,n="",o=function(e){for(var t="";e>0;)e--,t+=" ";return t},i=function(e){n+=o(r),"object"==typeof e?s(e):"function"==typeof e?n+="function()\n":"string"==typeof e?n+="string("+e.length+') "'+e+'"\n':"number"==typeof e?n+="number("+e+")\n":"boolean"==typeof e&&(n+="bool("+e+")\n")},s=function(e){var t;if(null===e)n+="NULL\n";else if(void 0===e)n+="undefined\n";else if("object"==typeof e){for(t in n+=o(r)+typeof e,r++,n+="("+function(e){var t,r=0;for(t in e)e.hasOwnProperty(t)&&r++;return r}(e)+") {\n",e)n+=o(r)+"["+t+"]=> \n",i(e[t]);n+=o(--r)+"}\n"}else i(e)};return 0==args.length&&args.push(this.context),t.forEach(args,function(e){s(e)}),n},date:function(e,r){var n;if(void 0===e||null===e||""===e)n=new Date;else if(t.lib.is("Date",e))n=e;else if(t.lib.is("String",e))n=e.match(/^[0-9]+$/)?new Date(1e3*e):new Date(1e3*t.lib.strtotime(e));else{if(!t.lib.is("Number",e))throw new t.Error("Unable to parse date "+e);n=new Date(1e3*e)}return n},block:function(e){return this.originalBlockTokens[e]?t.logic.parse.call(this,this.originalBlockTokens[e],this.context).output:this.blocks[e]},parent:function(){return t.placeholders.parent},attribute:function(e,r,n){return t.lib.is("Object",e)&&e.hasOwnProperty(r)?"function"==typeof e[r]?e[r].apply(void 0,n):e[r]:e[r]||void 0},max:function(e){return t.lib.is("Object",e)?(delete e._keys,t.lib.max(e)):t.lib.max.apply(null,arguments)},min:function(e){return t.lib.is("Object",e)?(delete e._keys,t.lib.min(e)):t.lib.min.apply(null,arguments)},template_from_string:function(e){return void 0===e&&(e=""),t.Templates.parsers.twig({options:this.options,data:e})},random:function(e){var r=2147483648;function n(e){var t=Math.floor(Math.random()*r),n=Math.min.call(null,0,e),o=Math.max.call(null,0,e);return n+Math.floor((o-n+1)*t/r)}if(t.lib.is("Number",e))return n(e);if(t.lib.is("String",e))return e.charAt(n(e.length-1));if(t.lib.is("Array",e))return e[n(e.length-1)];if(t.lib.is("Object",e)){var o=Object.keys(e);return e[o[n(o.length-1)]]}return n(r-1)},source:function(r,n){var o,i,s,a=!1;void 0!==e&&void 0!==e.exports&&"undefined"==typeof window?(i="fs",s=__dirname+"/"+r):(i="ajax",s=r);var p={id:r,path:s,method:i,parser:"source",async:!1,fetchTemplateSource:!0};void 0===n&&(n=!1);try{void 0===(o=t.Templates.loadRemote(r,p))||null===o?o="":a=!0}catch(e){t.log.debug("Twig.functions.source: ","Problem loading template ",e)}return a||n?o:'Template "{name}" is not defined.'.replace("{name}",r)}},t._function=function(e,r,n){if(!t.functions[e])throw"Unable to find function "+e;return t.functions[e](r,n)},t._function.extend=function(e,r){t.functions[e]=r},t}},function(e,t){e.exports=function(e){function t(e,t){var r=Object.prototype.toString.call(t).slice(8,-1);return void 0!==t&&null!==t&&r===e}return e.filters={upper:function(e){return"string"!=typeof e?e:e.toUpperCase()},lower:function(e){return"string"!=typeof e?e:e.toLowerCase()},capitalize:function(e){return"string"!=typeof e?e:e.substr(0,1).toUpperCase()+e.toLowerCase().substr(1)},title:function(e){return"string"!=typeof e?e:e.toLowerCase().replace(/(^|\s)([a-z])/g,function(e,t,r){return t+r.toUpperCase()})},length:function(t){return e.lib.is("Array",t)||"string"==typeof t?t.length:e.lib.is("Object",t)?void 0===t._keys?Object.keys(t).length:t._keys.length:0},reverse:function(e){if(t("Array",e))return e.reverse();if(t("String",e))return e.split("").reverse().join("");if(t("Object",e)){var r=e._keys||Object.keys(e).reverse();return e._keys=r,e}},sort:function(e){if(t("Array",e))return e.sort();if(t("Object",e)){delete e._keys;var r=Object.keys(e).sort(function(t,r){var n;return e[t]>e[r]==!(e[t]<=e[r])?e[t]>e[r]?1:e[t]<e[r]?-1:0:isNaN(n=parseFloat(e[t]))||isNaN(b1=parseFloat(e[r]))?"string"==typeof e[t]?e[t]>e[r].toString()?1:e[t]<e[r].toString()?-1:0:"string"==typeof e[r]?e[t].toString()>e[r]?1:e[t].toString()<e[r]?-1:0:null:n>b1?1:n<b1?-1:0});return e._keys=r,e}},keys:function(t){if(void 0!==t&&null!==t){var r=t._keys||Object.keys(t),n=[];return e.forEach(r,function(e){"_keys"!==e&&t.hasOwnProperty(e)&&n.push(e)}),n}},url_encode:function(e){if(void 0!==e&&null!==e){var t=encodeURIComponent(e);return t=t.replace("'","%27")}},join:function(r,n){if(void 0!==r&&null!==r){var o="",i=[],s=null;return n&&n[0]&&(o=n[0]),t("Array",r)?i=r:(s=r._keys||Object.keys(r),e.forEach(s,function(e){"_keys"!==e&&r.hasOwnProperty(e)&&i.push(r[e])})),i.join(o)}},default:function(t,r){if(void 0!==r&&r.length>1)throw new e.Error("default filter expects one argument");return void 0===t||null===t||""===t?void 0===r?"":r[0]:t},json_encode:function(r){if(void 0===r||null===r)return"null";if("object"==typeof r&&t("Array",r))return o=[],e.forEach(r,function(t){o.push(e.filters.json_encode(t))}),"["+o.join(",")+"]";if("object"==typeof r&&t("Date",r))return'"'+r.toISOString()+'"';if("object"==typeof r){var n=r._keys||Object.keys(r),o=[];return e.forEach(n,function(t){o.push(JSON.stringify(t)+":"+e.filters.json_encode(r[t]))}),"{"+o.join(",")+"}"}return JSON.stringify(r)},merge:function(r,n){var o=[],i=0,s=[];if(t("Array",r)?e.forEach(n,function(e){t("Array",e)||(o={})}):o={},t("Array",o)||(o._keys=[]),t("Array",r)?e.forEach(r,function(e){o._keys&&o._keys.push(i),o[i]=e,i++}):(s=r._keys||Object.keys(r),e.forEach(s,function(e){o[e]=r[e],o._keys.push(e);var t=parseInt(e,10);!isNaN(t)&&t>=i&&(i=t+1)})),e.forEach(n,function(r){t("Array",r)?e.forEach(r,function(e){o._keys&&o._keys.push(i),o[i]=e,i++}):(s=r._keys||Object.keys(r),e.forEach(s,function(e){o[e]||o._keys.push(e),o[e]=r[e];var t=parseInt(e,10);!isNaN(t)&&t>=i&&(i=t+1)}))}),0===n.length)throw new e.Error("Filter merge expects at least one parameter");return o},date:function(t,r){var n=e.functions.date(t),o=r&&r.length?r[0]:"F j, Y H:i";return e.lib.date(o,n)},date_modify:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||1!==r.length)throw new e.Error("date_modify filter expects 1 argument");var n,o=r[0];return e.lib.is("Date",t)&&(n=e.lib.strtotime(o,t.getTime()/1e3)),e.lib.is("String",t)&&(n=e.lib.strtotime(o,e.lib.strtotime(t))),e.lib.is("Number",t)&&(n=e.lib.strtotime(o,t)),new Date(1e3*n)}},replace:function(t,r){if(void 0!==t&&null!==t){var n,o=r[0];for(n in o)o.hasOwnProperty(n)&&"_keys"!==n&&(t=e.lib.replaceAll(t,n,o[n]));return t}},format:function(t,r){if(void 0!==t&&null!==t)return e.lib.vsprintf(t,r)},striptags:function(t,r){if(void 0!==t&&null!==t)return e.lib.strip_tags(t,r)},escape:function(t,r){if(void 0!==t&&null!==t){var n="html";if(r&&r.length&&!0!==r[0]&&(n=r[0]),"html"==n){var o=t.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");return e.Markup(o,"html")}if("js"==n){o=t.toString();for(var i="",s=0;s<o.length;s++){if(o[s].match(/^[a-zA-Z0-9,\._]$/))i+=o[s];else i+=(a=o.charCodeAt(s))<128?"\\x"+a.toString(16).toUpperCase():e.lib.sprintf("\\u%04s",a.toString(16).toUpperCase())}return e.Markup(i,"js")}if("css"==n){for(o=t.toString(),i="",s=0;s<o.length;s++){if(o[s].match(/^[a-zA-Z0-9]$/))i+=o[s];else i+="\\"+(a=o.charCodeAt(s)).toString(16).toUpperCase()+" "}return e.Markup(i,"css")}if("url"==n){i=e.filters.url_encode(t);return e.Markup(i,"url")}if("html_attr"==n){for(o=t.toString(),i="",s=0;s<o.length;s++)if(o[s].match(/^[a-zA-Z0-9,\.\-_]$/))i+=o[s];else if(o[s].match(/^[&<>"]$/))i+=o[s].replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");else{var a;i+=(a=o.charCodeAt(s))<=31&&9!=a&&10!=a&&13!=a?"�":a<128?e.lib.sprintf("&#x%02s;",a.toString(16).toUpperCase()):e.lib.sprintf("&#x%04s;",a.toString(16).toUpperCase())}return e.Markup(i,"html_attr")}throw new e.Error("escape strategy unsupported")}},e:function(t,r){return e.filters.escape(t,r)},nl2br:function(t){if(void 0!==t&&null!==t){var r="<br />BACKSLASH_n_replace";return t=e.filters.escape(t).replace(/\r\n/g,r).replace(/\r/g,r).replace(/\n/g,r),t=e.lib.replaceAll(t,"BACKSLASH_n_replace","\n"),e.Markup(t)}},number_format:function(e,t){var r=e,n=t&&t[0]?t[0]:void 0,o=t&&void 0!==t[1]?t[1]:".",i=t&&void 0!==t[2]?t[2]:",";r=(r+"").replace(/[^0-9+\-Ee.]/g,"");var s=isFinite(+r)?+r:0,a=isFinite(+n)?Math.abs(n):0,p="";return(p=(a?function(e,t){var r=Math.pow(10,t);return""+Math.round(e*r)/r}(s,a):""+Math.round(s)).split("."))[0].length>3&&(p[0]=p[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,i)),(p[1]||"").length<a&&(p[1]=p[1]||"",p[1]+=new Array(a-p[1].length+1).join("0")),p.join(o)},trim:function(e,t){if(void 0!==e&&null!==e){var r,n=""+e;r=t&&t[0]?""+t[0]:" \n\r\t\f\v \u2028\u2029 ";for(var o=0;o<n.length;o++)if(-1===r.indexOf(n.charAt(o))){n=n.substring(o);break}for(o=n.length-1;o>=0;o--)if(-1===r.indexOf(n.charAt(o))){n=n.substring(0,o+1);break}return-1===r.indexOf(n.charAt(0))?n:""}},truncate:function(e,t){var r=30,n=!1,o="...";if(e+="",t&&(t[0]&&(r=t[0]),t[1]&&(n=t[1]),t[2]&&(o=t[2])),e.length>r){if(n&&-1===(r=e.indexOf(" ",r)))return e;e=e.substr(0,r)+o}return e},slice:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||r.length<1)throw new e.Error("slice filter expects at least 1 argument");var n=r[0]||0,o=r.length>1?r[1]:t.length,i=n>=0?n:Math.max(t.length+n,0);if(e.lib.is("Array",t)){for(var s=[],a=i;a<i+o&&a<t.length;a++)s.push(t[a]);return s}if(e.lib.is("String",t))return t.substr(i,o);throw new e.Error("slice filter expects value to be an array or string")}},abs:function(e){if(void 0!==e&&null!==e)return Math.abs(e)},first:function(e){if(t("Array",e))return e[0];if(t("Object",e)){if("_keys"in e)return e[e._keys[0]]}else if("string"==typeof e)return e.substr(0,1)},split:function(t,r){if(void 0!==t&&null!==t){if(void 0===r||r.length<1||r.length>2)throw new e.Error("split filter expects 1 or 2 argument");if(e.lib.is("String",t)){var n=r[0],o=r[1],i=t.split(n);if(void 0===o)return i;if(o<0)return t.split(n,i.length+o);var s=[];if(""==n)for(;i.length>0;){for(var a="",p=0;p<o&&i.length>0;p++)a+=i.shift();s.push(a)}else{for(p=0;p<o-1&&i.length>0;p++)s.push(i.shift());i.length>0&&s.push(i.join(n))}return s}throw new e.Error("split filter expects value to be a string")}},last:function(t){var r;return e.lib.is("Object",t)?t[(r=void 0===t._keys?Object.keys(t):t._keys)[r.length-1]]:t[t.length-1]},raw:function(t){return e.Markup(t)},batch:function(t,r){var n,o,i,s=r.shift(),a=r.shift();if(!e.lib.is("Array",t))throw new e.Error("batch filter expects items to be an array");if(!e.lib.is("Number",s))throw new e.Error("batch filter expects size to be a number");if(s=Math.ceil(s),n=e.lib.chunkArray(t,s),a&&t.length%s!=0){for(i=s-(o=n.pop()).length;i--;)o.push(a);n.push(o)}return n},round:function(t,r){var n=(r=r||[]).length>0?r[0]:0,o=r.length>1?r[1]:"common";if(t=parseFloat(t),n&&!e.lib.is("Number",n))throw new e.Error("round filter expects precision to be a number");if("common"===o)return e.lib.round(t,n);if(!e.lib.is("Function",Math[o]))throw new e.Error("round filter expects method to be 'floor', 'ceil', or 'common'");return Math[o](t*Math.pow(10,n))/Math.pow(10,n)}},e.filter=function(t,r,n){if(!e.filters[t])throw"Unable to find filter "+t;return e.filters[t].call(this,r,n)},e.filter.extend=function(t,r){e.filters[t]=r},e}},function(e,t){e.exports=function(e){"use strict";e.expression.operator={leftToRight:"leftToRight",rightToLeft:"rightToLeft"};var t=function(e,t){if(void 0===t||null===t)return null;if(void 0!==t.indexOf)return e===t||""!==e&&t.indexOf(e)>-1;var r;for(r in t)if(t.hasOwnProperty(r)&&t[r]===e)return!0;return!1};return e.expression.operator.lookup=function(t,r){switch(t){case"..":r.precidence=20,r.associativity=e.expression.operator.leftToRight;break;case",":r.precidence=18,r.associativity=e.expression.operator.leftToRight;break;case"?:":case"?":case":":r.precidence=16,r.associativity=e.expression.operator.rightToLeft;break;case"or":r.precidence=14,r.associativity=e.expression.operator.leftToRight;break;case"and":r.precidence=13,r.associativity=e.expression.operator.leftToRight;break;case"b-or":r.precidence=12,r.associativity=e.expression.operator.leftToRight;break;case"b-xor":r.precidence=11,r.associativity=e.expression.operator.leftToRight;break;case"b-and":r.precidence=10,r.associativity=e.expression.operator.leftToRight;break;case"==":case"!=":r.precidence=9,r.associativity=e.expression.operator.leftToRight;break;case"<":case"<=":case">":case">=":case"not in":case"in":r.precidence=8,r.associativity=e.expression.operator.leftToRight;break;case"~":case"+":case"-":r.precidence=6,r.associativity=e.expression.operator.leftToRight;break;case"//":case"**":case"*":case"/":case"%":r.precidence=5,r.associativity=e.expression.operator.leftToRight;break;case"not":r.precidence=3,r.associativity=e.expression.operator.rightToLeft;break;default:throw new e.Error("Failed to lookup operator: "+t+" is an unknown operator.")}return r.operator=t,r},e.expression.operator.parse=function(r,n){var o,i,s;switch(e.log.trace("Twig.expression.operator.parse: ","Handling ",r),"?"===r&&(s=n.pop()),i=n.pop(),"not"!==r&&(o=n.pop()),"in"!==r&&"not in"!==r&&(o&&Array.isArray(o)&&(o=o.length),i&&Array.isArray(i)&&(i=i.length)),r){case":":break;case"?:":e.lib.boolval(o)?n.push(o):n.push(i);break;case"?":void 0===o&&(o=i,i=s,s=void 0),e.lib.boolval(o)?n.push(i):n.push(s);break;case"+":i=parseFloat(i),o=parseFloat(o),n.push(o+i);break;case"-":i=parseFloat(i),o=parseFloat(o),n.push(o-i);break;case"*":i=parseFloat(i),o=parseFloat(o),n.push(o*i);break;case"/":i=parseFloat(i),o=parseFloat(o),n.push(o/i);break;case"//":i=parseFloat(i),o=parseFloat(o),n.push(Math.floor(o/i));break;case"%":i=parseFloat(i),o=parseFloat(o),n.push(o%i);break;case"~":n.push((null!=o?o.toString():"")+(null!=i?i.toString():""));break;case"not":case"!":n.push(!e.lib.boolval(i));break;case"<":n.push(o<i);break;case"<=":n.push(o<=i);break;case">":n.push(o>i);break;case">=":n.push(o>=i);break;case"===":n.push(o===i);break;case"==":n.push(o==i);break;case"!==":n.push(o!==i);break;case"!=":n.push(o!=i);break;case"or":n.push(e.lib.boolval(o)||e.lib.boolval(i));break;case"b-or":n.push(o|i);break;case"b-xor":n.push(o^i);break;case"and":n.push(e.lib.boolval(o)&&e.lib.boolval(i));break;case"b-and":n.push(o&i);break;case"**":n.push(Math.pow(o,i));break;case"not in":n.push(!t(o,i));break;case"in":n.push(t(o,i));break;case"..":n.push(e.functions.range(o,i));break;default:throw new e.Error("Failed to parse operator: "+r+" is an unknown operator.")}},e}},function(e,t,r){e.exports=function(e){"use strict";function t(t,r,n){return r?e.expression.parseAsync.call(t,r,n):e.Promise.resolve(!1)}for(e.expression={},r(23)(e),e.expression.reservedWords=["true","false","null","TRUE","FALSE","NULL","_context","and","b-and","or","b-or","b-xor","in","not in","if"],e.expression.type={comma:"Twig.expression.type.comma",operator:{unary:"Twig.expression.type.operator.unary",binary:"Twig.expression.type.operator.binary"},string:"Twig.expression.type.string",bool:"Twig.expression.type.bool",slice:"Twig.expression.type.slice",array:{start:"Twig.expression.type.array.start",end:"Twig.expression.type.array.end"},object:{start:"Twig.expression.type.object.start",end:"Twig.expression.type.object.end"},parameter:{start:"Twig.expression.type.parameter.start",end:"Twig.expression.type.parameter.end"},subexpression:{start:"Twig.expression.type.subexpression.start",end:"Twig.expression.type.subexpression.end"},key:{period:"Twig.expression.type.key.period",brackets:"Twig.expression.type.key.brackets"},filter:"Twig.expression.type.filter",_function:"Twig.expression.type._function",variable:"Twig.expression.type.variable",number:"Twig.expression.type.number",_null:"Twig.expression.type.null",context:"Twig.expression.type.context",test:"Twig.expression.type.test"},e.expression.set={operations:[e.expression.type.filter,e.expression.type.operator.unary,e.expression.type.operator.binary,e.expression.type.array.end,e.expression.type.object.end,e.expression.type.parameter.end,e.expression.type.subexpression.end,e.expression.type.comma,e.expression.type.test],expressions:[e.expression.type._function,e.expression.type.bool,e.expression.type.string,e.expression.type.variable,e.expression.type.number,e.expression.type._null,e.expression.type.context,e.expression.type.parameter.start,e.expression.type.array.start,e.expression.type.object.start,e.expression.type.subexpression.start,e.expression.type.operator.unary]},e.expression.set.operations_extended=e.expression.set.operations.concat([e.expression.type.key.period,e.expression.type.key.brackets,e.expression.type.slice]),e.expression.fn={compile:{push:function(e,t,r){r.push(e)},push_both:function(e,t,r){r.push(e),t.push(e)}},parse:{push:function(e,t,r){t.push(e)},push_value:function(e,t,r){t.push(e.value)}}},e.expression.definitions=[{type:e.expression.type.test,regex:/^is\s+(not)?\s*([a-zA-Z_][a-zA-Z0-9_]*(\s?as)?)/,next:e.expression.set.operations.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.filter=e.match[2],e.modifier=e.match[1],delete e.match,delete e.value,r.push(e)},parse:function(r,n,o){var i=n.pop();return t(this,r.params,o).then(function(t){var o=e.test(r.filter,i,t);"not"==r.modifier?n.push(!o):n.push(o)})}},{type:e.expression.type.comma,regex:/^,/,next:e.expression.set.expressions.concat([e.expression.type.array.end,e.expression.type.object.end]),compile:function(t,r,n){var o,i=r.length-1;for(delete t.match,delete t.value;i>=0;i--){if((o=r.pop()).type===e.expression.type.object.start||o.type===e.expression.type.parameter.start||o.type===e.expression.type.array.start){r.push(o);break}n.push(o)}n.push(t)}},{type:e.expression.type.number,regex:/^\-?\d+(\.\d+)?/,next:e.expression.set.operations,compile:function(e,t,r){e.value=Number(e.value),r.push(e)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.operator.binary,regex:/(^\?\:|^(b\-and)|^(b\-or)|^(b\-xor)|^[\+\-~%\?]|^[\:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[\(|\s+]|^(or)[\(|\s+]|^(in)[\(|\s+]|^(not in)[\(|\s+]|^\.\.)/,next:e.expression.set.expressions,transform:function(e,t){switch(e[0]){case"and(":case"or(":case"in(":case"not in(":return t[t.length-1].value=e[2],e[0];default:return""}},compile:function(t,r,n){delete t.match,t.value=t.value.trim();var o=t.value,i=e.expression.operator.lookup(o,t);for(e.log.trace("Twig.expression.compile: ","Operator: ",i," from ",o);r.length>0&&(r[r.length-1].type==e.expression.type.operator.unary||r[r.length-1].type==e.expression.type.operator.binary)&&(i.associativity===e.expression.operator.leftToRight&&i.precidence>=r[r.length-1].precidence||i.associativity===e.expression.operator.rightToLeft&&i.precidence>r[r.length-1].precidence);){var s=r.pop();n.push(s)}if(":"===o){if(!r[r.length-1]||"?"!==r[r.length-1].value){var a=n.pop();if(a.type===e.expression.type.string||a.type===e.expression.type.variable)t.key=a.value;else if(a.type===e.expression.type.number)t.key=a.value.toString();else{if(!a.expression||a.type!==e.expression.type.parameter.end&&a.type!=e.expression.type.subexpression.end)throw new e.Error("Unexpected value before ':' of "+a.type+" = "+a.value);t.params=a.params}return void n.push(t)}}else r.push(i)},parse:function(t,r,n){if(t.key)r.push(t);else{if(t.params)return e.expression.parseAsync.call(this,t.params,n).then(function(e){t.key=e,r.push(t),n.loop||delete t.params});e.expression.operator.parse(t.value,r)}}},{type:e.expression.type.operator.unary,regex:/(^not\s+)/,next:e.expression.set.expressions,compile:function(t,r,n){delete t.match,t.value=t.value.trim();var o=t.value,i=e.expression.operator.lookup(o,t);for(e.log.trace("Twig.expression.compile: ","Operator: ",i," from ",o);r.length>0&&(r[r.length-1].type==e.expression.type.operator.unary||r[r.length-1].type==e.expression.type.operator.binary)&&(i.associativity===e.expression.operator.leftToRight&&i.precidence>=r[r.length-1].precidence||i.associativity===e.expression.operator.rightToLeft&&i.precidence>r[r.length-1].precidence);){var s=r.pop();n.push(s)}r.push(i)},parse:function(t,r,n){e.expression.operator.parse(t.value,r)}},{type:e.expression.type.string,regex:/^(["'])(?:(?=(\\?))\2[\s\S])*?\1/,next:e.expression.set.operations_extended,compile:function(t,r,n){var o=t.value;delete t.match,o='"'===o.substring(0,1)?o.replace('\\"','"'):o.replace("\\'","'"),t.value=o.substring(1,o.length-1).replace(/\\n/g,"\n").replace(/\\r/g,"\r"),e.log.trace("Twig.expression.compile: ","String value: ",t.value),n.push(t)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.subexpression.start,regex:/^\(/,next:e.expression.set.expressions.concat([e.expression.type.subexpression.end]),compile:function(e,t,r){e.value="(",r.push(e),t.push(e)},parse:e.expression.fn.parse.push},{type:e.expression.type.subexpression.end,regex:/^\)/,next:e.expression.set.operations_extended,validate:function(t,r){for(var n=r.length-1,o=!1,i=!1,s=0;!o&&n>=0;){var a=r[n];(o=a.type===e.expression.type.subexpression.start)&&i&&(i=!1,o=!1),a.type===e.expression.type.parameter.start?s++:a.type===e.expression.type.parameter.end?s--:a.type===e.expression.type.subexpression.end&&(i=!0),n--}return o&&0===s},compile:function(t,r,n){var o,i=t;for(o=r.pop();r.length>0&&o.type!=e.expression.type.subexpression.start;)n.push(o),o=r.pop();for(var s=[];t.type!==e.expression.type.subexpression.start;)s.unshift(t),t=n.pop();s.unshift(t);void 0===(o=r[r.length-1])||o.type!==e.expression.type._function&&o.type!==e.expression.type.filter&&o.type!==e.expression.type.test&&o.type!==e.expression.type.key.brackets?(i.expression=!0,s.pop(),s.shift(),i.params=s,n.push(i)):(i.expression=!1,o.params=s)},parse:function(t,r,n){if(t.expression)return e.expression.parseAsync.call(this,t.params,n).then(function(e){r.push(e)});throw new e.Error("Unexpected subexpression end when token is not marked as an expression")}},{type:e.expression.type.parameter.start,regex:/^\(/,next:e.expression.set.expressions.concat([e.expression.type.parameter.end]),validate:function(t,r){var n=r[r.length-1];return n&&e.indexOf(e.expression.reservedWords,n.value.trim())<0},compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.parameter.end,regex:/^\)/,next:e.expression.set.operations_extended,compile:function(t,r,n){var o,i=t;for(o=r.pop();r.length>0&&o.type!=e.expression.type.parameter.start;)n.push(o),o=r.pop();for(var s=[];t.type!==e.expression.type.parameter.start;)s.unshift(t),t=n.pop();s.unshift(t);void 0===(t=n[n.length-1])||t.type!==e.expression.type._function&&t.type!==e.expression.type.filter&&t.type!==e.expression.type.test&&t.type!==e.expression.type.key.brackets?(i.expression=!0,s.pop(),s.shift(),i.params=s,n.push(i)):(i.expression=!1,t.params=s)},parse:function(t,r,n){var o=[],i=!1,s=null;if(t.expression)return e.expression.parseAsync.call(this,t.params,n).then(function(e){r.push(e)});for(;r.length>0;){if((s=r.pop())&&s.type&&s.type==e.expression.type.parameter.start){i=!0;break}o.unshift(s)}if(!i)throw new e.Error("Expected end of parameter set.");r.push(o)}},{type:e.expression.type.slice,regex:/^\[(\d*\:\d*)\]/,next:e.expression.set.operations_extended,compile:function(e,t,r){var n=e.match[1].split(":"),o=n[0]?parseInt(n[0]):void 0,i=n[1]?parseInt(n[1]):void 0;e.value="slice",e.params=[o,i],i||(e.params=[o]),r.push(e)},parse:function(t,r,n){var o=r.pop(),i=t.params;r.push(e.filter.call(this,t.value,o,i))}},{type:e.expression.type.array.start,regex:/^\[/,next:e.expression.set.expressions.concat([e.expression.type.array.end]),compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.array.end,regex:/^\]/,next:e.expression.set.operations_extended,compile:function(t,r,n){for(var o,i=r.length-1;i>=0&&(o=r.pop()).type!==e.expression.type.array.start;i--)n.push(o);n.push(t)},parse:function(t,r,n){for(var o=[],i=!1,s=null;r.length>0;){if((s=r.pop()).type&&s.type==e.expression.type.array.start){i=!0;break}o.unshift(s)}if(!i)throw new e.Error("Expected end of array.");r.push(o)}},{type:e.expression.type.object.start,regex:/^\{/,next:e.expression.set.expressions.concat([e.expression.type.object.end]),compile:e.expression.fn.compile.push_both,parse:e.expression.fn.parse.push},{type:e.expression.type.object.end,regex:/^\}/,next:e.expression.set.operations_extended,compile:function(t,r,n){for(var o,i=r.length-1;i>=0&&(!(o=r.pop())||o.type!==e.expression.type.object.start);i--)n.push(o);n.push(t)},parse:function(t,r,n){for(var o={},i=!1,s=null,a=!1,p=null;r.length>0;){if((s=r.pop())&&s.type&&s.type===e.expression.type.object.start){i=!0;break}if(s&&s.type&&(s.type===e.expression.type.operator.binary||s.type===e.expression.type.operator.unary)&&s.key){if(!a)throw new e.Error("Missing value for key '"+s.key+"' in object definition.");o[s.key]=p,void 0===o._keys&&(o._keys=[]),o._keys.unshift(s.key),p=null,a=!1}else a=!0,p=s}if(!i)throw new e.Error("Unexpected end of object.");r.push(o)}},{type:e.expression.type.filter,regex:/^\|\s?([a-zA-Z_][a-zA-Z0-9_\-]*)/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.value=e.match[1],r.push(e)},parse:function(r,n,o){var i=this,s=n.pop();return t(this,r.params,o).then(function(t){return e.filter.call(i,r.value,s,t)}).then(function(e){n.push(e)})}},{type:e.expression.type._function,regex:/^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/,next:e.expression.type.parameter.start,validate:function(t,r){return t[1]&&e.indexOf(e.expression.reservedWords,t[1])<0},transform:function(e,t){return"("},compile:function(e,t,r){var n=e.match[1];e.fn=n,delete e.match,delete e.value,r.push(e)},parse:function(r,n,o){var i,s=this,a=r.fn;return t(this,r.params,o).then(function(t){if(e.functions[a])i=e.functions[a].apply(s,t);else{if("function"!=typeof o[a])throw new e.Error(a+" function does not exist and is not defined in the context");i=o[a].apply(o,t)}return i}).then(function(e){n.push(e)})}},{type:e.expression.type.variable,regex:/^[a-zA-Z_][a-zA-Z0-9_]*/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:e.expression.fn.compile.push,validate:function(t,r){return e.indexOf(e.expression.reservedWords,t[0])<0},parse:function(t,r,n){return e.expression.resolveAsync.call(this,n[t.value],n).then(function(e){r.push(e)})}},{type:e.expression.type.key.period,regex:/^\.([a-zA-Z0-9_]+)/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(e,t,r){e.key=e.match[1],delete e.match,delete e.value,r.push(e)},parse:function(r,n,o,i){var s,a=this,p=r.key,c=n.pop();return t(this,r.params,o).then(function(t){if(null===c||void 0===c){if(a.options.strict_variables)throw new e.Error("Can't access a key "+p+" on an null or undefined object.");s=void 0}else{var r=function(e){return e.substr(0,1).toUpperCase()+e.substr(1)};s="object"==typeof c&&p in c?c[p]:void 0!==c["get"+r(p)]?c["get"+r(p)]:void 0!==c["is"+r(p)]?c["is"+r(p)]:void 0}return e.expression.resolveAsync.call(a,s,o,t,i,c)}).then(function(e){n.push(e)})}},{type:e.expression.type.key.brackets,regex:/^\[([^\]\:]*)\]/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:function(t,r,n){var o=t.match[1];delete t.value,delete t.match,t.stack=e.expression.compile({value:o}).stack,n.push(t)},parse:function(r,n,o,i){var s,a,p=this,c=null;return t(this,r.params,o).then(function(t){return c=t,e.expression.parseAsync.call(p,r.stack,o)}).then(function(t){if(null===(s=n.pop())||void 0===s){if(p.options.strict_variables)throw new e.Error("Can't access a key "+t+" on an null or undefined object.");return null}return a="object"==typeof s&&t in s?s[t]:null,e.expression.resolveAsync.call(p,a,s,c,i)}).then(function(e){n.push(e)})}},{type:e.expression.type._null,regex:/^(null|NULL|none|NONE)/,next:e.expression.set.operations,compile:function(e,t,r){delete e.match,e.value=null,r.push(e)},parse:e.expression.fn.parse.push_value},{type:e.expression.type.context,regex:/^_context/,next:e.expression.set.operations_extended.concat([e.expression.type.parameter.start]),compile:e.expression.fn.compile.push,parse:function(e,t,r){t.push(r)}},{type:e.expression.type.bool,regex:/^(true|TRUE|false|FALSE)/,next:e.expression.set.operations,compile:function(e,t,r){e.value="true"===e.match[0].toLowerCase(),delete e.match,r.push(e)},parse:e.expression.fn.parse.push_value}],e.expression.resolveAsync=function(t,r,n,o,i){if("function"!=typeof t)return e.Promise.resolve(t);var s=e.Promise.resolve(n);if(o&&o.type===e.expression.type.parameter.end){s=s.then(function(){return o.params&&e.expression.parseAsync.call(this,o.params,r,!0)}).then(function(e){return o.cleanup=!0,e})}return s.then(function(e){return t.apply(i||r,e||[])})},e.expression.resolve=function(t,r,n,o,i){return e.async.potentiallyAsync(this,!1,function(){return e.expression.resolveAsync.call(this,t,r,n,o,i)})},e.expression.handler={},e.expression.extendType=function(t){e.expression.type[t]="Twig.expression.type."+t},e.expression.extend=function(t){if(!t.type)throw new e.Error("Unable to extend logic definition. No type provided for "+t);e.expression.handler[t.type]=t};e.expression.definitions.length>0;)e.expression.extend(e.expression.definitions.shift());return e.expression.tokenize=function(t){var r,n,o,i,s,a,p=[],c=0,l=null,u=[];for(a=function(){for(var t=arguments.length-2,n=new Array(t);t-- >0;)n[t]=arguments[t];if(e.log.trace("Twig.expression.tokenize","Matched a ",r," regular expression of ",n),l&&e.indexOf(l,r)<0)return u.push(r+" cannot follow a "+p[p.length-1].type+" at template:"+c+" near '"+n[0].substring(0,20)+"...'"),n[0];var o=e.expression.handler[r];return o.validate&&!o.validate(n,p)?n[0]:(u=[],p.push({type:r,value:n[0],match:n}),s=!0,l=i,c+=n[0].length,o.transform?o.transform(n,p):"")},e.log.debug("Twig.expression.tokenize","Tokenizing expression ",t);t.length>0;){for(r in t=t.trim(),e.expression.handler){if(i=e.expression.handler[r].next,n=e.expression.handler[r].regex,e.log.trace("Checking type ",r," on ",t),s=!1,e.lib.isArray(n))for(o=n.length;o-- >0;)t=t.replace(n[o],a);else t=t.replace(n,a);if(s)break}if(!s)throw u.length>0?new e.Error(u.join(" OR ")):new e.Error("Unable to parse '"+t+"' at template position"+c)}return e.log.trace("Twig.expression.tokenize","Tokenized to ",p),p},e.expression.compile=function(t){var r=t.value,n=e.expression.tokenize(r),o=null,i=[],s=[],a=null;for(e.log.trace("Twig.expression.compile: ","Compiling ",r);n.length>0;)o=n.shift(),a=e.expression.handler[o.type],e.log.trace("Twig.expression.compile: ","Compiling ",o),a.compile&&a.compile(o,s,i),e.log.trace("Twig.expression.compile: ","Stack is",s),e.log.trace("Twig.expression.compile: ","Output is",i);for(;s.length>0;)i.push(s.pop());return e.log.trace("Twig.expression.compile: ","Final output is",i),t.stack=i,delete t.value,t},e.expression.parse=function(t,r,n,o){var i=this;e.lib.isArray(t)||(t=[t]);var s=[],a=[],p=e.expression.type.operator.binary;return e.async.potentiallyAsync(this,o,function(){return e.async.forEach(t,function(n,o){var c,l=null,u=null;if(!n.cleanup)return t.length>o+1&&(u=t[o+1]),(l=e.expression.handler[n.type]).parse&&(c=l.parse.call(i,n,s,r,u)),n.type===p&&r.loop&&a.push(n),c}).then(function(){for(var e=a.length,t=null;e-- >0;)(t=a[e]).params&&t.key&&delete t.key;if(n){var r=s.splice(0);s.push(r)}return s.pop()})})},e}},function(e,t){e.exports=function(e){return e.compiler={module:{}},e.compiler.compile=function(t,r){var n,o=JSON.stringify(t.tokens),i=t.id;if(r.module){if(void 0===e.compiler.module[r.module])throw new e.Error("Unable to find module type "+r.module);n=e.compiler.module[r.module](i,o,r.twig)}else n=e.compiler.wrap(i,o);return n},e.compiler.module={amd:function(t,r,n){return'define(["'+n+'"], function (Twig) {\n\tvar twig, templates;\ntwig = Twig.twig;\ntemplates = '+e.compiler.wrap(t,r)+"\n\treturn templates;\n});"},node:function(t,r){return'var twig = require("twig").twig;\nexports.template = '+e.compiler.wrap(t,r)},cjs2:function(t,r,n){return'module.declare([{ twig: "'+n+'" }], function (require, exports, module) {\n\tvar twig = require("twig").twig;\n\texports.template = '+e.compiler.wrap(t,r)+"\n});"}},e.compiler.wrap=function(e,t){return'twig({id:"'+e.replace('"','\\"')+'", data:'+t+", precompiled: true});\n"},e}},function(e,t){e.exports=function(e){"use strict";function t(t,r){if(t.options.rethrow)throw"string"==typeof r&&(r=new e.Error(r)),"TwigException"!=r.type||r.file||(r.file=t.id),r;if(e.log.error("Error parsing twig template "+t.id+": "),r.stack?e.log.error(r.stack):e.log.error(r.toString()),e.debug)return r.toString()}return e.trace=!1,e.debug=!1,e.cache=!0,e.noop=function(){},e.placeholders={parent:"{{|PARENT|}}"},e.hasIndexOf=Array.prototype.hasOwnProperty("indexOf"),e.indexOf=function(t,r){if(e.hasIndexOf)return t.indexOf(r);if(void 0===t||null===t)throw new TypeError;var n=Object(t),o=n.length>>>0;if(0===o)return-1;var i=0;if(arguments.length>0&&((i=Number(arguments[1]))!=i?i=0:0!==i&&i!==1/0&&i!==-1/0&&(i=(i>0||-1)*Math.floor(Math.abs(i)))),i>=o)return-1;for(var s=i>=0?i:Math.max(o-Math.abs(i),0);s<o;s++)if(s in n&&n[s]===r)return s;return t==r?0:-1},e.forEach=function(e,t,r){if(Array.prototype.forEach)return e.forEach(t,r);var n,o;if(null==e)throw new TypeError(" this is null or not defined");var i=Object(e),s=i.length>>>0;if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(r&&(n=r),o=0;o<s;){var a;o in i&&(a=i[o],t.call(n,a,o,i)),o++}},e.merge=function(t,r,n){return e.forEach(Object.keys(r),function(e){(!n||e in t)&&(t[e]=r[e])}),t},e.attempt=function(e,t){try{return e()}catch(e){return t(e)}},e.Error=function(e,t){this.message=e,this.name="TwigException",this.type="TwigException",this.file=t},e.Error.prototype.toString=function(){return this.name+": "+this.message},e.log={trace:function(){e.trace&&console&&console.log(Array.prototype.slice.call(arguments))},debug:function(){e.debug&&console&&console.log(Array.prototype.slice.call(arguments))}},"undefined"!=typeof console?void 0!==console.error?e.log.error=function(){console.error.apply(console,arguments)}:void 0!==console.log&&(e.log.error=function(){console.log.apply(console,arguments)}):e.log.error=function(){},e.ChildContext=function(t){return e.lib.copy(t)},e.token={},e.token.type={output:"output",logic:"logic",comment:"comment",raw:"raw",output_whitespace_pre:"output_whitespace_pre",output_whitespace_post:"output_whitespace_post",output_whitespace_both:"output_whitespace_both",logic_whitespace_pre:"logic_whitespace_pre",logic_whitespace_post:"logic_whitespace_post",logic_whitespace_both:"logic_whitespace_both"},e.token.definitions=[{type:e.token.type.raw,open:"{% raw %}",close:"{% endraw %}"},{type:e.token.type.raw,open:"{% verbatim %}",close:"{% endverbatim %}"},{type:e.token.type.output_whitespace_pre,open:"{{-",close:"}}"},{type:e.token.type.output_whitespace_post,open:"{{",close:"-}}"},{type:e.token.type.output_whitespace_both,open:"{{-",close:"-}}"},{type:e.token.type.logic_whitespace_pre,open:"{%-",close:"%}"},{type:e.token.type.logic_whitespace_post,open:"{%",close:"-%}"},{type:e.token.type.logic_whitespace_both,open:"{%-",close:"-%}"},{type:e.token.type.output,open:"{{",close:"}}"},{type:e.token.type.logic,open:"{%",close:"%}"},{type:e.token.type.comment,open:"{#",close:"#}"}],e.token.strings=['"',"'"],e.token.findStart=function(t){var r,n,o,i,s={position:null,def:null},a=null,p=e.token.definitions.length;for(r=0;r<p;r++)n=e.token.definitions[r],o=t.indexOf(n.open),i=t.indexOf(n.close),e.log.trace("Twig.token.findStart: ","Searching for ",n.open," found at ",o),o>=0&&n.open.length!==n.close.length&&i<0||(o>=0&&(null===s.position||o<s.position)?(s.position=o,s.def=n,a=i):o>=0&&null!==s.position&&o===s.position&&(n.open.length>s.def.open.length?(s.position=o,s.def=n,a=i):n.open.length===s.def.open.length&&(n.close.length,s.def.close.length,i>=0&&i<a&&(s.position=o,s.def=n,a=i))));return s},e.token.findEnd=function(t,r,n){for(var o,i,s=null,a=!1,p=0,c=null,l=null,u=null,f=null,h=null,y=null;!a;){if(c=null,l=null,!((u=t.indexOf(r.close,p))>=0))throw new e.Error("Unable to find closing bracket '"+r.close+"' opened near template position "+n);if(s=u,a=!0,r.type===e.token.type.comment)break;if(r.type===e.token.type.raw)break;for(i=e.token.strings.length,o=0;o<i;o+=1)(h=t.indexOf(e.token.strings[o],p))>0&&h<u&&(null===c||h<c)&&(c=h,l=e.token.strings[o]);if(null!==c)for(f=c+1,s=null,a=!1;;){if((y=t.indexOf(l,f))<0)throw"Unclosed string in template";if("\\"!==t.substr(y-1,1)){p=y+1;break}f=y+1}}return s},e.tokenize=function(t){for(var r=[],n=0,o=null,i=null;t.length>0;)if(o=e.token.findStart(t),e.log.trace("Twig.tokenize: ","Found token: ",o),null!==o.position){if(o.position>0&&r.push({type:e.token.type.raw,value:t.substring(0,o.position)}),t=t.substr(o.position+o.def.open.length),n+=o.position+o.def.open.length,i=e.token.findEnd(t,o.def,n),e.log.trace("Twig.tokenize: ","Token ends at ",i),r.push({type:o.def.type,value:t.substring(0,i).trim()}),"\n"===t.substr(i+o.def.close.length,1))switch(o.def.type){case"logic_whitespace_pre":case"logic_whitespace_post":case"logic_whitespace_both":case"logic":i+=1}t=t.substr(i+o.def.close.length),n+=i+o.def.close.length}else r.push({type:e.token.type.raw,value:t}),t="";return r},e.compile=function(t){var r=this;return e.attempt(function(){for(var n=[],o=[],i=[],s=null,a=null,p=null,c=null,l=null,u=null,f=null,h=null,y=null,d=null,g=null,m=null,x=function(t){e.expression.compile.call(r,t),o.length>0?i.push(t):n.push(t)},v=function(t){if(a=e.logic.compile.call(r,t),d=a.type,g=e.logic.handler[d].open,m=e.logic.handler[d].next,e.log.trace("Twig.compile: ","Compiled logic token to ",a," next is: ",m," open is : ",g),void 0!==g&&!g){if(c=o.pop(),f=e.logic.handler[c.type],e.indexOf(f.next,d)<0)throw new Error(d+" not expected after a "+c.type);c.output=c.output||[],c.output=c.output.concat(i),i=[],y={type:e.token.type.logic,token:c},o.length>0?i.push(y):n.push(y)}void 0!==m&&m.length>0?(e.log.trace("Twig.compile: ","Pushing ",a," to logic stack."),o.length>0&&((c=o.pop()).output=c.output||[],c.output=c.output.concat(i),o.push(c),i=[]),o.push(a)):void 0!==g&&g&&(y={type:e.token.type.logic,token:a},o.length>0?i.push(y):n.push(y))};t.length>0;){switch(s=t.shift(),l=n[n.length-1],u=i[i.length-1],h=t[0],e.log.trace("Compiling token ",s),s.type){case e.token.type.raw:o.length>0?i.push(s):n.push(s);break;case e.token.type.logic:v.call(r,s);break;case e.token.type.comment:break;case e.token.type.output:x.call(r,s);break;case e.token.type.logic_whitespace_pre:case e.token.type.logic_whitespace_post:case e.token.type.logic_whitespace_both:case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:switch(s.type!==e.token.type.output_whitespace_post&&s.type!==e.token.type.logic_whitespace_post&&(l&&l.type===e.token.type.raw&&(n.pop(),null===l.value.match(/^\s*$/)&&(l.value=l.value.trim(),n.push(l))),u&&u.type===e.token.type.raw&&(i.pop(),null===u.value.match(/^\s*$/)&&(u.value=u.value.trim(),i.push(u)))),s.type){case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:x.call(r,s);break;case e.token.type.logic_whitespace_pre:case e.token.type.logic_whitespace_post:case e.token.type.logic_whitespace_both:v.call(r,s)}s.type!==e.token.type.output_whitespace_pre&&s.type!==e.token.type.logic_whitespace_pre&&h&&h.type===e.token.type.raw&&(t.shift(),null===h.value.match(/^\s*$/)&&(h.value=h.value.trim(),t.unshift(h)))}e.log.trace("Twig.compile: "," Output: ",n," Logic Stack: ",o," Pending Output: ",i)}if(o.length>0)throw p=o.pop(),new Error("Unable to find an end tag for "+p.type+", expecting one of "+p.next);return n},function(t){if(r.options.rethrow)throw"TwigException"!=t.type||t.file||(t.file=r.id),t;e.log.error("Error compiling twig template "+r.id+": "),t.stack?e.log.error(t.stack):e.log.error(t.toString())})},e.parse=function(r,n,o){var i,s=this,a=[],p=null,c=!0,l=!0;function u(e){a.push(e)}function f(e){void 0!==e.chain&&(l=e.chain),void 0!==e.context&&(n=e.context),void 0!==e.output&&a.push(e.output)}if(i=e.async.forEach(r,function(t){switch(e.log.debug("Twig.parse: ","Parsing token: ",t),t.type){case e.token.type.raw:a.push(e.filters.raw(t.value));break;case e.token.type.logic:return e.logic.parseAsync.call(s,t.token,n,l).then(f);case e.token.type.comment:break;case e.token.type.output_whitespace_pre:case e.token.type.output_whitespace_post:case e.token.type.output_whitespace_both:case e.token.type.output:return e.log.debug("Twig.parse: ","Output token: ",t.stack),e.expression.parseAsync.call(s,t.stack,n).then(u)}}).then(function(){return a=e.output.call(s,a),c=!1,a}).catch(function(e){o&&t(s,e),p=e}),o)return i;if(null!==p)return t(this,p);if(c)throw new e.Error("You are using Twig.js in sync mode in combination with async extensions.");return a},e.prepare=function(t){var r,n;return e.log.debug("Twig.prepare: ","Tokenizing ",t),n=e.tokenize.call(this,t),e.log.debug("Twig.prepare: ","Compiling ",n),r=e.compile.call(this,n),e.log.debug("Twig.prepare: ","Compiled ",r),r},e.output=function(t){var r=this.options.autoescape;if(!r)return t.join("");var n="string"==typeof r?r:"html",o=0,i=t.length,s="",a=new Array(i);for(o=0;o<i;o++)(s=t[o])&&!0!==s.twig_markup&&s.twig_markup!=n&&(s=e.filters.escape(s,[n])),a[o]=s;return a.length<1?"":e.Markup(a.join(""),!0)},e.Templates={loaders:{},parsers:{},registry:{}},e.validateId=function(t){if("prototype"===t)throw new e.Error(t+" is not a valid twig identifier");if(e.cache&&e.Templates.registry.hasOwnProperty(t))throw new e.Error("There is already a template with the ID "+t);return!0},e.Templates.registerLoader=function(t,r,n){if("function"!=typeof r)throw new e.Error("Unable to add loader for "+t+": Invalid function reference given.");n&&(r=r.bind(n)),this.loaders[t]=r},e.Templates.unRegisterLoader=function(e){this.isRegisteredLoader(e)&&delete this.loaders[e]},e.Templates.isRegisteredLoader=function(e){return this.loaders.hasOwnProperty(e)},e.Templates.registerParser=function(t,r,n){if("function"!=typeof r)throw new e.Error("Unable to add parser for "+t+": Invalid function regerence given.");n&&(r=r.bind(n)),this.parsers[t]=r},e.Templates.unRegisterParser=function(e){this.isRegisteredParser(e)&&delete this.parsers[e]},e.Templates.isRegisteredParser=function(e){return this.parsers.hasOwnProperty(e)},e.Templates.save=function(t){if(void 0===t.id)throw new e.Error("Unable to save template with no id");e.Templates.registry[t.id]=t},e.Templates.load=function(t){return e.Templates.registry.hasOwnProperty(t)?e.Templates.registry[t]:null},e.Templates.loadRemote=function(t,r,n,o){var i=void 0===r.id?t:r.id,s=e.Templates.registry[i];return e.cache&&void 0!==s?("function"==typeof n&&n(s),s):(r.parser=r.parser||"twig",r.id=i,void 0===r.async&&(r.async=!0),(this.loaders[r.method]||this.loaders.fs).call(this,t,r,n,o))},e.Template=function(t){var r,n,o,i=t.data,s=t.id,a=t.blocks,p=t.macros||{},c=t.base,l=t.path,u=t.url,f=t.name,h=t.method,y=t.options;this.id=s,this.method=h,this.base=c,this.path=l,this.url=u,this.name=f,this.macros=p,this.options=y,this.reset(a),r="String",n=i,o=Object.prototype.toString.call(n).slice(8,-1),this.tokens=void 0!==n&&null!==n&&o===r?e.prepare.call(this,i):i,void 0!==s&&e.Templates.save(this)},e.Template.prototype.reset=function(t){e.log.debug("Twig.Template.reset","Reseting template "+this.id),this.blocks={},this.importedBlocks=[],this.originalBlockTokens={},this.child={blocks:t||{}},this.extend=null,this.parseStack=[]},e.Template.prototype.render=function(t,r,n){var o=this;return this.context=t||{},this.reset(),r&&r.blocks&&(this.blocks=r.blocks),r&&r.macros&&(this.macros=r.macros),e.async.potentiallyAsync(this,n,function(){return e.parseAsync.call(this,this.tokens,this.context).then(function(t){var n,i;return o.extend?(o.options.allowInlineIncludes&&(n=e.Templates.load(o.extend))&&(n.options=o.options),n||(i=e.path.parsePath(o,o.extend),n=e.Templates.loadRemote(i,{method:o.getLoaderMethod(),base:o.base,async:!1,id:i,options:o.options})),o.parent=n,o.parent.renderAsync(o.context,{blocks:o.blocks})):r?"blocks"==r.output?o.blocks:"macros"==r.output?o.macros:t:t})})},e.Template.prototype.importFile=function(t){var r,n;if(!this.url&&this.options.allowInlineIncludes){if(t=this.path?e.path.parsePath(this,t):t,!(n=e.Templates.load(t))&&!(n=e.Templates.loadRemote(r,{id:t,method:this.getLoaderMethod(),async:!1,path:t,options:this.options})))throw new e.Error("Unable to find the template "+t);return n.options=this.options,n}return r=e.path.parsePath(this,t),n=e.Templates.loadRemote(r,{method:this.getLoaderMethod(),base:this.base,async:!1,options:this.options,id:r})},e.Template.prototype.importBlocks=function(t,r){var n=this.importFile(t),o=this.context,i=this;r=r||!1,n.render(o),e.forEach(Object.keys(n.blocks),function(e){(r||void 0===i.blocks[e])&&(i.blocks[e]=n.blocks[e],i.importedBlocks.push(e))})},e.Template.prototype.importMacros=function(t){var r=e.path.parsePath(this,t);return e.Templates.loadRemote(r,{method:this.getLoaderMethod(),async:!1,id:r})},e.Template.prototype.getLoaderMethod=function(){return this.path?"fs":this.url?"ajax":this.method||"fs"},e.Template.prototype.compile=function(t){return e.compiler.compile(this,t)},e.Markup=function(e,t){if("string"!=typeof e||e.length<1)return e;var r=new String(e);return r.twig_markup=void 0===t||t,r},e}},function(e,t,r){
- /**
- * Twig.js
- *
- * @copyright 2011-2016 John Roepke and the Twig.js Contributors
- * @license Available under the BSD 2-Clause License
- * @link https://github.com/twigjs/twig.js
- */
- var n={VERSION:"1.11.1"};r(26)(n),r(25)(n),r(24)(n),r(22)(n),r(21)(n),r(20)(n),r(11)(n),r(10)(n),r(8)(n),r(7)(n),r(6)(n),r(5)(n),r(4)(n),r(3)(n),r(2)(n),e.exports=n.exports}])});
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/node_modules/twig")
- },{"fs":21,"path":201}],208:[function(require,module,exports){
- // weightSort(arr, [options | weightKey])
- // Parameters:
- // arr ... an array of form [ [ weight, var], ... ]
- // [ [ -3, A ], [ -1, B ], [ 5, C ], [ -1, D ] ]
- // OR
- // an array of form [ { 'weight': value, other key/values } ]
- // [ { 'weight': -3, k: A ], { 'weight': -1, v: B }, [ 5, C ] ]
- // OR
- // an object of form { 'index': {'weight': value, other key/values }, ... }
- // (please note that numerical indexes won't work)
- //
- // weightKey ... name of the key which holds each element's weight (default:
- // 'weight')
- //
- // as the last item shows, you can even mix the forms
- //
- // Returns:
- // if the first form is used, only the 'var' will be returned; with the
- // second form the elements are untouched, only their position changed.
- //
- // Notes:
- // Entries in the source array with the same weight are returned in the
- // same order
- // * weight might be a function closure
- function weightSort (arr, options) {
- // source: http://stackoverflow.com/a/9716515/4832631
- function isNumber (n) {
- return !isNaN(parseFloat(n)) && isFinite(n)
- }
- function cmp (a, b) {
- if (a === b) {
- return 0
- }
- if (isNumber(a) && isNumber(b)) {
- return parseFloat(a) < parseFloat(b) ? -1 : 1
- } else {
- return a < b ? -1 : 1
- }
- }
- var i
- var j
- var ret1 = {}
- if (typeof options === 'string') {
- options = {
- key: options
- }
- } else if (!options) {
- options = {
- key: 'weight'
- }
- }
- if (!('key' in options)) {
- options.key = 'weight'
- }
- if (!('compareFunction' in options)) {
- options.compareFunction = cmp
- }
- // check if input array is an object, convert to array
- var isObject = false
- if (typeof arr.length === 'undefined') {
- var newArr = []
- isObject = true
- for (i in arr) {
- arr[i].__weightSort_index = i
- newArr.push(arr[i])
- }
- arr = newArr
- }
- // first put all elements into an assoc. array
- for (i = 0; i < arr.length; i++) {
- var cur = arr[i]
- var wgt
- var data
- if (cur.length) {
- wgt = cur[0]
- data = cur[1]
- } else {
- wgt = cur[options.key]
- data = cur
- }
- if (typeof wgt === 'function') {
- wgt = wgt()
- }
- if (!wgt) {
- wgt = 0
- }
- if (!ret1[wgt]) {
- ret1[wgt] = []
- }
- ret1[wgt].push(data)
- }
- // get the keys, convert to value, order them
- var keys1 = []
- for (var k in ret1) {
- keys1.push(k)
- }
- keys1.sort(options.compareFunction)
- if (options.reverse) {
- keys1.reverse()
- }
- var ret2 = []
- // iterate through array and compile final return value
- for (i = 0; i < keys1.length; i++) {
- for (j = 0; j < ret1[keys1[i]].length; j++) {
- ret2.push(ret1[keys1[i]][j])
- }
- }
- // rebuild object if necessary
- if (isObject) {
- newArr = {}
- for (i = 0; i < ret2.length; i++) {
- var ob = ret2[i]
- var index = ob.__weightSort_index
- delete ob.__weightSort_index
- newArr[index] = ob
- }
- ret2 = newArr
- }
- return ret2
- }
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = weightSort
- }
- if (typeof window !== 'undefined') {
- window.weightSort = weightSort
- window.weight_sort = weightSort // legacy
- }
- },{}],209:[function(require,module,exports){
- module.exports.RADIUS = 6378137;
- module.exports.FLATTENING = 1/298.257223563;
- module.exports.POLAR_RADIUS = 6356752.3142;
- },{}],210:[function(require,module,exports){
- function DOMParser(options){
- this.options = options ||{locator:{}};
-
- }
- DOMParser.prototype.parseFromString = function(source,mimeType){
- var options = this.options;
- var sax = new XMLReader();
- var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
- var errorHandler = options.errorHandler;
- var locator = options.locator;
- var defaultNSMap = options.xmlns||{};
- var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
- if(locator){
- domBuilder.setDocumentLocator(locator)
- }
-
- sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
- sax.domBuilder = options.domBuilder || domBuilder;
- if(/\/x?html?$/.test(mimeType)){
- entityMap.nbsp = '\xa0';
- entityMap.copy = '\xa9';
- defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
- }
- defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
- if(source){
- sax.parse(source,defaultNSMap,entityMap);
- }else{
- sax.errorHandler.error("invalid doc source");
- }
- return domBuilder.doc;
- }
- function buildErrorHandler(errorImpl,domBuilder,locator){
- if(!errorImpl){
- if(domBuilder instanceof DOMHandler){
- return domBuilder;
- }
- errorImpl = domBuilder ;
- }
- var errorHandler = {}
- var isCallback = errorImpl instanceof Function;
- locator = locator||{}
- function build(key){
- var fn = errorImpl[key];
- if(!fn && isCallback){
- fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
- }
- errorHandler[key] = fn && function(msg){
- fn('[xmldom '+key+']\t'+msg+_locator(locator));
- }||function(){};
- }
- build('warning');
- build('error');
- build('fatalError');
- return errorHandler;
- }
- //console.log('#\n\n\n\n\n\n\n####')
- /**
- * +ContentHandler+ErrorHandler
- * +LexicalHandler+EntityResolver2
- * -DeclHandler-DTDHandler
- *
- * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
- * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
- * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
- */
- function DOMHandler() {
- this.cdata = false;
- }
- function position(locator,node){
- node.lineNumber = locator.lineNumber;
- node.columnNumber = locator.columnNumber;
- }
- /**
- * @see org.xml.sax.ContentHandler#startDocument
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
- */
- DOMHandler.prototype = {
- startDocument : function() {
- this.doc = new DOMImplementation().createDocument(null, null, null);
- if (this.locator) {
- this.doc.documentURI = this.locator.systemId;
- }
- },
- startElement:function(namespaceURI, localName, qName, attrs) {
- var doc = this.doc;
- var el = doc.createElementNS(namespaceURI, qName||localName);
- var len = attrs.length;
- appendElement(this, el);
- this.currentElement = el;
-
- this.locator && position(this.locator,el)
- for (var i = 0 ; i < len; i++) {
- var namespaceURI = attrs.getURI(i);
- var value = attrs.getValue(i);
- var qName = attrs.getQName(i);
- var attr = doc.createAttributeNS(namespaceURI, qName);
- this.locator &&position(attrs.getLocator(i),attr);
- attr.value = attr.nodeValue = value;
- el.setAttributeNode(attr)
- }
- },
- endElement:function(namespaceURI, localName, qName) {
- var current = this.currentElement
- var tagName = current.tagName;
- this.currentElement = current.parentNode;
- },
- startPrefixMapping:function(prefix, uri) {
- },
- endPrefixMapping:function(prefix) {
- },
- processingInstruction:function(target, data) {
- var ins = this.doc.createProcessingInstruction(target, data);
- this.locator && position(this.locator,ins)
- appendElement(this, ins);
- },
- ignorableWhitespace:function(ch, start, length) {
- },
- characters:function(chars, start, length) {
- chars = _toString.apply(this,arguments)
- //console.log(chars)
- if(chars){
- if (this.cdata) {
- var charNode = this.doc.createCDATASection(chars);
- } else {
- var charNode = this.doc.createTextNode(chars);
- }
- if(this.currentElement){
- this.currentElement.appendChild(charNode);
- }else if(/^\s*$/.test(chars)){
- this.doc.appendChild(charNode);
- //process xml
- }
- this.locator && position(this.locator,charNode)
- }
- },
- skippedEntity:function(name) {
- },
- endDocument:function() {
- this.doc.normalize();
- },
- setDocumentLocator:function (locator) {
- if(this.locator = locator){// && !('lineNumber' in locator)){
- locator.lineNumber = 0;
- }
- },
- //LexicalHandler
- comment:function(chars, start, length) {
- chars = _toString.apply(this,arguments)
- var comm = this.doc.createComment(chars);
- this.locator && position(this.locator,comm)
- appendElement(this, comm);
- },
-
- startCDATA:function() {
- //used in characters() methods
- this.cdata = true;
- },
- endCDATA:function() {
- this.cdata = false;
- },
-
- startDTD:function(name, publicId, systemId) {
- var impl = this.doc.implementation;
- if (impl && impl.createDocumentType) {
- var dt = impl.createDocumentType(name, publicId, systemId);
- this.locator && position(this.locator,dt)
- appendElement(this, dt);
- }
- },
- /**
- * @see org.xml.sax.ErrorHandler
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
- */
- warning:function(error) {
- console.warn('[xmldom warning]\t'+error,_locator(this.locator));
- },
- error:function(error) {
- console.error('[xmldom error]\t'+error,_locator(this.locator));
- },
- fatalError:function(error) {
- console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
- throw error;
- }
- }
- function _locator(l){
- if(l){
- return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
- }
- }
- function _toString(chars,start,length){
- if(typeof chars == 'string'){
- return chars.substr(start,length)
- }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
- if(chars.length >= start+length || start){
- return new java.lang.String(chars,start,length)+'';
- }
- return chars;
- }
- }
- /*
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
- * used method of org.xml.sax.ext.LexicalHandler:
- * #comment(chars, start, length)
- * #startCDATA()
- * #endCDATA()
- * #startDTD(name, publicId, systemId)
- *
- *
- * IGNORED method of org.xml.sax.ext.LexicalHandler:
- * #endDTD()
- * #startEntity(name)
- * #endEntity(name)
- *
- *
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
- * IGNORED method of org.xml.sax.ext.DeclHandler
- * #attributeDecl(eName, aName, type, mode, value)
- * #elementDecl(name, model)
- * #externalEntityDecl(name, publicId, systemId)
- * #internalEntityDecl(name, value)
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
- * IGNORED method of org.xml.sax.EntityResolver2
- * #resolveEntity(String name,String publicId,String baseURI,String systemId)
- * #resolveEntity(publicId, systemId)
- * #getExternalSubset(name, baseURI)
- * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
- * IGNORED method of org.xml.sax.DTDHandler
- * #notationDecl(name, publicId, systemId) {};
- * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
- */
- "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
- DOMHandler.prototype[key] = function(){return null}
- })
- /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
- function appendElement (hander,node) {
- if (!hander.currentElement) {
- hander.doc.appendChild(node);
- } else {
- hander.currentElement.appendChild(node);
- }
- }//appendChild and setAttributeNS are preformance key
- //if(typeof require == 'function'){
- var XMLReader = require('./sax').XMLReader;
- var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
- exports.XMLSerializer = require('./dom').XMLSerializer ;
- exports.DOMParser = DOMParser;
- //}
- },{"./dom":211,"./sax":212}],211:[function(require,module,exports){
- /*
- * DOM Level 2
- * Object DOMException
- * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
- */
- function copy(src,dest){
- for(var p in src){
- dest[p] = src[p];
- }
- }
- /**
- ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
- ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
- */
- function _extends(Class,Super){
- var pt = Class.prototype;
- if(Object.create){
- var ppt = Object.create(Super.prototype)
- pt.__proto__ = ppt;
- }
- if(!(pt instanceof Super)){
- function t(){};
- t.prototype = Super.prototype;
- t = new t();
- copy(pt,t);
- Class.prototype = pt = t;
- }
- if(pt.constructor != Class){
- if(typeof Class != 'function'){
- console.error("unknow Class:"+Class)
- }
- pt.constructor = Class
- }
- }
- var htmlns = 'http://www.w3.org/1999/xhtml' ;
- // Node Types
- var NodeType = {}
- var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
- var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
- var TEXT_NODE = NodeType.TEXT_NODE = 3;
- var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
- var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
- var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
- var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
- var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
- var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
- var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
- var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
- var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
- // ExceptionCode
- var ExceptionCode = {}
- var ExceptionMessage = {};
- var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
- var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
- var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
- var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
- var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
- var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
- var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
- var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
- var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
- var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
- //level2
- var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
- var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
- var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
- var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
- var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
- function DOMException(code, message) {
- if(message instanceof Error){
- var error = message;
- }else{
- error = this;
- Error.call(this, ExceptionMessage[code]);
- this.message = ExceptionMessage[code];
- if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
- }
- error.code = code;
- if(message) this.message = this.message + ": " + message;
- return error;
- };
- DOMException.prototype = Error.prototype;
- copy(ExceptionCode,DOMException)
- /**
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
- * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
- * The items in the NodeList are accessible via an integral index, starting from 0.
- */
- function NodeList() {
- };
- NodeList.prototype = {
- /**
- * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
- * @standard level1
- */
- length:0,
- /**
- * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
- * @standard level1
- * @param index unsigned long
- * Index into the collection.
- * @return Node
- * The node at the indexth position in the NodeList, or null if that is not a valid index.
- */
- item: function(index) {
- return this[index] || null;
- },
- toString:function(isHTML,nodeFilter){
- for(var buf = [], i = 0;i<this.length;i++){
- serializeToString(this[i],buf,isHTML,nodeFilter);
- }
- return buf.join('');
- }
- };
- function LiveNodeList(node,refresh){
- this._node = node;
- this._refresh = refresh
- _updateLiveList(this);
- }
- function _updateLiveList(list){
- var inc = list._node._inc || list._node.ownerDocument._inc;
- if(list._inc != inc){
- var ls = list._refresh(list._node);
- //console.log(ls.length)
- __set__(list,'length',ls.length);
- copy(ls,list);
- list._inc = inc;
- }
- }
- LiveNodeList.prototype.item = function(i){
- _updateLiveList(this);
- return this[i];
- }
- _extends(LiveNodeList,NodeList);
- /**
- *
- * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
- * NamedNodeMap objects in the DOM are live.
- * used for attributes or DocumentType entities
- */
- function NamedNodeMap() {
- };
- function _findNodeIndex(list,node){
- var i = list.length;
- while(i--){
- if(list[i] === node){return i}
- }
- }
- function _addNamedNode(el,list,newAttr,oldAttr){
- if(oldAttr){
- list[_findNodeIndex(list,oldAttr)] = newAttr;
- }else{
- list[list.length++] = newAttr;
- }
- if(el){
- newAttr.ownerElement = el;
- var doc = el.ownerDocument;
- if(doc){
- oldAttr && _onRemoveAttribute(doc,el,oldAttr);
- _onAddAttribute(doc,el,newAttr);
- }
- }
- }
- function _removeNamedNode(el,list,attr){
- //console.log('remove attr:'+attr)
- var i = _findNodeIndex(list,attr);
- if(i>=0){
- var lastIndex = list.length-1
- while(i<lastIndex){
- list[i] = list[++i]
- }
- list.length = lastIndex;
- if(el){
- var doc = el.ownerDocument;
- if(doc){
- _onRemoveAttribute(doc,el,attr);
- attr.ownerElement = null;
- }
- }
- }else{
- throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
- }
- }
- NamedNodeMap.prototype = {
- length:0,
- item:NodeList.prototype.item,
- getNamedItem: function(key) {
- // if(key.indexOf(':')>0 || key == 'xmlns'){
- // return null;
- // }
- //console.log()
- var i = this.length;
- while(i--){
- var attr = this[i];
- //console.log(attr.nodeName,key)
- if(attr.nodeName == key){
- return attr;
- }
- }
- },
- setNamedItem: function(attr) {
- var el = attr.ownerElement;
- if(el && el!=this._ownerElement){
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
- }
- var oldAttr = this.getNamedItem(attr.nodeName);
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
- return oldAttr;
- },
- /* returns Node */
- setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
- var el = attr.ownerElement, oldAttr;
- if(el && el!=this._ownerElement){
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
- }
- oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
- return oldAttr;
- },
- /* returns Node */
- removeNamedItem: function(key) {
- var attr = this.getNamedItem(key);
- _removeNamedNode(this._ownerElement,this,attr);
- return attr;
-
-
- },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
-
- //for level2
- removeNamedItemNS:function(namespaceURI,localName){
- var attr = this.getNamedItemNS(namespaceURI,localName);
- _removeNamedNode(this._ownerElement,this,attr);
- return attr;
- },
- getNamedItemNS: function(namespaceURI, localName) {
- var i = this.length;
- while(i--){
- var node = this[i];
- if(node.localName == localName && node.namespaceURI == namespaceURI){
- return node;
- }
- }
- return null;
- }
- };
- /**
- * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
- */
- function DOMImplementation(/* Object */ features) {
- this._features = {};
- if (features) {
- for (var feature in features) {
- this._features = features[feature];
- }
- }
- };
- DOMImplementation.prototype = {
- hasFeature: function(/* string */ feature, /* string */ version) {
- var versions = this._features[feature.toLowerCase()];
- if (versions && (!version || version in versions)) {
- return true;
- } else {
- return false;
- }
- },
- // Introduced in DOM Level 2:
- createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
- var doc = new Document();
- doc.implementation = this;
- doc.childNodes = new NodeList();
- doc.doctype = doctype;
- if(doctype){
- doc.appendChild(doctype);
- }
- if(qualifiedName){
- var root = doc.createElementNS(namespaceURI,qualifiedName);
- doc.appendChild(root);
- }
- return doc;
- },
- // Introduced in DOM Level 2:
- createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
- var node = new DocumentType();
- node.name = qualifiedName;
- node.nodeName = qualifiedName;
- node.publicId = publicId;
- node.systemId = systemId;
- // Introduced in DOM Level 2:
- //readonly attribute DOMString internalSubset;
-
- //TODO:..
- // readonly attribute NamedNodeMap entities;
- // readonly attribute NamedNodeMap notations;
- return node;
- }
- };
- /**
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
- */
- function Node() {
- };
- Node.prototype = {
- firstChild : null,
- lastChild : null,
- previousSibling : null,
- nextSibling : null,
- attributes : null,
- parentNode : null,
- childNodes : null,
- ownerDocument : null,
- nodeValue : null,
- namespaceURI : null,
- prefix : null,
- localName : null,
- // Modified in DOM Level 2:
- insertBefore:function(newChild, refChild){//raises
- return _insertBefore(this,newChild,refChild);
- },
- replaceChild:function(newChild, oldChild){//raises
- this.insertBefore(newChild,oldChild);
- if(oldChild){
- this.removeChild(oldChild);
- }
- },
- removeChild:function(oldChild){
- return _removeChild(this,oldChild);
- },
- appendChild:function(newChild){
- return this.insertBefore(newChild,null);
- },
- hasChildNodes:function(){
- return this.firstChild != null;
- },
- cloneNode:function(deep){
- return cloneNode(this.ownerDocument||this,this,deep);
- },
- // Modified in DOM Level 2:
- normalize:function(){
- var child = this.firstChild;
- while(child){
- var next = child.nextSibling;
- if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
- this.removeChild(next);
- child.appendData(next.data);
- }else{
- child.normalize();
- child = next;
- }
- }
- },
- // Introduced in DOM Level 2:
- isSupported:function(feature, version){
- return this.ownerDocument.implementation.hasFeature(feature,version);
- },
- // Introduced in DOM Level 2:
- hasAttributes:function(){
- return this.attributes.length>0;
- },
- lookupPrefix:function(namespaceURI){
- var el = this;
- while(el){
- var map = el._nsMap;
- //console.dir(map)
- if(map){
- for(var n in map){
- if(map[n] == namespaceURI){
- return n;
- }
- }
- }
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
- }
- return null;
- },
- // Introduced in DOM Level 3:
- lookupNamespaceURI:function(prefix){
- var el = this;
- while(el){
- var map = el._nsMap;
- //console.dir(map)
- if(map){
- if(prefix in map){
- return map[prefix] ;
- }
- }
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
- }
- return null;
- },
- // Introduced in DOM Level 3:
- isDefaultNamespace:function(namespaceURI){
- var prefix = this.lookupPrefix(namespaceURI);
- return prefix == null;
- }
- };
- function _xmlEncoder(c){
- return c == '<' && '<' ||
- c == '>' && '>' ||
- c == '&' && '&' ||
- c == '"' && '"' ||
- '&#'+c.charCodeAt()+';'
- }
- copy(NodeType,Node);
- copy(NodeType,Node.prototype);
- /**
- * @param callback return true for continue,false for break
- * @return boolean true: break visit;
- */
- function _visitNode(node,callback){
- if(callback(node)){
- return true;
- }
- if(node = node.firstChild){
- do{
- if(_visitNode(node,callback)){return true}
- }while(node=node.nextSibling)
- }
- }
- function Document(){
- }
- function _onAddAttribute(doc,el,newAttr){
- doc && doc._inc++;
- var ns = newAttr.namespaceURI ;
- if(ns == 'http://www.w3.org/2000/xmlns/'){
- //update namespace
- el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
- }
- }
- function _onRemoveAttribute(doc,el,newAttr,remove){
- doc && doc._inc++;
- var ns = newAttr.namespaceURI ;
- if(ns == 'http://www.w3.org/2000/xmlns/'){
- //update namespace
- delete el._nsMap[newAttr.prefix?newAttr.localName:'']
- }
- }
- function _onUpdateChild(doc,el,newChild){
- if(doc && doc._inc){
- doc._inc++;
- //update childNodes
- var cs = el.childNodes;
- if(newChild){
- cs[cs.length++] = newChild;
- }else{
- //console.log(1)
- var child = el.firstChild;
- var i = 0;
- while(child){
- cs[i++] = child;
- child =child.nextSibling;
- }
- cs.length = i;
- }
- }
- }
- /**
- * attributes;
- * children;
- *
- * writeable properties:
- * nodeValue,Attr:value,CharacterData:data
- * prefix
- */
- function _removeChild(parentNode,child){
- var previous = child.previousSibling;
- var next = child.nextSibling;
- if(previous){
- previous.nextSibling = next;
- }else{
- parentNode.firstChild = next
- }
- if(next){
- next.previousSibling = previous;
- }else{
- parentNode.lastChild = previous;
- }
- _onUpdateChild(parentNode.ownerDocument,parentNode);
- return child;
- }
- /**
- * preformance key(refChild == null)
- */
- function _insertBefore(parentNode,newChild,nextChild){
- var cp = newChild.parentNode;
- if(cp){
- cp.removeChild(newChild);//remove and update
- }
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
- var newFirst = newChild.firstChild;
- if (newFirst == null) {
- return newChild;
- }
- var newLast = newChild.lastChild;
- }else{
- newFirst = newLast = newChild;
- }
- var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
- newFirst.previousSibling = pre;
- newLast.nextSibling = nextChild;
-
-
- if(pre){
- pre.nextSibling = newFirst;
- }else{
- parentNode.firstChild = newFirst;
- }
- if(nextChild == null){
- parentNode.lastChild = newLast;
- }else{
- nextChild.previousSibling = newLast;
- }
- do{
- newFirst.parentNode = parentNode;
- }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
- _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
- //console.log(parentNode.lastChild.nextSibling == null)
- if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
- newChild.firstChild = newChild.lastChild = null;
- }
- return newChild;
- }
- function _appendSingleChild(parentNode,newChild){
- var cp = newChild.parentNode;
- if(cp){
- var pre = parentNode.lastChild;
- cp.removeChild(newChild);//remove and update
- var pre = parentNode.lastChild;
- }
- var pre = parentNode.lastChild;
- newChild.parentNode = parentNode;
- newChild.previousSibling = pre;
- newChild.nextSibling = null;
- if(pre){
- pre.nextSibling = newChild;
- }else{
- parentNode.firstChild = newChild;
- }
- parentNode.lastChild = newChild;
- _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
- return newChild;
- //console.log("__aa",parentNode.lastChild.nextSibling == null)
- }
- Document.prototype = {
- //implementation : null,
- nodeName : '#document',
- nodeType : DOCUMENT_NODE,
- doctype : null,
- documentElement : null,
- _inc : 1,
-
- insertBefore : function(newChild, refChild){//raises
- if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
- var child = newChild.firstChild;
- while(child){
- var next = child.nextSibling;
- this.insertBefore(child,refChild);
- child = next;
- }
- return newChild;
- }
- if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
- this.documentElement = newChild;
- }
-
- return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
- },
- removeChild : function(oldChild){
- if(this.documentElement == oldChild){
- this.documentElement = null;
- }
- return _removeChild(this,oldChild);
- },
- // Introduced in DOM Level 2:
- importNode : function(importedNode,deep){
- return importNode(this,importedNode,deep);
- },
- // Introduced in DOM Level 2:
- getElementById : function(id){
- var rtv = null;
- _visitNode(this.documentElement,function(node){
- if(node.nodeType == ELEMENT_NODE){
- if(node.getAttribute('id') == id){
- rtv = node;
- return true;
- }
- }
- })
- return rtv;
- },
-
- //document factory method:
- createElement : function(tagName){
- var node = new Element();
- node.ownerDocument = this;
- node.nodeName = tagName;
- node.tagName = tagName;
- node.childNodes = new NodeList();
- var attrs = node.attributes = new NamedNodeMap();
- attrs._ownerElement = node;
- return node;
- },
- createDocumentFragment : function(){
- var node = new DocumentFragment();
- node.ownerDocument = this;
- node.childNodes = new NodeList();
- return node;
- },
- createTextNode : function(data){
- var node = new Text();
- node.ownerDocument = this;
- node.appendData(data)
- return node;
- },
- createComment : function(data){
- var node = new Comment();
- node.ownerDocument = this;
- node.appendData(data)
- return node;
- },
- createCDATASection : function(data){
- var node = new CDATASection();
- node.ownerDocument = this;
- node.appendData(data)
- return node;
- },
- createProcessingInstruction : function(target,data){
- var node = new ProcessingInstruction();
- node.ownerDocument = this;
- node.tagName = node.target = target;
- node.nodeValue= node.data = data;
- return node;
- },
- createAttribute : function(name){
- var node = new Attr();
- node.ownerDocument = this;
- node.name = name;
- node.nodeName = name;
- node.localName = name;
- node.specified = true;
- return node;
- },
- createEntityReference : function(name){
- var node = new EntityReference();
- node.ownerDocument = this;
- node.nodeName = name;
- return node;
- },
- // Introduced in DOM Level 2:
- createElementNS : function(namespaceURI,qualifiedName){
- var node = new Element();
- var pl = qualifiedName.split(':');
- var attrs = node.attributes = new NamedNodeMap();
- node.childNodes = new NodeList();
- node.ownerDocument = this;
- node.nodeName = qualifiedName;
- node.tagName = qualifiedName;
- node.namespaceURI = namespaceURI;
- if(pl.length == 2){
- node.prefix = pl[0];
- node.localName = pl[1];
- }else{
- //el.prefix = null;
- node.localName = qualifiedName;
- }
- attrs._ownerElement = node;
- return node;
- },
- // Introduced in DOM Level 2:
- createAttributeNS : function(namespaceURI,qualifiedName){
- var node = new Attr();
- var pl = qualifiedName.split(':');
- node.ownerDocument = this;
- node.nodeName = qualifiedName;
- node.name = qualifiedName;
- node.namespaceURI = namespaceURI;
- node.specified = true;
- if(pl.length == 2){
- node.prefix = pl[0];
- node.localName = pl[1];
- }else{
- //el.prefix = null;
- node.localName = qualifiedName;
- }
- return node;
- }
- };
- _extends(Document,Node);
- function Element() {
- this._nsMap = {};
- };
- Element.prototype = {
- nodeType : ELEMENT_NODE,
- hasAttribute : function(name){
- return this.getAttributeNode(name)!=null;
- },
- getAttribute : function(name){
- var attr = this.getAttributeNode(name);
- return attr && attr.value || '';
- },
- getAttributeNode : function(name){
- return this.attributes.getNamedItem(name);
- },
- setAttribute : function(name, value){
- var attr = this.ownerDocument.createAttribute(name);
- attr.value = attr.nodeValue = "" + value;
- this.setAttributeNode(attr)
- },
- removeAttribute : function(name){
- var attr = this.getAttributeNode(name)
- attr && this.removeAttributeNode(attr);
- },
-
- //four real opeartion method
- appendChild:function(newChild){
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
- return this.insertBefore(newChild,null);
- }else{
- return _appendSingleChild(this,newChild);
- }
- },
- setAttributeNode : function(newAttr){
- return this.attributes.setNamedItem(newAttr);
- },
- setAttributeNodeNS : function(newAttr){
- return this.attributes.setNamedItemNS(newAttr);
- },
- removeAttributeNode : function(oldAttr){
- //console.log(this == oldAttr.ownerElement)
- return this.attributes.removeNamedItem(oldAttr.nodeName);
- },
- //get real attribute name,and remove it by removeAttributeNode
- removeAttributeNS : function(namespaceURI, localName){
- var old = this.getAttributeNodeNS(namespaceURI, localName);
- old && this.removeAttributeNode(old);
- },
-
- hasAttributeNS : function(namespaceURI, localName){
- return this.getAttributeNodeNS(namespaceURI, localName)!=null;
- },
- getAttributeNS : function(namespaceURI, localName){
- var attr = this.getAttributeNodeNS(namespaceURI, localName);
- return attr && attr.value || '';
- },
- setAttributeNS : function(namespaceURI, qualifiedName, value){
- var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
- attr.value = attr.nodeValue = "" + value;
- this.setAttributeNode(attr)
- },
- getAttributeNodeNS : function(namespaceURI, localName){
- return this.attributes.getNamedItemNS(namespaceURI, localName);
- },
-
- getElementsByTagName : function(tagName){
- return new LiveNodeList(this,function(base){
- var ls = [];
- _visitNode(base,function(node){
- if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
- ls.push(node);
- }
- });
- return ls;
- });
- },
- getElementsByTagNameNS : function(namespaceURI, localName){
- return new LiveNodeList(this,function(base){
- var ls = [];
- _visitNode(base,function(node){
- if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
- ls.push(node);
- }
- });
- return ls;
-
- });
- }
- };
- Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
- Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
- _extends(Element,Node);
- function Attr() {
- };
- Attr.prototype.nodeType = ATTRIBUTE_NODE;
- _extends(Attr,Node);
- function CharacterData() {
- };
- CharacterData.prototype = {
- data : '',
- substringData : function(offset, count) {
- return this.data.substring(offset, offset+count);
- },
- appendData: function(text) {
- text = this.data+text;
- this.nodeValue = this.data = text;
- this.length = text.length;
- },
- insertData: function(offset,text) {
- this.replaceData(offset,0,text);
-
- },
- appendChild:function(newChild){
- throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
- },
- deleteData: function(offset, count) {
- this.replaceData(offset,count,"");
- },
- replaceData: function(offset, count, text) {
- var start = this.data.substring(0,offset);
- var end = this.data.substring(offset+count);
- text = start + text + end;
- this.nodeValue = this.data = text;
- this.length = text.length;
- }
- }
- _extends(CharacterData,Node);
- function Text() {
- };
- Text.prototype = {
- nodeName : "#text",
- nodeType : TEXT_NODE,
- splitText : function(offset) {
- var text = this.data;
- var newText = text.substring(offset);
- text = text.substring(0, offset);
- this.data = this.nodeValue = text;
- this.length = text.length;
- var newNode = this.ownerDocument.createTextNode(newText);
- if(this.parentNode){
- this.parentNode.insertBefore(newNode, this.nextSibling);
- }
- return newNode;
- }
- }
- _extends(Text,CharacterData);
- function Comment() {
- };
- Comment.prototype = {
- nodeName : "#comment",
- nodeType : COMMENT_NODE
- }
- _extends(Comment,CharacterData);
- function CDATASection() {
- };
- CDATASection.prototype = {
- nodeName : "#cdata-section",
- nodeType : CDATA_SECTION_NODE
- }
- _extends(CDATASection,CharacterData);
- function DocumentType() {
- };
- DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
- _extends(DocumentType,Node);
- function Notation() {
- };
- Notation.prototype.nodeType = NOTATION_NODE;
- _extends(Notation,Node);
- function Entity() {
- };
- Entity.prototype.nodeType = ENTITY_NODE;
- _extends(Entity,Node);
- function EntityReference() {
- };
- EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
- _extends(EntityReference,Node);
- function DocumentFragment() {
- };
- DocumentFragment.prototype.nodeName = "#document-fragment";
- DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
- _extends(DocumentFragment,Node);
- function ProcessingInstruction() {
- }
- ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
- _extends(ProcessingInstruction,Node);
- function XMLSerializer(){}
- XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
- return nodeSerializeToString.call(node,isHtml,nodeFilter);
- }
- Node.prototype.toString = nodeSerializeToString;
- function nodeSerializeToString(isHtml,nodeFilter){
- var buf = [];
- var refNode = this.nodeType == 9?this.documentElement:this;
- var prefix = refNode.prefix;
- var uri = refNode.namespaceURI;
-
- if(uri && prefix == null){
- //console.log(prefix)
- var prefix = refNode.lookupPrefix(uri);
- if(prefix == null){
- //isHTML = true;
- var visibleNamespaces=[
- {namespace:uri,prefix:null}
- //{namespace:uri,prefix:''}
- ]
- }
- }
- serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
- //console.log('###',this.nodeType,uri,prefix,buf.join(''))
- return buf.join('');
- }
- function needNamespaceDefine(node,isHTML, visibleNamespaces) {
- var prefix = node.prefix||'';
- var uri = node.namespaceURI;
- if (!prefix && !uri){
- return false;
- }
- if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
- || uri == 'http://www.w3.org/2000/xmlns/'){
- return false;
- }
-
- var i = visibleNamespaces.length
- //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
- while (i--) {
- var ns = visibleNamespaces[i];
- // get namespace prefix
- //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
- if (ns.prefix == prefix){
- return ns.namespace != uri;
- }
- }
- //console.log(isHTML,uri,prefix=='')
- //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
- // return false;
- //}
- //node.flag = '11111'
- //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
- return true;
- }
- function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
- if(nodeFilter){
- node = nodeFilter(node);
- if(node){
- if(typeof node == 'string'){
- buf.push(node);
- return;
- }
- }else{
- return;
- }
- //buf.sort.apply(attrs, attributeSorter);
- }
- switch(node.nodeType){
- case ELEMENT_NODE:
- if (!visibleNamespaces) visibleNamespaces = [];
- var startVisibleNamespaces = visibleNamespaces.length;
- var attrs = node.attributes;
- var len = attrs.length;
- var child = node.firstChild;
- var nodeName = node.tagName;
-
- isHTML = (htmlns === node.namespaceURI) ||isHTML
- buf.push('<',nodeName);
-
-
-
- for(var i=0;i<len;i++){
- // add namespaces for attributes
- var attr = attrs.item(i);
- if (attr.prefix == 'xmlns') {
- visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
- }else if(attr.nodeName == 'xmlns'){
- visibleNamespaces.push({ prefix: '', namespace: attr.value });
- }
- }
- for(var i=0;i<len;i++){
- var attr = attrs.item(i);
- if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
- var prefix = attr.prefix||'';
- var uri = attr.namespaceURI;
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
- buf.push(ns, '="' , uri , '"');
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
- }
- serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
- }
- // add namespace for current node
- if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
- var prefix = node.prefix||'';
- var uri = node.namespaceURI;
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
- buf.push(ns, '="' , uri , '"');
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
- }
-
- if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
- buf.push('>');
- //if is cdata child node
- if(isHTML && /^script$/i.test(nodeName)){
- while(child){
- if(child.data){
- buf.push(child.data);
- }else{
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
- }
- child = child.nextSibling;
- }
- }else
- {
- while(child){
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
- child = child.nextSibling;
- }
- }
- buf.push('</',nodeName,'>');
- }else{
- buf.push('/>');
- }
- // remove added visible namespaces
- //visibleNamespaces.length = startVisibleNamespaces;
- return;
- case DOCUMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- var child = node.firstChild;
- while(child){
- serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
- child = child.nextSibling;
- }
- return;
- case ATTRIBUTE_NODE:
- return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
- case TEXT_NODE:
- return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
- case CDATA_SECTION_NODE:
- return buf.push( '<![CDATA[',node.data,']]>');
- case COMMENT_NODE:
- return buf.push( "<!--",node.data,"-->");
- case DOCUMENT_TYPE_NODE:
- var pubid = node.publicId;
- var sysid = node.systemId;
- buf.push('<!DOCTYPE ',node.name);
- if(pubid){
- buf.push(' PUBLIC "',pubid);
- if (sysid && sysid!='.') {
- buf.push( '" "',sysid);
- }
- buf.push('">');
- }else if(sysid && sysid!='.'){
- buf.push(' SYSTEM "',sysid,'">');
- }else{
- var sub = node.internalSubset;
- if(sub){
- buf.push(" [",sub,"]");
- }
- buf.push(">");
- }
- return;
- case PROCESSING_INSTRUCTION_NODE:
- return buf.push( "<?",node.target," ",node.data,"?>");
- case ENTITY_REFERENCE_NODE:
- return buf.push( '&',node.nodeName,';');
- //case ENTITY_NODE:
- //case NOTATION_NODE:
- default:
- buf.push('??',node.nodeName);
- }
- }
- function importNode(doc,node,deep){
- var node2;
- switch (node.nodeType) {
- case ELEMENT_NODE:
- node2 = node.cloneNode(false);
- node2.ownerDocument = doc;
- //var attrs = node2.attributes;
- //var len = attrs.length;
- //for(var i=0;i<len;i++){
- //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
- //}
- case DOCUMENT_FRAGMENT_NODE:
- break;
- case ATTRIBUTE_NODE:
- deep = true;
- break;
- //case ENTITY_REFERENCE_NODE:
- //case PROCESSING_INSTRUCTION_NODE:
- ////case TEXT_NODE:
- //case CDATA_SECTION_NODE:
- //case COMMENT_NODE:
- // deep = false;
- // break;
- //case DOCUMENT_NODE:
- //case DOCUMENT_TYPE_NODE:
- //cannot be imported.
- //case ENTITY_NODE:
- //case NOTATION_NODE:
- //can not hit in level3
- //default:throw e;
- }
- if(!node2){
- node2 = node.cloneNode(false);//false
- }
- node2.ownerDocument = doc;
- node2.parentNode = null;
- if(deep){
- var child = node.firstChild;
- while(child){
- node2.appendChild(importNode(doc,child,deep));
- child = child.nextSibling;
- }
- }
- return node2;
- }
- //
- //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
- // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
- function cloneNode(doc,node,deep){
- var node2 = new node.constructor();
- for(var n in node){
- var v = node[n];
- if(typeof v != 'object' ){
- if(v != node2[n]){
- node2[n] = v;
- }
- }
- }
- if(node.childNodes){
- node2.childNodes = new NodeList();
- }
- node2.ownerDocument = doc;
- switch (node2.nodeType) {
- case ELEMENT_NODE:
- var attrs = node.attributes;
- var attrs2 = node2.attributes = new NamedNodeMap();
- var len = attrs.length
- attrs2._ownerElement = node2;
- for(var i=0;i<len;i++){
- node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
- }
- break;;
- case ATTRIBUTE_NODE:
- deep = true;
- }
- if(deep){
- var child = node.firstChild;
- while(child){
- node2.appendChild(cloneNode(doc,child,deep));
- child = child.nextSibling;
- }
- }
- return node2;
- }
- function __set__(object,key,value){
- object[key] = value
- }
- //do dynamic
- try{
- if(Object.defineProperty){
- Object.defineProperty(LiveNodeList.prototype,'length',{
- get:function(){
- _updateLiveList(this);
- return this.$$length;
- }
- });
- Object.defineProperty(Node.prototype,'textContent',{
- get:function(){
- return getTextContent(this);
- },
- set:function(data){
- switch(this.nodeType){
- case ELEMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- while(this.firstChild){
- this.removeChild(this.firstChild);
- }
- if(data || String(data)){
- this.appendChild(this.ownerDocument.createTextNode(data));
- }
- break;
- default:
- //TODO:
- this.data = data;
- this.value = data;
- this.nodeValue = data;
- }
- }
- })
-
- function getTextContent(node){
- switch(node.nodeType){
- case ELEMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- var buf = [];
- node = node.firstChild;
- while(node){
- if(node.nodeType!==7 && node.nodeType !==8){
- buf.push(getTextContent(node));
- }
- node = node.nextSibling;
- }
- return buf.join('');
- default:
- return node.nodeValue;
- }
- }
- __set__ = function(object,key,value){
- //console.log(value)
- object['$$'+key] = value
- }
- }
- }catch(e){//ie8
- }
- //if(typeof require == 'function'){
- exports.DOMImplementation = DOMImplementation;
- exports.XMLSerializer = XMLSerializer;
- //}
- },{}],212:[function(require,module,exports){
- //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
- //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
- //[5] Name ::= NameStartChar (NameChar)*
- var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
- var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
- var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
- //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
- //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
- var S_TAG = 0;//tag name offerring
- var S_ATTR = 1;//attr name offerring
- var S_ATTR_SPACE=2;//attr name end and space offer
- var S_EQ = 3;//=space?
- var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
- var S_ATTR_END = 5;//attr value end and no space(quot end)
- var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
- var S_TAG_CLOSE = 7;//closed el<el />
- function XMLReader(){
-
- }
- XMLReader.prototype = {
- parse:function(source,defaultNSMap,entityMap){
- var domBuilder = this.domBuilder;
- domBuilder.startDocument();
- _copy(defaultNSMap ,defaultNSMap = {})
- parse(source,defaultNSMap,entityMap,
- domBuilder,this.errorHandler);
- domBuilder.endDocument();
- }
- }
- function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
- function fixedFromCharCode(code) {
- // String.prototype.fromCharCode does not supports
- // > 2 bytes unicode chars directly
- if (code > 0xffff) {
- code -= 0x10000;
- var surrogate1 = 0xd800 + (code >> 10)
- , surrogate2 = 0xdc00 + (code & 0x3ff);
- return String.fromCharCode(surrogate1, surrogate2);
- } else {
- return String.fromCharCode(code);
- }
- }
- function entityReplacer(a){
- var k = a.slice(1,-1);
- if(k in entityMap){
- return entityMap[k];
- }else if(k.charAt(0) === '#'){
- return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
- }else{
- errorHandler.error('entity not found:'+a);
- return a;
- }
- }
- function appendText(end){//has some bugs
- if(end>start){
- var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
- locator&&position(start);
- domBuilder.characters(xt,0,end-start);
- start = end
- }
- }
- function position(p,m){
- while(p>=lineEnd && (m = linePattern.exec(source))){
- lineStart = m.index;
- lineEnd = lineStart + m[0].length;
- locator.lineNumber++;
- //console.log('line++:',locator,startPos,endPos)
- }
- locator.columnNumber = p-lineStart+1;
- }
- var lineStart = 0;
- var lineEnd = 0;
- var linePattern = /.*(?:\r\n?|\n)|.*$/g
- var locator = domBuilder.locator;
-
- var parseStack = [{currentNSMap:defaultNSMapCopy}]
- var closeMap = {};
- var start = 0;
- while(true){
- try{
- var tagStart = source.indexOf('<',start);
- if(tagStart<0){
- if(!source.substr(start).match(/^\s*$/)){
- var doc = domBuilder.doc;
- var text = doc.createTextNode(source.substr(start));
- doc.appendChild(text);
- domBuilder.currentElement = text;
- }
- return;
- }
- if(tagStart>start){
- appendText(tagStart);
- }
- switch(source.charAt(tagStart+1)){
- case '/':
- var end = source.indexOf('>',tagStart+3);
- var tagName = source.substring(tagStart+2,end);
- var config = parseStack.pop();
- if(end<0){
-
- tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
- //console.error('#@@@@@@'+tagName)
- errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
- end = tagStart+1+tagName.length;
- }else if(tagName.match(/\s</)){
- tagName = tagName.replace(/[\s<].*/,'');
- errorHandler.error("end tag name: "+tagName+' maybe not complete');
- end = tagStart+1+tagName.length;
- }
- //console.error(parseStack.length,parseStack)
- //console.error(config);
- var localNSMap = config.localNSMap;
- var endMatch = config.tagName == tagName;
- var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
- if(endIgnoreCaseMach){
- domBuilder.endElement(config.uri,config.localName,tagName);
- if(localNSMap){
- for(var prefix in localNSMap){
- domBuilder.endPrefixMapping(prefix) ;
- }
- }
- if(!endMatch){
- errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
- }
- }else{
- parseStack.push(config)
- }
-
- end++;
- break;
- // end elment
- case '?':// <?...?>
- locator&&position(tagStart);
- end = parseInstruction(source,tagStart,domBuilder);
- break;
- case '!':// <!doctype,<![CDATA,<!--
- locator&&position(tagStart);
- end = parseDCC(source,tagStart,domBuilder,errorHandler);
- break;
- default:
- locator&&position(tagStart);
- var el = new ElementAttributes();
- var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
- //elStartEnd
- var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
- var len = el.length;
-
-
- if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
- el.closed = true;
- if(!entityMap.nbsp){
- errorHandler.warning('unclosed xml attribute');
- }
- }
- if(locator && len){
- var locator2 = copyLocator(locator,{});
- //try{//attribute position fixed
- for(var i = 0;i<len;i++){
- var a = el[i];
- position(a.offset);
- a.locator = copyLocator(locator,{});
- }
- //}catch(e){console.error('@@@@@'+e)}
- domBuilder.locator = locator2
- if(appendElement(el,domBuilder,currentNSMap)){
- parseStack.push(el)
- }
- domBuilder.locator = locator;
- }else{
- if(appendElement(el,domBuilder,currentNSMap)){
- parseStack.push(el)
- }
- }
-
-
-
- if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
- end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
- }else{
- end++;
- }
- }
- }catch(e){
- errorHandler.error('element parse error: '+e)
- //errorHandler.error('element parse error: '+e);
- end = -1;
- //throw e;
- }
- if(end>start){
- start = end;
- }else{
- //TODO: 这里有可能sax回退,有位置错误风险
- appendText(Math.max(tagStart,start)+1);
- }
- }
- }
- function copyLocator(f,t){
- t.lineNumber = f.lineNumber;
- t.columnNumber = f.columnNumber;
- return t;
- }
- /**
- * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
- */
- function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
- var attrName;
- var value;
- var p = ++start;
- var s = S_TAG;//status
- while(true){
- var c = source.charAt(p);
- switch(c){
- case '=':
- if(s === S_ATTR){//attrName
- attrName = source.slice(start,p);
- s = S_EQ;
- }else if(s === S_ATTR_SPACE){
- s = S_EQ;
- }else{
- //fatalError: equal must after attrName or space after attrName
- throw new Error('attribute equal must after attrName');
- }
- break;
- case '\'':
- case '"':
- if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
- ){//equal
- if(s === S_ATTR){
- errorHandler.warning('attribute value must after "="')
- attrName = source.slice(start,p)
- }
- start = p+1;
- p = source.indexOf(c,start)
- if(p>0){
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
- el.add(attrName,value,start-1);
- s = S_ATTR_END;
- }else{
- //fatalError: no end quot match
- throw new Error('attribute value no end \''+c+'\' match');
- }
- }else if(s == S_ATTR_NOQUOT_VALUE){
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
- //console.log(attrName,value,start,p)
- el.add(attrName,value,start);
- //console.dir(el)
- errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
- start = p+1;
- s = S_ATTR_END
- }else{
- //fatalError: no equal before
- throw new Error('attribute value must after "="');
- }
- break;
- case '/':
- switch(s){
- case S_TAG:
- el.setTagName(source.slice(start,p));
- case S_ATTR_END:
- case S_TAG_SPACE:
- case S_TAG_CLOSE:
- s =S_TAG_CLOSE;
- el.closed = true;
- case S_ATTR_NOQUOT_VALUE:
- case S_ATTR:
- case S_ATTR_SPACE:
- break;
- //case S_EQ:
- default:
- throw new Error("attribute invalid close char('/')")
- }
- break;
- case ''://end document
- //throw new Error('unexpected end of input')
- errorHandler.error('unexpected end of input');
- if(s == S_TAG){
- el.setTagName(source.slice(start,p));
- }
- return p;
- case '>':
- switch(s){
- case S_TAG:
- el.setTagName(source.slice(start,p));
- case S_ATTR_END:
- case S_TAG_SPACE:
- case S_TAG_CLOSE:
- break;//normal
- case S_ATTR_NOQUOT_VALUE://Compatible state
- case S_ATTR:
- value = source.slice(start,p);
- if(value.slice(-1) === '/'){
- el.closed = true;
- value = value.slice(0,-1)
- }
- case S_ATTR_SPACE:
- if(s === S_ATTR_SPACE){
- value = attrName;
- }
- if(s == S_ATTR_NOQUOT_VALUE){
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
- el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
- }else{
- if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
- errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
- }
- el.add(value,value,start)
- }
- break;
- case S_EQ:
- throw new Error('attribute value missed!!');
- }
- // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
- return p;
- /*xml space '\x20' | #x9 | #xD | #xA; */
- case '\u0080':
- c = ' ';
- default:
- if(c<= ' '){//space
- switch(s){
- case S_TAG:
- el.setTagName(source.slice(start,p));//tagName
- s = S_TAG_SPACE;
- break;
- case S_ATTR:
- attrName = source.slice(start,p)
- s = S_ATTR_SPACE;
- break;
- case S_ATTR_NOQUOT_VALUE:
- var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
- el.add(attrName,value,start)
- case S_ATTR_END:
- s = S_TAG_SPACE;
- break;
- //case S_TAG_SPACE:
- //case S_EQ:
- //case S_ATTR_SPACE:
- // void();break;
- //case S_TAG_CLOSE:
- //ignore warning
- }
- }else{//not space
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
- switch(s){
- //case S_TAG:void();break;
- //case S_ATTR:void();break;
- //case S_ATTR_NOQUOT_VALUE:void();break;
- case S_ATTR_SPACE:
- var tagName = el.tagName;
- if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
- errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
- }
- el.add(attrName,attrName,start);
- start = p;
- s = S_ATTR;
- break;
- case S_ATTR_END:
- errorHandler.warning('attribute space is required"'+attrName+'"!!')
- case S_TAG_SPACE:
- s = S_ATTR;
- start = p;
- break;
- case S_EQ:
- s = S_ATTR_NOQUOT_VALUE;
- start = p;
- break;
- case S_TAG_CLOSE:
- throw new Error("elements closed character '/' and '>' must be connected to");
- }
- }
- }//end outer switch
- //console.log('p++',p)
- p++;
- }
- }
- /**
- * @return true if has new namespace define
- */
- function appendElement(el,domBuilder,currentNSMap){
- var tagName = el.tagName;
- var localNSMap = null;
- //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
- var i = el.length;
- while(i--){
- var a = el[i];
- var qName = a.qName;
- var value = a.value;
- var nsp = qName.indexOf(':');
- if(nsp>0){
- var prefix = a.prefix = qName.slice(0,nsp);
- var localName = qName.slice(nsp+1);
- var nsPrefix = prefix === 'xmlns' && localName
- }else{
- localName = qName;
- prefix = null
- nsPrefix = qName === 'xmlns' && ''
- }
- //can not set prefix,because prefix !== ''
- a.localName = localName ;
- //prefix == null for no ns prefix attribute
- if(nsPrefix !== false){//hack!!
- if(localNSMap == null){
- localNSMap = {}
- //console.log(currentNSMap,0)
- _copy(currentNSMap,currentNSMap={})
- //console.log(currentNSMap,1)
- }
- currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
- a.uri = 'http://www.w3.org/2000/xmlns/'
- domBuilder.startPrefixMapping(nsPrefix, value)
- }
- }
- var i = el.length;
- while(i--){
- a = el[i];
- var prefix = a.prefix;
- if(prefix){//no prefix attribute has no namespace
- if(prefix === 'xml'){
- a.uri = 'http://www.w3.org/XML/1998/namespace';
- }if(prefix !== 'xmlns'){
- a.uri = currentNSMap[prefix || '']
-
- //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
- }
- }
- }
- var nsp = tagName.indexOf(':');
- if(nsp>0){
- prefix = el.prefix = tagName.slice(0,nsp);
- localName = el.localName = tagName.slice(nsp+1);
- }else{
- prefix = null;//important!!
- localName = el.localName = tagName;
- }
- //no prefix element has default namespace
- var ns = el.uri = currentNSMap[prefix || ''];
- domBuilder.startElement(ns,localName,tagName,el);
- //endPrefixMapping and startPrefixMapping have not any help for dom builder
- //localNSMap = null
- if(el.closed){
- domBuilder.endElement(ns,localName,tagName);
- if(localNSMap){
- for(prefix in localNSMap){
- domBuilder.endPrefixMapping(prefix)
- }
- }
- }else{
- el.currentNSMap = currentNSMap;
- el.localNSMap = localNSMap;
- //parseStack.push(el);
- return true;
- }
- }
- function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
- if(/^(?:script|textarea)$/i.test(tagName)){
- var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
- var text = source.substring(elStartEnd+1,elEndStart);
- if(/[&<]/.test(text)){
- if(/^script$/i.test(tagName)){
- //if(!/\]\]>/.test(text)){
- //lexHandler.startCDATA();
- domBuilder.characters(text,0,text.length);
- //lexHandler.endCDATA();
- return elEndStart;
- //}
- }//}else{//text area
- text = text.replace(/&#?\w+;/g,entityReplacer);
- domBuilder.characters(text,0,text.length);
- return elEndStart;
- //}
-
- }
- }
- return elStartEnd+1;
- }
- function fixSelfClosed(source,elStartEnd,tagName,closeMap){
- //if(tagName in closeMap){
- var pos = closeMap[tagName];
- if(pos == null){
- //console.log(tagName)
- pos = source.lastIndexOf('</'+tagName+'>')
- if(pos<elStartEnd){//忘记闭合
- pos = source.lastIndexOf('</'+tagName)
- }
- closeMap[tagName] =pos
- }
- return pos<elStartEnd;
- //}
- }
- function _copy(source,target){
- for(var n in source){target[n] = source[n]}
- }
- function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
- var next= source.charAt(start+2)
- switch(next){
- case '-':
- if(source.charAt(start + 3) === '-'){
- var end = source.indexOf('-->',start+4);
- //append comment source.substring(4,end)//<!--
- if(end>start){
- domBuilder.comment(source,start+4,end-start-4);
- return end+3;
- }else{
- errorHandler.error("Unclosed comment");
- return -1;
- }
- }else{
- //error
- return -1;
- }
- default:
- if(source.substr(start+3,6) == 'CDATA['){
- var end = source.indexOf(']]>',start+9);
- domBuilder.startCDATA();
- domBuilder.characters(source,start+9,end-start-9);
- domBuilder.endCDATA()
- return end+3;
- }
- //<!DOCTYPE
- //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
- var matchs = split(source,start);
- var len = matchs.length;
- if(len>1 && /!doctype/i.test(matchs[0][0])){
- var name = matchs[1][0];
- var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
- var sysid = len>4 && matchs[4][0];
- var lastMatch = matchs[len-1]
- domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
- sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
- domBuilder.endDTD();
-
- return lastMatch.index+lastMatch[0].length
- }
- }
- return -1;
- }
- function parseInstruction(source,start,domBuilder){
- var end = source.indexOf('?>',start);
- if(end){
- var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
- if(match){
- var len = match[0].length;
- domBuilder.processingInstruction(match[1], match[2]) ;
- return end+2;
- }else{//error
- return -1;
- }
- }
- return -1;
- }
- /**
- * @param source
- */
- function ElementAttributes(source){
-
- }
- ElementAttributes.prototype = {
- setTagName:function(tagName){
- if(!tagNamePattern.test(tagName)){
- throw new Error('invalid tagName:'+tagName)
- }
- this.tagName = tagName
- },
- add:function(qName,value,offset){
- if(!tagNamePattern.test(qName)){
- throw new Error('invalid attribute:'+qName)
- }
- this[this.length++] = {qName:qName,value:value,offset:offset}
- },
- length:0,
- getLocalName:function(i){return this[i].localName},
- getLocator:function(i){return this[i].locator},
- getQName:function(i){return this[i].qName},
- getURI:function(i){return this[i].uri},
- getValue:function(i){return this[i].value}
- // ,getIndex:function(uri, localName)){
- // if(localName){
- //
- // }else{
- // var qName = uri
- // }
- // },
- // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
- // getType:function(uri,localName){}
- // getType:function(i){},
- }
- function _set_proto_(thiz,parent){
- thiz.__proto__ = parent;
- return thiz;
- }
- if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
- _set_proto_ = function(thiz,parent){
- function p(){};
- p.prototype = parent;
- p = new p();
- for(parent in thiz){
- p[parent] = thiz[parent];
- }
- return p;
- }
- }
- function split(source,start){
- var match;
- var buf = [];
- var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
- reg.lastIndex = start;
- reg.exec(source);//skip <
- while(match = reg.exec(source)){
- buf.push(match);
- if(match[1])return buf;
- }
- }
- exports.XMLReader = XMLReader;
- },{}],213:[function(require,module,exports){
- /* global L */
- const isTrue = require('./isTrue')
- const styleToLeaflet = require('./styleToLeaflet')
- class DecoratorPattern {
- constructor (layer) {
- this.layer = layer
- this.layer.on('update', this.processObject.bind(this))
- this.layer.on('remove', this.removeObject.bind(this))
- }
- parseType (key, value) {
- switch (key) {
- case 'polygon':
- case 'rotate':
- return isTrue(value)
- case 'angleCorrection':
- case 'pixelSize':
- case 'headAngle':
- return parseFloat(value)
- default:
- return value
- }
- }
- processObject (object, data) {
- if (!data.patternFeatures) {
- data.patternFeatures = {}
- }
- for (var k in data.features) {
- let def = k === 'default' ? data.data.style : data.data['style:' + k]
- if (def.pattern && data.styles.includes(k)) {
- let symbol
- let symbolOptions = {}
- let options = {}
- for (let k in def) {
- let m1 = k.match(/^pattern-path-(.*)$/)
- let m2 = k.match(/^pattern-(.*)$/)
- if (m1) {
- symbolOptions[m1[1]] = def[k]
- } else if (m2) {
- options[m2[1]] = this.parseType(m2[1], def[k])
- }
- }
- symbolOptions = styleToLeaflet(symbolOptions)
- switch (def.pattern.toString()) {
- case 'dash':
- options.pathOptions = symbolOptions
- symbol = L.Symbol.dash(options)
- break
- case 'arrowHead':
- options.pathOptions = symbolOptions
- symbol = L.Symbol.arrowHead(options)
- break
- case 'marker':
- options.markerOptions = symbolOptions
- symbol = L.Symbol.marker(options)
- break
- default:
- // TODO
- }
- options.symbol = symbol
- if (!data.patternFeatures[k]) {
- data.patternFeatures[k] = L.polylineDecorator(data.features[k])
- data.patternFeatures[k].addTo(this.layer.map)
- }
- data.patternFeatures[k].setPatterns([ options ])
- if (this.layer._shallBindPopupToStyle(k)) {
- data.patternFeatures[k].bindPopup(data.popup)
- }
- } else {
- if (data.patternFeatures[k]) {
- this.layer.map.removeLayer(data.patternFeatures[k])
- delete data.patternFeatures[k]
- }
- }
- }
- }
- removeObject (object, data) {
- if (!data.patternFeatures) {
- return
- }
- for (var k in data.features) {
- if (data.patternFeatures[k]) {
- this.layer.map.removeLayer(data.patternFeatures[k])
- delete data.patternFeatures[k]
- }
- }
- }
- }
- module.exports = DecoratorPattern
- },{"./isTrue":222,"./styleToLeaflet":224}],214:[function(require,module,exports){
- const Sublayer = require('./Sublayer')
- class Memberlayer extends Sublayer {
- constructor (master, options) {
- super(master, options)
- this.masterlayer = this.master.mainlayer
- this.masterlayer.on('add', this.featureOnMainModified.bind(this))
- this.masterlayer.on('remove', this.featureOnMainModified.bind(this))
- this.masterlayer.on('update', this.featureOnMainModified.bind(this))
- this.on('add', this.featureMemberModified.bind(this))
- this.on('remove', this.featureMemberModified.bind(this))
- }
- featureMemberModified (feature, data) {
- feature.memberOf.forEach(master => {
- this.masterlayer.scheduleReprocess(master.id)
- })
- }
- featureOnMainModified (feature) {
- if (!feature.members) {
- return
- }
- feature.members.forEach(member => {
- if (member.id in this.visibleFeatures) {
- this.scheduleReprocess(member.id)
- }
- })
- }
- twigData (ob, data) {
- let result = super.twigData(ob, data)
- for (var k in this.masterlayer.visibleFeatures) {
- let feature = this.masterlayer.visibleFeatures[k]
- if (feature.object.members) {
- feature.object.members.forEach((member, sequence) => {
- if (member.id === ob.id) {
- if (!('masters' in result)) {
- result.masters = []
- }
- result.masters.push({
- id: feature.id,
- type: feature.object.type,
- osm_id: feature.object.osm_id,
- tags: feature.object.tags,
- meta: feature.object.meta,
- role: member.role,
- dir: member.dir,
- connectedPrev: member.connectedPrev,
- connectedNext: member.connectedNext,
- flags: feature.flags,
- sequence
- })
- }
- })
- }
- }
- return result
- }
- }
- module.exports = Memberlayer
- },{"./Sublayer":219}],215:[function(require,module,exports){
- var css = ".leaflet-popup-content {\n max-height: 250px;\n overflow: auto;\n}\n.leaflet-popup-content pre {\n font-size: 8px;\n}\n.overpass-layer-icon > img,\n.overpass-layer-icon > svg {\n display: block;\n}\n.overpass-layer-icon div.sign {\n position: relative;\n font-size: 12px;\n text-align: center;\n transform: translate(-50%, -50%);\n display: flex;\n justify-content: center;\n}\n/* top: -37px; */\n"; (require("browserify-css").createStyle(css, { "href": "src/OverpassLayer.css" }, { "insertAt": "bottom" })); module.exports = css;
- },{"browserify-css":22}],216:[function(require,module,exports){
- /* global overpassFrontend:false */
- /* eslint camelcase: 0 */
- require('./OverpassLayer.css')
- const ee = require('event-emitter')
- const BoundingBox = require('boundingbox')
- const twig = require('twig')
- const OverpassFrontend = require('overpass-frontend')
- const escapeHtml = require('html-escape')
- const Sublayer = require('./Sublayer')
- const Memberlayer = require('./Memberlayer')
- const compileFeature = require('./compileFeature')
- class OverpassLayer {
- constructor (options) {
- if (!options) {
- options = {}
- }
- this.options = options
- this.overpassFrontend = 'overpassFrontend' in this.options ? this.options.overpassFrontend : overpassFrontend
- this.options.minZoom = 'minZoom' in this.options ? this.options.minZoom : 16
- this.options.maxZoom = 'maxZoom' in this.options ? this.options.maxZoom : null
- this.options.feature = 'feature' in this.options ? this.options.feature : {}
- this.options.feature.style = 'style' in this.options.feature ? this.options.feature.style : {}
- this.options.feature.title = 'title' in this.options.feature ? this.options.feature.title : function (ob) { return escapeHtml(ob.tags.name || ob.tags.operator || ob.tags.ref || ob.id) }
- this.options.feature.body = 'body' in this.options.feature ? this.options.feature.body : ''
- this.options.feature.markerSymbol = 'markerSymbol' in this.options.feature ? this.options.feature.markerSymbol : '<img anchorX="13" anchorY="42" width="25" height="42" signAnchorX="0" signAnchorY="-30" src="img/map_pointer.png">'
- this.options.feature.markerSign = 'markerSign' in this.options.feature ? this.options.feature.markerSign : null
- this.options.queryOptions = 'queryOptions' in this.options ? this.options.queryOptions : {}
- if (!('properties' in this.options.queryOptions)) {
- this.options.queryOptions.properties = OverpassFrontend.ALL
- }
- this.options.styleNoBindPopup = this.options.styleNoBindPopup || []
- this.options.stylesNoAutoShow = this.options.stylesNoAutoShow || []
- compileFeature(this.options.feature, twig)
- this.currentRequest = null
- this.lastZoom = null
- this.mainlayer = new Sublayer(this, options)
- this.subLayers = {
- main: this.mainlayer
- }
- if (this.options.members) {
- this.options.queryOptions.properties = OverpassFrontend.TAGS | OverpassFrontend.META | OverpassFrontend.MEMBERS | OverpassFrontend.BBOX
- this.options.queryOptions.memberProperties = OverpassFrontend.ALL
- this.options.queryOptions.members = true
- let memberOptions = {
- id: this.options.id,
- sublayer_id: 'member',
- minZoom: this.options.minZoom,
- maxZoom: this.options.maxZoom,
- feature: this.options.memberFeature,
- styleNoBindPopup: this.options.styleNoBindPopup || [],
- stylesNoAutoShow: this.options.stylesNoAutoShow || [],
- const: this.options.const
- }
- if (this.options.updateAssets) {
- memberOptions.updateAssets = this.options.updateAssets
- }
- compileFeature(memberOptions.feature, twig)
- this.memberlayer = new Memberlayer(this, memberOptions)
- this.subLayers.member = this.memberlayer
- }
- }
- addTo (map) {
- this.map = map
- this.map.on('moveend', this.check_update_map, this)
- for (let k in this.subLayers) {
- this.subLayers[k].addTo(map)
- }
- this.check_update_map()
- this.map.createPane('hover')
- this.map.getPane('hover').style.zIndex = 499
- }
- remove () {
- for (let k in this.subLayers) {
- this.subLayers[k].hideAll(true)
- this.subLayers[k].remove()
- }
- this.abortRequest()
- this.map.off('moveend', this.check_update_map, this)
- this.map = null
- }
- abortRequest () {
- if (this.currentRequest) {
- if (this.onLoadEnd) {
- this.onLoadEnd({
- request: this.currentRequest,
- error: null
- })
- }
- this.currentRequest.abort()
- this.currentRequest = null
- }
- }
- check_update_map () {
- var bounds = new BoundingBox(this.map.getBounds())
- if (this.map.getZoom() < this.options.minZoom ||
- (this.options.maxZoom !== null && this.map.getZoom() > this.options.maxZoom)) {
- for (let k in this.subLayers) {
- this.subLayers[k].hideAll()
- }
- // abort remaining request
- this.abortRequest()
- return
- }
- for (let k in this.subLayers) {
- this.subLayers[k].hideNonVisible(bounds)
- }
- let query = this.options.query
- if (typeof query === 'object') {
- query = query[Object.keys(query).filter(function (x) { return x <= this.map.getZoom() }.bind(this)).reverse()[0]]
- }
- if (query !== this.lastQuery) {
- let filter = new OverpassFrontend.Filter(query)
- this.mainlayer.hideNonVisibleFilter(filter)
- this.lastQuery = query
- }
- // When zoom level changed, update visible objects
- if (this.lastZoom !== this.map.getZoom()) {
- for (let k in this.subLayers) {
- this.subLayers[k].zoomChange()
- }
- this.lastZoom = this.map.getZoom()
- }
- // Abort current requests (in case they are long-lasting - we don't need them
- // anyway). Data which is being submitted will still be loaded to the cache.
- this.abortRequest()
- if (!query) {
- return
- }
- for (let k in this.subLayers) {
- this.subLayers[k].startAdding()
- }
- if (this.options.members) {
- this.options.queryOptions.memberBounds = bounds
- this.options.queryOptions.memberCallback = (err, ob) => {
- if (err) {
- return console.error('unexpected error', err)
- }
- this.memberlayer.add(ob)
- }
- }
- this.currentRequest = this.overpassFrontend.BBoxQuery(query, bounds,
- this.options.queryOptions,
- (err, ob) => {
- if (err) {
- console.log('unexpected error', err)
- }
- this.mainlayer.add(ob)
- },
- function (err) {
- if (this.onLoadEnd) {
- this.onLoadEnd({
- request: this.currentRequest,
- error: err
- })
- }
- for (let k in this.subLayers) {
- this.subLayers[k].finishAdding()
- }
- this.currentRequest = null
- }.bind(this)
- )
- if (this.onLoadStart) {
- this.onLoadStart({
- request: this.currentRequest
- })
- }
- }
- recalc () {
- for (let k in this.subLayers) {
- this.subLayers[k].recalc()
- }
- }
- scheduleReprocess (id) {
- for (let k in this.subLayers) {
- this.subLayers[k].scheduleReprocess(id)
- }
- }
- updateAssets (div, objectData) {
- for (let k in this.subLayers) {
- this.subLayers[k].updateAssets(div, objectData)
- }
- }
- get (id, callback) {
- var done = false
- this.overpassFrontend.get(id,
- {
- properties: OverpassFrontend.ALL
- },
- (err, ob) => {
- if (err === null) {
- callback(err, ob)
- }
- done = true
- },
- (err) => {
- if (!done) {
- callback(err, null)
- }
- }
- )
- }
- show (id, options, callback) {
- let sublayer = this.mainlayer
- if (options.sublayer_id) {
- sublayer = this.subLayers[options.sublayer_id]
- }
- let request = sublayer.show(id, options, callback)
- let result = {
- id: id,
- sublayer_id: options.sublayer_id,
- options: options,
- hide: request.hide
- }
- return result
- }
- hide (id) {
- this.mainlayer.hide(id)
- }
- openPopupOnObject (ob, sublayer = 'main') {
- this.subLayers[sublayer].openPopupOnObject(ob)
- }
- }
- ee(OverpassLayer.prototype)
- // to enable extending twig
- OverpassLayer.twig = twig
- module.exports = OverpassLayer
- },{"./Memberlayer":214,"./OverpassLayer.css":215,"./Sublayer":219,"./compileFeature":221,"boundingbox":20,"event-emitter":41,"html-escape":46,"overpass-frontend":180,"twig":207}],217:[function(require,module,exports){
- var css = "ul.overpass-layer-list {\n margin-top: 0;\n margin-bottom: 0;\n}\nul.overpass-layer-list > li {\n position: relative;\n list-style: none;\n min-height: 30px;\n}\nul.overpass-layer-list > li > .markerParent {\n position: absolute;\n margin-left: -35px;\n width: 30px;\n height: 30px;\n text-align: center;\n display: block;\n color: black;\n text-decoration: none;\n}\n\nul.overpass-layer-list > li > .markerParent > .icon {\n text-align: center;\n position: absolute;\n top: 3px;\n font-size: 15px;\n left: 0;\n right: 0;\n z-index: 1;\n display: inline-block;\n}\nul.overpass-layer-list > li > a.title {\n display: inline-block;\n color: black;\n text-decoration: none;\n}\nul.overpass-layer-list > li > a.title:hover,\nul.overpass-layer-list > li > a.title:active {\n text-decoration: underline;\n}\nul.overpass-layer-list > li > div.description {\n font-style: italic;\n color: #707070;\n float: right;\n text-align: right;\n}\nul.overpass-layer-list > li:after {\n content: '';\n display: table;\n clear: both;\n}\n.hoverable {\n cursor: pointer;\n}\n"; (require("browserify-css").createStyle(css, { "href": "src/OverpassLayerList.css" }, { "insertAt": "bottom" })); module.exports = css;
- },{"browserify-css":22}],218:[function(require,module,exports){
- /* eslint camelcase: 0 */
- require('./OverpassLayerList.css')
- const isTrue = require('./isTrue')
- class OverpassLayerList {
- constructor (layer, options) {
- // compatibility <1.0
- let parentDom
- if (arguments.length > 1 && arguments[1].constructor.name === 'OverpassLayer') {
- parentDom = arguments[0]
- layer = arguments[1]
- console.error('overpass-layer: class OverpassLayerList() accepts only one parameter, "layer"')
- }
- // end
- this.dom = document.createElement('ul')
- this.dom.className = 'overpass-layer-list'
- this.layer = layer
- this.options = options || {}
- this.options.prefix = this.options.prefix || 'list'
- this.layer.on('add', (ob, data) => this.addObject(data))
- this.layer.on('update', (ob, data) => this.updateObject(data))
- this.layer.on('remove', (ob, data) => this.delObject(data))
- this.items = {}
- if (parentDom) {
- this.addTo(parentDom)
- }
- }
- addTo (parentDom) {
- parentDom.appendChild(this.dom)
- }
- _getMarker (ob) {
- var a
- if (ob.data[this.options.prefix + 'MarkerSymbol']) {
- a = document.createElement('div')
- a.className = 'marker'
- a.innerHTML = ob.data[this.options.prefix + 'MarkerSymbol']
- } else if (ob.data.markerSymbol) {
- a = document.createElement('div')
- a.className = 'marker'
- a.innerHTML = ob.data.markerSymbol
- } else if (ob.data.marker && ob.data.marker.iconUrl) {
- a = document.createElement('img')
- a.className = 'marker'
- a.src = ob.data.marker.iconUrl
- }
- return a
- }
- addObject (ob) {
- if (isTrue(ob.data[this.options.prefix + 'Exclude'])) {
- return
- }
- if (ob.id in this.items) { // already added
- return
- }
- var div = document.createElement('li')
- var a
- this.items[ob.id] = div
- ob[this.options.prefix + 'Item'] = div
- // MARKER&ICON PARENT
- var p = document.createElement('a')
- p.className = 'markerParent'
- p.href = 'appUrl' in ob.data ? ob.data.appUrl : '#'
- p.onclick = function (ob) {
- this.layer.openPopupOnObject(ob)
- return false
- }.bind(this, ob)
- div.appendChild(p)
- // MARKER
- a = this._getMarker(ob)
- if (a) {
- p.appendChild(a)
- }
- // ICON
- a = document.createElement('div')
- a.className = 'icon'
- let html = ob.data[this.options.prefix + 'MarkerSign'] || ob.data.markerSign || ''
- a.innerHTML = html
- a.currentHTML = html
- p.appendChild(a)
- // TITLE
- a = document.createElement('a')
- a.className = 'title'
- a.href = 'appUrl' in ob.data ? ob.data.appUrl : '#'
- a.onclick = function (ob) {
- this.layer.openPopupOnObject(ob)
- return false
- }.bind(this, ob)
- html = ob.data[this.options.prefix + 'Title'] || ob.data.title
- a.innerHTML = html
- a.currentHTML = html
- div.appendChild(a)
- let title = a
- // DESCRIPTION
- a = document.createElement('div')
- a.className = 'description'
- html = ob.data[this.options.prefix + 'Description'] || ob.data.description || ''
- a.innerHTML = html
- a.currentHTML = html
- div.appendChild(a)
- div.priority = 'priority' in ob.data ? parseFloat(ob.data.priority) : 0
- var current = this.dom.firstChild
- while (current && current.priority <= div.priority) {
- current = current.nextSibling
- }
- if (current) {
- this.dom.insertBefore(div, current)
- } else {
- this.dom.appendChild(div)
- }
- ob.sublayer.updateAssets(div, ob.data)
- title.onmouseover = function (id, sublayer_id) {
- if (this.currentHover) {
- this.currentHover.hide()
- }
- this.currentHover = this.layer.show(id,
- {
- styles: [ 'hover' ],
- flags: [ 'hover' ],
- sublayer_id
- },
- () => {}
- )
- }.bind(this, ob.id, ob.sublayer_id)
- title.onmouseout = function (id, sublayer_id) {
- if (this.currentHover) {
- this.currentHover.hide()
- }
- this.currentHover = null
- }.bind(this, ob.id, ob.sublayer_id)
- }
- updateObject (ob) {
- var listExclude = isTrue(ob.data[this.options.prefix + 'Exclude'])
- if (!(ob.id in this.items) && !listExclude) {
- return
- }
- if (listExclude) {
- return this.delObject(ob)
- }
- var div = this.items[ob.id]
- var p = div.firstChild
- while (p) {
- if (p.className === 'markerParent') {
- var a = p.firstChild
- while (a) {
- // MARKER
- if (a.className === 'marker') {
- while (p.lastChild) {
- p.removeChild(p.lastChild)
- }
- a = this._getMarker(ob)
- p.appendChild(a)
- }
- // ICON
- a = document.createElement('div')
- a.className = 'icon'
- a.innerHTML = ob.data[this.options.prefix + 'MarkerSign'] || ob.data.markerSign || ''
- p.appendChild(a)
- a = a.nextSibling
- }
- }
- // TITLE
- if (p.className === 'title') {
- let html = ob.data[this.options.prefix + 'Title'] || ob.data.title || ''
- if (p.currentHTML !== html) {
- p.innerHTML = html
- ob.sublayer.updateAssets(div, ob.data)
- }
- }
- // TITLE
- if (p.className === 'description') {
- let html = ob.data[this.options.prefix + 'Description'] || ob.data.description || ''
- if (p.currentHTML !== html) {
- p.innerHTML = html
- ob.sublayer.updateAssets(div, ob.data)
- }
- }
- p = p.nextSibling
- }
- }
- delObject (ob) {
- var div = this.items[ob.id]
- if (div) {
- this.dom.removeChild(div)
- }
- delete this.items[ob.id]
- delete ob[this.options.prefix + 'Item']
- }
- remove () {
- while (this.dom.firstChild) {
- this.dom.removeChild(this.dom.lastChild)
- }
- for (var k in this.items) {
- delete this.items[k][this.options.prefix + 'Item']
- }
- this.items = {}
- }
- }
- module.exports = OverpassLayerList
- },{"./OverpassLayerList.css":217,"./isTrue":222}],219:[function(require,module,exports){
- /* global L */
- const ee = require('event-emitter')
- const OverpassFrontend = require('overpass-frontend')
- const nearestPointOnGeometry = require('nearest-point-on-geometry')
- const BoundingBox = require('boundingbox')
- const styleToLeaflet = require('./styleToLeaflet')
- const strToStyle = require('./strToStyle')
- const SublayerFeature = require('./SublayerFeature')
- // Extensions:
- const decorators = [
- require('./DecoratorPattern')
- ]
- class Sublayer {
- constructor (master, options) {
- this.master = master
- options.sublayer_id = options.sublayer_id || 'main'
- this.options = options
- this.visibleFeatures = {}
- this.shownFeatures = {} // features which are forcibly shown
- this.shownFeatureOptions = {}
- this.lastZoom = null
- this._scheduledReprocesses = {}
- if (!options.feature['style:hover']) {
- options.feature['style:hover'] = {
- color: 'black',
- width: 3,
- opacity: 1,
- radius: 12,
- pane: 'hover'
- }
- }
- if (options.styleNoBindPopup) {
- options.styleNoBindPopup.push('hover')
- } else {
- options.styleNoBindPopup = [ 'hover' ]
- }
- if (options.stylesNoAutoShow) {
- options.stylesNoAutoShow.push('hover')
- } else {
- options.stylesNoAutoShow = [ 'hover' ]
- }
- decorators.forEach(Ext => new Ext(this))
- }
- addTo (map) {
- this.map = map
- this.map.on('popupopen', this._popupOpen.bind(this))
- }
- _popupOpen (e) {
- if (e.popup.sublayer === this) {
- this.updateAssets(e.popup._contentNode)
- }
- }
- domUpdateHooks (node) {
- if (node.getAttribute) {
- let id = node.getAttribute('data-object')
- if (id) {
- let sublayerId = node.getAttribute('data-sublayer') || 'main'
- node.classList.add('hoverable')
- // check if referenced object is loaded - if not, request load
- let ofOptions = {
- properties: OverpassFrontend.ALL
- }
- let subObject = this.master.overpassFrontend.getCached(id, ofOptions)
- if (!subObject) {
- this.master.overpassFrontend.get(id, ofOptions,
- () => {},
- () => {}
- )
- }
- node.onmouseover = () => {
- if (this.currentHover) {
- this.currentHover.hide()
- }
- this.currentHover = this.master.subLayers[sublayerId].show(id, { styles: [ 'hover' ] }, function () {})
- }
- node.onmouseout = () => {
- if (this.currentHover) {
- this.currentHover.hide()
- }
- this.currentHover = null
- }
- node.onclick = () => {
- if (this.currentHover) {
- this.currentHover.hide()
- }
- this.master.subLayers[sublayerId].openPopupOnObject(id)
- }
- }
- }
- let child = node.firstChild
- while (child) {
- this.domUpdateHooks(child)
- child = child.nextSibling
- }
- }
- remove () {
- this.map.off('popupopen', this._popupOpen.bind(this))
- this.map = null
- }
- startAdding () {
- this.currentRequestFeatures = {}
- }
- add (ob) {
- this.currentRequestFeatures[ob.id] = true
- if (!(ob.id in this.visibleFeatures)) {
- var data = new SublayerFeature(ob, this)
- if (ob.id in this.shownFeatures) {
- data = this.shownFeatures[ob.id]
- } else {
- this._processObject(data)
- this._show(data)
- }
- this.visibleFeatures[ob.id] = data
- if (this.master.onAppear) {
- this.master.onAppear(data)
- }
- this.master.emit('add', ob, data)
- this.emit('add', ob, data)
- }
- }
- finishAdding () {
- for (var k in this.visibleFeatures) {
- if (!(k in this.currentRequestFeatures)) {
- if (!(k in this.shownFeatures)) {
- this._hide(this.visibleFeatures[k])
- }
- delete this.visibleFeatures[k]
- }
- }
- }
- hideAll (force) {
- for (let k in this.visibleFeatures) {
- let ob = this.visibleFeatures[k]
- if (force || !(ob.id in this.shownFeatures)) {
- this._hide(ob)
- }
- }
- this.visibleFeatures = {}
- }
- // Hide loaded but non-visible objects
- hideNonVisible (bounds) {
- for (let k in this.visibleFeatures) {
- let ob = this.visibleFeatures[k]
- if (!ob.object.intersects(bounds)) {
- if (!(ob.id in this.shownFeatures)) {
- this._hide(ob)
- }
- delete this.visibleFeatures[k]
- }
- }
- }
- /**
- * Hide all objects which do not satisfy the filter
- * @param {OverpassFrontend.Filter} filter A filter, e.g. new OverpassFrontend.Filter('nwr[amenity=restaurant]')
- */
- hideNonVisibleFilter (filter) {
- for (let k in this.visibleFeatures) {
- let ob = this.visibleFeatures[k]
- if (!filter.match(ob.object)) {
- if (!(ob.id in this.shownFeatures)) {
- this._hide(ob)
- }
- delete this.visibleFeatures[k]
- }
- }
- }
- get (id, options, callback) {
- let isAborted = false
- let isDone = false
- let result = {
- id,
- options,
- abort: () => {
- if (isDone) {
- console.log('abort called, although done')
- return
- }
- isAborted = true
- isDone = true
- if (result.request) {
- result.request.abort()
- }
- }
- }
- if (id in this.visibleFeatures) {
- window.setTimeout(() => {
- isDone = true
- if (!isAborted) {
- callback(null, this.visibleFeatures[id])
- }
- }, 0)
- return result
- }
- if (id in this.shownFeatures) {
- window.setTimeout(() => {
- isDone = true
- if (!isAborted) {
- callback(null, this.shownFeatures[id])
- }
- }, 0)
- return result
- }
- result.request = this.master.get(id, (err, ob) => {
- isDone = true
- if (err) {
- return callback(err)
- }
- if (isAborted) {
- return
- }
- if (ob === null) {
- return console.log('object does not exist', id)
- }
- let data
- if (id in this.visibleFeatures) {
- data = this.visibleFeatures[id]
- } else if (id in this.shownFeatures) {
- data = this.shownFeatures[id]
- } else {
- data = new SublayerFeature(ob, this)
- }
- callback(null, data)
- })
- return result
- }
- show (data, options, callback) {
- let show1 = () => {
- id = data.id
- result.id = id
- this.shownFeatures[id] = data
- if (!(id in this.shownFeatureOptions)) {
- this.shownFeatureOptions[id] = []
- }
- this.shownFeatureOptions[id].push(options)
- data.isShown = true
- data.updateFlags()
- this._processObject(data)
- this._show(data)
- callback(null, data.object, data)
- }
- let id = typeof data === 'string' ? data : data.id
- let isHidden = false
- let result = {
- options,
- hide: () => {
- if (isHidden) {
- console.log('already hidden')
- }
- isHidden = true
- if (result.request) {
- result.request.abort()
- delete result.request
- return
- }
- if (id in this.shownFeatures) {
- var i = this.shownFeatureOptions[id].indexOf(options)
- if (i !== -1) {
- this.shownFeatureOptions[id].splice(i, 1)
- }
- data.updateFlags()
- if (this.shownFeatureOptions[id].length === 0) {
- this.hide(data)
- } else {
- this._processObject(this.shownFeatures[id])
- }
- }
- }
- }
- options.priority = -1
- options.properties = OverpassFrontend.ALL
- if (typeof data === 'string') {
- result.request = this.get(data, options, (err, _data) => {
- delete result.request
- if (isHidden) {
- return
- }
- if (err) {
- callback(err)
- return
- }
- data = _data
- show1()
- })
- } else {
- show1()
- }
- return result
- }
- hide (id) {
- if (typeof id === 'object') {
- id = id.id
- }
- if (id in this.shownFeatures) {
- let data = this.shownFeatures[id]
- delete this.shownFeatures[id]
- delete this.shownFeatureOptions[id]
- if (id in this.visibleFeatures) {
- this._processObject(data)
- } else {
- this._hide(data)
- }
- }
- }
- zoomChange () {
- this.recalc()
- for (let k in this.visibleFeatures) {
- let data = this.visibleFeatures[k]
- this.master.emit('zoomChange', data.object, data)
- this.emit('zoomChange', data.object, data)
- if (this.master.onZoomChange) {
- this.master.onZoomChange(data)
- }
- }
- this.lastZoom = this.map.getZoom()
- }
- recalc () {
- for (var k in this.visibleFeatures) {
- this._processObject(this.visibleFeatures[k])
- }
- }
- _processObject (data) {
- var k
- var ob = data.object
- var showOptions = {
- styles: []
- }
- if (ob.id in this.shownFeatureOptions) {
- this.shownFeatureOptions[ob.id].forEach(function (opt) {
- if ('styles' in opt) {
- showOptions.styles = showOptions.styles.concat(opt.styles)
- }
- })
- }
- var objectData = this.evaluate(data)
- if (!data.feature) {
- data.feature = ob.leafletFeature({
- weight: 0,
- opacity: 0,
- fillOpacity: 0,
- radius: 0
- })
- }
- for (k in objectData) {
- var m = k.match(/^style(|:(.*))$/)
- if (m) {
- var styleId = typeof m[2] === 'undefined' ? 'default' : m[2]
- var style = styleToLeaflet(objectData[k])
- if (data.features[styleId]) {
- data.features[styleId].setStyle(style)
- } else {
- data.features[styleId] = ob.leafletFeature(style)
- }
- if ('text' in style && 'setText' in data.features[styleId]) {
- data.features[styleId].setText(null)
- data.features[styleId].setText(style.text, {
- repeat: style.textRepeat,
- offset: style.textOffset,
- below: style.textBelow,
- attributes: {
- 'fill': style.textFill,
- 'fill-opacity': style.textFillOpacity,
- 'font-weight': style.textFontWeight,
- 'font-size': style.textFontSize,
- 'letter-spacing': style.textLetterSpacing
- }
- })
- }
- if ('offset' in style && 'setOffset' in data.features[styleId]) {
- data.features[styleId].setOffset(style.offset)
- }
- }
- }
- if ('styles' in showOptions) {
- objectData.styles = objectData.styles.concat(showOptions.styles)
- }
- objectData.marker = {
- html: '',
- iconAnchor: [ 0, 0 ],
- iconSize: [ 0, 0 ],
- signAnchor: [ 0, 0 ],
- popupAnchor: [ 0, 0 ]
- }
- if (objectData.markerSymbol) {
- objectData.marker.html += objectData.markerSymbol
- var div = document.createElement('div')
- div.innerHTML = objectData.markerSymbol
- if (div.firstChild) {
- var c = div.firstChild
- objectData.marker.iconSize = [ c.offsetWidth, c.offsetHeight ]
- if (c.hasAttribute('width')) {
- objectData.marker.iconSize[0] = parseFloat(c.getAttribute('width'))
- }
- if (c.hasAttribute('height')) {
- objectData.marker.iconSize[1] = parseFloat(c.getAttribute('height'))
- }
- objectData.marker.iconAnchor = [ objectData.marker.iconSize[0] / 2, objectData.marker.iconSize[1] / 2 ]
- if (c.hasAttribute('anchorx')) {
- objectData.marker.iconAnchor[0] = parseFloat(c.getAttribute('anchorx'))
- }
- if (c.hasAttribute('anchory')) {
- objectData.marker.iconAnchor[1] = parseFloat(c.getAttribute('anchory'))
- }
- if (c.hasAttribute('signanchorx')) {
- objectData.marker.signAnchor[0] = parseFloat(c.getAttribute('signanchorx'))
- }
- if (c.hasAttribute('signanchory')) {
- objectData.marker.signAnchor[1] = parseFloat(c.getAttribute('signanchory'))
- }
- if (c.hasAttribute('popupanchory')) {
- objectData.marker.popupAnchor[0] = parseFloat(c.getAttribute('popupanchorx'))
- }
- if (c.hasAttribute('popupanchory')) {
- objectData.marker.popupAnchor[1] = parseFloat(c.getAttribute('popupanchory'))
- }
- }
- this.updateAssets(div, objectData)
- }
- if (objectData.markerSign) {
- let x = objectData.marker.iconAnchor[0] + objectData.marker.signAnchor[0]
- let y = -objectData.marker.iconSize[1] + objectData.marker.iconAnchor[1] + objectData.marker.signAnchor[1]
- objectData.marker.html += '<div class="sign" style="margin-left: ' + x + 'px; margin-top: ' + y + 'px;">' + objectData.markerSign + '</div>'
- }
- if (objectData.marker.html) {
- objectData.marker.className = 'overpass-layer-icon'
- var icon = L.divIcon(objectData.marker)
- if (data.featureMarker) {
- data.featureMarker.setIcon(icon)
- if (data.featureMarker._icon) {
- this.updateAssets(data.featureMarker._icon, objectData)
- }
- } else {
- data.featureMarker = L.marker(ob.center, { icon: icon })
- }
- }
- if (data.isShown) {
- for (k in data.features) {
- data.feature.addTo(this.map)
- if (objectData.styles && objectData.styles.indexOf(k) !== -1 && data.styles && data.styles.indexOf(k) === -1) {
- data.features[k].addTo(this.map)
- }
- if (objectData.styles && objectData.styles.indexOf(k) === -1 && data.styles && data.styles.indexOf(k) !== -1) {
- this.map.removeLayer(data.features[k])
- }
- }
- }
- data.styles = objectData.styles
- var popupContent = ''
- popupContent += '<h1>' + objectData.title + '</h1>'
- var popupDescription = objectData.popupDescription || objectData.description
- if (popupDescription) {
- popupContent += '<div class="description">' + popupDescription + '</div>'
- }
- if (objectData.body) {
- popupContent += '<div class="body">' + objectData.body + '</div>'
- }
- if (data.popup) {
- if (data.popup._contentNode) {
- if (data.popup.currentHTML !== popupContent) {
- data.popup._contentNode.innerHTML = popupContent
- this.updateAssets(data.popup._contentNode, objectData)
- }
- } else {
- data.popup.setContent(popupContent)
- }
- data.popup.currentHTML = popupContent
- } else {
- data.popup = L.popup().setContent(popupContent)
- data.popup.object = data
- data.popup.sublayer = this
- data.feature.bindPopup(data.popup)
- for (k in data.features) {
- if (this._shallBindPopupToStyle(k)) {
- data.features[k].bindPopup(data.popup)
- }
- }
- if (data.featureMarker) {
- data.featureMarker.bindPopup(data.popup)
- }
- }
- data.id = ob.id
- data.layer_id = this.options.id
- data.sublayer_id = this.options.sublayer_id
- data.data = objectData
- if (this.master.onUpdate) {
- this.master.onUpdate(data)
- }
- this.master.emit('update', data.object, data)
- this.emit('update', data.object, data)
- }
- evaluate (data) {
- var k
- var ob = data.object
- data.twigData = this.twigData(ob, data)
- var objectData = {}
- for (k in this.options.feature) {
- if (typeof this.options.feature[k] === 'function') {
- objectData[k] = this.options.feature[k](data.twigData)
- } else {
- objectData[k] = this.options.feature[k]
- }
- }
- var styleIds = []
- for (k in objectData) {
- var m = k.match(/^style(|:(.*))$/)
- if (m) {
- var style = objectData[k]
- var styleId = typeof m[2] === 'undefined' ? 'default' : m[2]
- if (typeof style === 'string' || 'twig_markup' in style) {
- objectData[k] = strToStyle(style)
- }
- if (this.options.stylesNoAutoShow.indexOf(styleId) === -1) {
- styleIds.push(styleId)
- }
- }
- }
- if (!('features' in data)) {
- data.features = {}
- }
- objectData.styles =
- 'styles' in objectData ? objectData.styles
- : 'styles' in this.options ? this.options.styles
- : styleIds
- if (typeof objectData.styles === 'string' || 'twig_markup' in objectData.styles) {
- var styles = objectData.styles.trim()
- if (styles === '') {
- objectData.styles = []
- } else {
- objectData.styles = styles.split(/,/)
- }
- }
- return objectData
- }
- twigData (ob, data) {
- var result = {
- id: ob.id,
- sublayer_id: this.options.sublayer_id,
- osm_id: ob.osm_id,
- type: ob.type,
- tags: ob.tags,
- meta: ob.meta,
- flags: data.flags,
- members: [],
- 'const': this.options.const
- }
- if (ob.memberFeatures) {
- ob.memberFeatures.forEach((member, sequence) => {
- let r = {
- id: member.id,
- sequence,
- type: member.type,
- osm_id: member.osm_id,
- role: ob.members[sequence].role,
- tags: member.tags,
- meta: member.meta,
- dir: member.dir,
- connectedPrev: member.connectedPrev,
- connectedNext: member.connectedNext
- }
- result.members.push(r)
- })
- }
- if (this.map) {
- result.map = {
- zoom: this.map.getZoom()
- }
- }
- this.emit('twigData', ob, data, result)
- this.master.emit('twigData', ob, data, result)
- return result
- }
- _shallBindPopupToStyle (styleId) {
- return this.options.styleNoBindPopup.indexOf(styleId) === -1
- }
- _show (data) {
- if (!this.map) {
- return
- }
- data.feature.addTo(this.map)
- for (var i = 0; i < data.styles.length; i++) {
- var k = data.styles[i]
- if (k in data.features) {
- data.features[k].addTo(this.map)
- }
- }
- if (data.featureMarker) {
- data.featureMarker.addTo(this.map)
- this.updateAssets(data.featureMarker._icon, data)
- }
- data.object.on('update', this.scheduleReprocess.bind(this, data.id))
- data.isShown = true
- }
- _hide (data) {
- this.master.emit('remove', data.object, data)
- this.emit('remove', data.object, data)
- this.map.removeLayer(data.feature)
- for (var k in data.features) {
- this.map.removeLayer(data.features[k])
- }
- if (data.featureMarker) {
- this.map.removeLayer(data.featureMarker)
- }
- if (this.master.onDisappear) {
- this.master.onDisappear(data)
- }
- data.object.off('update', this.scheduleReprocess.bind(this, data.id))
- data.isShown = false
- }
- scheduleReprocess (id) {
- if (!(id in this._scheduledReprocesses)) {
- this._scheduledReprocesses[id] = window.setTimeout(() => {
- delete this._scheduledReprocesses[id]
- if (id in this.visibleFeatures) {
- this._processObject(this.visibleFeatures[id])
- }
- }, 0)
- }
- }
- updateAssets (div, objectData) {
- this.domUpdateHooks(div)
- if (this.options.updateAssets) {
- this.options.updateAssets(div, objectData, this)
- }
- }
- openPopupOnObject (ob, options) {
- if (typeof ob === 'string') {
- return this.get(ob, options, (err, ob) => {
- if (err) {
- return console.log(err)
- }
- this._processObject(ob)
- this._show(ob)
- this.openPopupOnObject(ob, options)
- })
- }
- // When object is quite smaller than current view, show popup on feature
- let viewBounds = new BoundingBox(this.map.getBounds())
- let obBounds = new BoundingBox(ob.object.bounds)
- if (obBounds.diagonalLength() * 0.75 < viewBounds.diagonalLength()) {
- return ob.feature.openPopup()
- }
- // otherwise, try to find point on geometry closest to center of view
- let pt = this.map.getCenter()
- let geom = ob.object.GeoJSON()
- let pos = nearestPointOnGeometry(geom, { type: 'Feature', geometry: { type: 'Point', coordinates: [ pt.lng, pt.lat ] } })
- if (pos) {
- pos = pos.geometry.coordinates
- return ob.feature.openPopup([pos[1], pos[0]])
- }
- // no point found? use normal object popup open then ...
- ob.feature.openPopup()
- }
- }
- ee(Sublayer.prototype)
- module.exports = Sublayer
- },{"./DecoratorPattern":213,"./SublayerFeature":220,"./strToStyle":223,"./styleToLeaflet":224,"boundingbox":20,"event-emitter":41,"nearest-point-on-geometry":174,"overpass-frontend":180}],220:[function(require,module,exports){
- class SublayerFeature {
- constructor (object, sublayer) {
- this.object = object
- this.id = object.id
- this.sublayer = sublayer
- this.isShown = false
- this.flags = {}
- }
- updateFlags () {
- let shownFeatureOptions = this.sublayer.shownFeatureOptions[this.id]
- this.flags = {}
- shownFeatureOptions.forEach(options => {
- if (options.flags) {
- options.flags.forEach(flag => {
- this.flags[flag] = true
- })
- }
- })
- }
- }
- module.exports = SublayerFeature
- },{}],221:[function(require,module,exports){
- function compileFeature (feature, twig) {
- for (var k in feature) {
- if (typeof feature[k] === 'string' && feature[k].search('{') !== -1) {
- let template
- try {
- template = twig.twig({ data: feature[k], autoescape: true })
- } catch (err) {
- console.log('Error compiling twig template ' + this.id + '/' + k + ':', err)
- break
- }
- feature[k] = function (template, k, ob) {
- try {
- return template.render(ob)
- } catch (err) {
- console.log('Error rendering twig template ' + this.id + '/' + k + ': ', err)
- }
- return null
- }.bind(this, template, k)
- } else if (typeof feature[k] === 'object' && (['style'].indexOf(k) !== -1 || k.match(/^style:/))) {
- var templates = {}
- for (var k1 in feature[k]) {
- if (typeof feature[k][k1] === 'string' && feature[k][k1].search('{') !== -1) {
- templates[k1] = twig.twig({ data: feature[k][k1], autoescape: true })
- } else {
- templates[k1] = feature[k][k1]
- }
- }
- feature[k] = function (templates, ob) {
- var ret = {}
- for (var k1 in templates) {
- if (typeof templates[k1] === 'object' && templates[k1] !== null && 'render' in templates[k1]) {
- ret[k1] = templates[k1].render(ob)
- } else {
- ret[k1] = templates[k1]
- }
- }
- return ret
- }.bind(this, templates)
- }
- }
- return feature
- }
- module.exports = compileFeature
- },{}],222:[function(require,module,exports){
- function isTrue (value) {
- if (value === null || typeof value === 'undefined') {
- return false
- }
- if (typeof value === 'boolean') {
- return value
- }
- if ((typeof value === 'string') ||
- (typeof value === 'object' && 'twig_markup' in value)) {
- if (value.trim() === 'false') {
- return false
- }
- if (value.trim() === 'true') {
- return true
- }
- }
- if (value === 0 || value.toString() === '0' || value.toString() === '') {
- return false
- }
- return true
- }
- window.isTrue = isTrue
- module.exports = isTrue
- },{}],223:[function(require,module,exports){
- function strToStyle (style) {
- var str = style.split('\n')
- style = {}
- for (var i = 0; i < str.length; i++) {
- var m
- if ((m = str[i].match(/^\s*([a-zA-Z0-9_]+)\s*:\s*(.*)\s*$/))) {
- var v = m[2].trim()
- if (v.match(/^-?[0-9]+(\.[0-9]+)?/)) {
- v = parseFloat(v)
- }
- style[m[1]] = v
- }
- }
- return style
- }
- module.exports = strToStyle
- },{}],224:[function(require,module,exports){
- const isTrue = require('./isTrue')
- const transforms = {
- stroke: {
- type: 'boolean'
- },
- fill: {
- type: 'boolean'
- },
- textRepeat: {
- type: 'boolean'
- },
- textBelow: {
- type: 'boolean'
- },
- noClip: {
- type: 'boolean'
- },
- width: {
- rename: 'weight',
- type: 'float'
- },
- opacity: {
- type: 'float'
- },
- fillOpacity: {
- type: 'float'
- }
- }
- function styleToLeaflet (style) {
- let ret = JSON.parse(JSON.stringify(style))
- for (let k in ret) {
- let value = ret[k]
- if (k in transforms) {
- let transform = transforms[k]
- switch (transform.type) {
- case 'boolean':
- value = isTrue(ret[k])
- break
- case 'float':
- value = parseFloat(ret[k])
- break
- }
- if (transform.rename) {
- delete ret[k]
- k = transform.rename
- }
- }
- ret[k] = value
- }
- return ret
- }
- module.exports = styleToLeaflet
- },{"./isTrue":222}]},{},[1]);
|