forked from mWater/minimongo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimongo.min.js
More file actions
37 lines (37 loc) · 224 KB
/
Copy pathminimongo.min.js
File metadata and controls
37 lines (37 loc) · 224 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{configurable:false,enumerable:true,get:getter})}};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s=18)})([function(module,exports,__webpack_require__){var async,booleanCrosses,booleanPointInPolygon,booleanWithin,bowser,compileDocumentSelector,compileSort,deg2rad,getDistanceFromLatLngInM,intersect,isLocalStorageSupported,pointInPolygon,polygonIntersection,processGeoIntersectsOperator,processNearOperator,_;_=__webpack_require__(1);async=__webpack_require__(5);bowser=__webpack_require__(22);compileDocumentSelector=__webpack_require__(2).compileDocumentSelector;compileSort=__webpack_require__(2).compileSort;booleanPointInPolygon=__webpack_require__(9)["default"];intersect=__webpack_require__(24)["default"];booleanCrosses=__webpack_require__(26)["default"];booleanWithin=__webpack_require__(33)["default"];isLocalStorageSupported=function(){var e;if(!window.localStorage){return false}try{window.localStorage.setItem("test","test");window.localStorage.removeItem("test");return true}catch(_error){e=_error;return false}};exports.compileDocumentSelector=compileDocumentSelector;exports.autoselectLocalDb=function(options,success,error){var IndexedDb,LocalStorageDb,MemoryDb,WebSQLDb,browser,_ref;IndexedDb=__webpack_require__(12);WebSQLDb=__webpack_require__(13);LocalStorageDb=__webpack_require__(14);MemoryDb=__webpack_require__(10);browser=bowser.browser;if(!isLocalStorageSupported()){return new MemoryDb(options,success)}if(window.cordova){if(((_ref=window.device)!=null?_ref.platform:void 0)==="iOS"&&window.sqlitePlugin){console.log("Selecting WebSQLDb(sqlite) for Cordova");options.storage="sqlite";return new WebSQLDb(options,success,error)}else{console.log("Selecting else WebSQLDb for Cordova");return new WebSQLDb(options,success,error)}}if(browser.android||browser.ios||browser.chrome||browser.safari||browser.opera||browser.blackberry){console.log("Selecting WebSQLDb for browser");return new WebSQLDb(options,success,function(_this){return function(err){console.log("Failed to create WebSQLDb: "+(err?err.message:void 0));return new IndexedDb(options,success,function(err){console.log("Failed to create IndexedDb: "+(err?err.message:void 0));return new MemoryDb(options,success)})}}(this))}if(browser.firefox&&browser.version>=16){console.log("Selecting IndexedDb for browser");return new IndexedDb(options,success,function(_this){return function(err){console.log("Failed to create IndexedDb: "+(err?err.message:void 0));return new MemoryDb(options,success)}}(this))}console.log("Selecting LocalStorageDb for fallback");return new LocalStorageDb(options,success,error)};exports.migrateLocalDb=function(fromDb,toDb,success,error){var HybridDb,col,hybridDb,name,_ref;HybridDb=__webpack_require__(15);hybridDb=new HybridDb(fromDb,toDb);_ref=fromDb.collections;for(name in _ref){col=_ref[name];if(toDb[name]){hybridDb.addCollection(name)}}return hybridDb.upload(success,error)};exports.cloneLocalDb=function(fromDb,toDb,success,error){var col,name,_ref;_ref=fromDb.collections;for(name in _ref){col=_ref[name];if(!toDb[name]){toDb.addCollection(name)}}return async.each(_.values(fromDb.collections),function(_this){return function(fromCol,cb){var toCol;toCol=toDb[fromCol.name];return fromCol.find({}).fetch(function(items){return toCol.seed(items,function(){return fromCol.pendingUpserts(function(upserts){return toCol.upsert(_.pluck(upserts,"doc"),_.pluck(upserts,"base"),function(){return fromCol.pendingRemoves(function(removes){return async.eachSeries(removes,function(remove,cb2){return toCol.remove(remove,function(){return cb2()},cb2)},cb)},cb)},cb)},cb)},cb)},cb)}}(this),function(_this){return function(err){if(err){return error(err)}return success()}}(this))};exports.cloneLocalCollection=function(fromCol,toCol,success,error){return fromCol.find({}).fetch(function(_this){return function(items){return toCol.seed(items,function(){return fromCol.pendingUpserts(function(upserts){return toCol.upsert(_.pluck(upserts,"doc"),_.pluck(upserts,"base"),function(){return fromCol.pendingRemoves(function(removes){return async.eachSeries(removes,function(remove,cb2){return toCol.remove(remove,function(){return cb2()},cb2)},function(err){if(err){return error(err)}return success()})},error)},error)},error)},error)}}(this),error)};exports.processFind=function(items,selector,options){var filtered;filtered=_.filter(items,compileDocumentSelector(selector));filtered=processNearOperator(selector,filtered);filtered=processGeoIntersectsOperator(selector,filtered);if(options&&options.sort){filtered.sort(compileSort(options.sort))}if(options&&options.skip){filtered=_.slice(filtered,options.skip)}if(options&&options.limit){filtered=_.take(filtered,options.limit)}if(options&&options.fields){filtered=exports.filterFields(filtered,options.fields)}return filtered};exports.filterFields=function(items,fields){if(fields==null){fields={}}if(_.keys(fields).length===0){return items}return _.map(items,function(item){var field,from,newItem,obj,path,pathElem,to,_i,_j,_k,_l,_len,_len1,_len2,_len3,_len4,_m,_ref,_ref1,_ref2,_ref3;newItem={};if(_.first(_.values(fields))===1){_ref=_.keys(fields).concat(["_id"]);for(_i=0,_len=_ref.length;_i<_len;_i++){field=_ref[_i];path=field.split(".");obj=item;for(_j=0,_len1=path.length;_j<_len1;_j++){pathElem=path[_j];if(obj){obj=obj[pathElem]}}if(obj==null){continue}from=item;to=newItem;_ref1=_.initial(path);for(_k=0,_len2=_ref1.length;_k<_len2;_k++){pathElem=_ref1[_k];to[pathElem]=to[pathElem]||{};to=to[pathElem];from=from[pathElem]}to[_.last(path)]=from[_.last(path)]}return newItem}else{item=_.cloneDeep(item);_ref2=_.keys(fields);for(_l=0,_len3=_ref2.length;_l<_len3;_l++){field=_ref2[_l];path=field.split(".");obj=item;_ref3=_.initial(path);for(_m=0,_len4=_ref3.length;_m<_len4;_m++){pathElem=_ref3[_m];if(obj){obj=obj[pathElem]}}if(obj==null){continue}delete obj[_.last(path)]}return item}})};exports.createUid=function(){return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(c){var r,v;r=Math.random()*16|0;v=c==="x"?r:r&3|8;return v.toString(16)})};processNearOperator=function(selector,list){var distances,geo,key,value;for(key in selector){value=selector[key];if(value!=null&&value["$near"]){geo=value["$near"]["$geometry"];if(geo.type!=="Point"){break}list=_.filter(list,function(doc){return doc[key]&&doc[key].type==="Point"});distances=_.map(list,function(doc){return{doc:doc,distance:getDistanceFromLatLngInM(geo.coordinates[1],geo.coordinates[0],doc[key].coordinates[1],doc[key].coordinates[0])}});distances=_.filter(distances,function(item){return item.distance>=0});distances=_.sortBy(distances,"distance");if(value["$near"]["$maxDistance"]){distances=_.filter(distances,function(item){return item.distance<=value["$near"]["$maxDistance"]})}list=_.pluck(distances,"doc")}}return list};pointInPolygon=function(point,polygon){return booleanPointInPolygon(point,polygon)};polygonIntersection=function(polygon1,polygon2){return intersect(polygon1,polygon2)!=null};getDistanceFromLatLngInM=function(lat1,lng1,lat2,lng2){var R,a,c,d,dLat,dLng;R=6370986;dLat=deg2rad(lat2-lat1);dLng=deg2rad(lng2-lng1);a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(deg2rad(lat1))*Math.cos(deg2rad(lat2))*Math.sin(dLng/2)*Math.sin(dLng/2);c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));d=R*c;return d};deg2rad=function(deg){return deg*(Math.PI/180)};processGeoIntersectsOperator=function(selector,list){var geo,key,value;for(key in selector){value=selector[key];if(value!=null&&value["$geoIntersects"]){geo=value["$geoIntersects"]["$geometry"];if(geo.type!=="Polygon"){break}list=_.filter(list,function(doc){var line,lineGeo,_i,_len,_ref,_ref1;if(!doc[key]){return false}if(doc[key].type==="Point"){return pointInPolygon(doc[key],geo)}else if((_ref=doc[key].type)==="Polygon"||_ref==="MultiPolygon"){return polygonIntersection(doc[key],geo)}else if(doc[key].type==="LineString"){return booleanCrosses(doc[key],geo)||booleanWithin(doc[key],geo)}else if(doc[key].type==="MultiLineString"){_ref1=doc[key].coordinates;for(_i=0,_len=_ref1.length;_i<_len;_i++){line=_ref1[_i];lineGeo={type:"LineString",coordinates:line};if(booleanCrosses(lineGeo,geo)||booleanWithin(lineGeo,geo)){return true}}return false}})}}return list};exports.regularizeUpsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;if(_.isFunction(bases)){_ref=[void 0,bases,success],bases=_ref[0],success=_ref[1],error=_ref[2]}if(!_.isArray(docs)){docs=[docs];bases=[bases]}else{bases=bases||[]}items=_.map(docs,function(doc,i){return{doc:doc,base:i<bases.length?bases[i]:void 0}});for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(!item.doc._id){item.doc._id=exports.createUid()}if(item.base&&!item.base._id){throw new Error("Base needs _id")}if(item.base&&item.base._id!==item.doc._id){throw new Error("Base needs same _id")}}return[items,success,error]}},function(module,exports){module.exports=_},function(module,exports,__webpack_require__){LocalCollection={};EJSON=__webpack_require__(23);var _=__webpack_require__(1);var isArray=function(x){return _.isArray(x)&&!EJSON.isBinary(x)};var _anyIfArray=function(x,f){if(isArray(x))return _.any(x,f);return f(x)};var _anyIfArrayPlus=function(x,f){if(f(x))return true;return isArray(x)&&_.any(x,f)};var hasOperators=function(valueSelector){var theseAreOperators=undefined;for(var selKey in valueSelector){var thisIsOperator=selKey.substr(0,1)==="$";if(theseAreOperators===undefined){theseAreOperators=thisIsOperator}else if(theseAreOperators!==thisIsOperator){throw new Error("Inconsistent selector: "+valueSelector)}}return!!theseAreOperators};var compileValueSelector=function(valueSelector){if(valueSelector==null){return function(value){return _anyIfArray(value,function(x){return x==null})}}if(!_.isObject(valueSelector)){return function(value){return _anyIfArray(value,function(x){return x===valueSelector})}}if(valueSelector instanceof RegExp){return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return valueSelector.test(x)})}}if(isArray(valueSelector)){return function(value){if(!isArray(value))return false;return _anyIfArrayPlus(value,function(x){return LocalCollection._f._equal(valueSelector,x)})}}if(hasOperators(valueSelector)){var operatorFunctions=[];_.each(valueSelector,function(operand,operator){if(!_.has(VALUE_OPERATORS,operator))throw new Error("Unrecognized operator: "+operator);operatorFunctions.push(VALUE_OPERATORS[operator](operand,valueSelector.$options))});return function(value){return _.all(operatorFunctions,function(f){return f(value)})}}return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._equal(valueSelector,x)})}};var LOGICAL_OPERATORS={$and:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.all(subSelectorFunctions,function(f){return f(doc)})}},$or:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.any(subSelectorFunctions,function(f){return f(doc)})}},$nor:function(subSelector){if(!isArray(subSelector)||_.isEmpty(subSelector))throw Error("$and/$or/$nor must be nonempty array");var subSelectorFunctions=_.map(subSelector,compileDocumentSelector);return function(doc){return _.all(subSelectorFunctions,function(f){return!f(doc)})}},$where:function(selectorValue){if(!(selectorValue instanceof Function)){selectorValue=Function("return "+selectorValue)}return function(doc){return selectorValue.call(doc)}}};var VALUE_OPERATORS={$in:function(operand){if(!isArray(operand))throw new Error("Argument to $in must be array");var index=null;if(_.all(operand,_.isString))index=_.indexBy(operand);return function(value){return _anyIfArrayPlus(value,function(x){if(_.isString(x)&&index!==null)return index[x]!=undefined;return _.any(operand,function(operandElt){return LocalCollection._f._equal(operandElt,x)})})}},$all:function(operand){if(!isArray(operand))throw new Error("Argument to $all must be array");return function(value){if(!isArray(value))return false;return _.all(operand,function(operandElt){return _.any(value,function(valueElt){return LocalCollection._f._equal(operandElt,valueElt)})})}},$lt:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)<0})}},$lte:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)<=0})}},$gt:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)>0})}},$gte:function(operand){return function(value){return _anyIfArray(value,function(x){return LocalCollection._f._cmp(x,operand)>=0})}},$ne:function(operand){return function(value){return!_anyIfArrayPlus(value,function(x){return LocalCollection._f._equal(x,operand)})}},$nin:function(operand){if(!isArray(operand))throw new Error("Argument to $nin must be array");var inFunction=VALUE_OPERATORS.$in(operand);return function(value){if(value===undefined)return true;return!inFunction(value)}},$exists:function(operand){return function(value){return operand===(value!==undefined)}},$mod:function(operand){var divisor=operand[0],remainder=operand[1];return function(value){return _anyIfArray(value,function(x){return x%divisor===remainder})}},$size:function(operand){return function(value){return isArray(value)&&operand===value.length}},$type:function(operand){return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return LocalCollection._f._type(x)===operand})}},$regex:function(operand,options){if(options!==undefined){if(/[^gim]/.test(options))throw new Error("Only the i, m, and g regexp options are supported");var regexSource=operand instanceof RegExp?operand.source:operand;operand=new RegExp(regexSource,options)}else if(!(operand instanceof RegExp)){operand=new RegExp(operand)}return function(value){if(value===undefined)return false;return _anyIfArray(value,function(x){return operand.test(x)})}},$options:function(operand){return function(value){return true}},$elemMatch:function(operand){var matcher=compileDocumentSelector(operand);return function(value){if(!isArray(value))return false;return _.any(value,function(x){return matcher(x)})}},$not:function(operand){var matcher=compileValueSelector(operand);return function(value){return!matcher(value)}},$near:function(operand){return function(value){return true}},$geoIntersects:function(operand){return function(value){return true}}};LocalCollection._f={_type:function(v){if(typeof v==="number")return 1;if(typeof v==="string")return 2;if(typeof v==="boolean")return 8;if(isArray(v))return 4;if(v===null)return 10;if(v instanceof RegExp)return 11;if(typeof v==="function")return 13;if(v instanceof Date)return 9;if(EJSON.isBinary(v))return 5;if(v instanceof Meteor.Collection.ObjectID)return 7;return 3},_equal:function(a,b){return EJSON.equals(a,b,{keyOrderSensitive:true})},_typeorder:function(t){return[-1,1,2,3,4,5,-1,6,7,8,0,9,-1,100,2,100,1,8,1][t]},_cmp:function(a,b){if(a===undefined)return b===undefined?0:-1;if(b===undefined)return 1;var ta=LocalCollection._f._type(a);var tb=LocalCollection._f._type(b);var oa=LocalCollection._f._typeorder(ta);var ob=LocalCollection._f._typeorder(tb);if(oa!==ob)return oa<ob?-1:1;if(ta!==tb)throw Error("Missing type coercion logic in _cmp");if(ta===7){ta=tb=2;a=a.toHexString();b=b.toHexString()}if(ta===9){ta=tb=1;a=a.getTime();b=b.getTime()}if(ta===1)return a-b;if(tb===2)return a<b?-1:a===b?0:1;if(ta===3){var to_array=function(obj){var ret=[];for(var key in obj){ret.push(key);ret.push(obj[key])}return ret};return LocalCollection._f._cmp(to_array(a),to_array(b))}if(ta===4){for(var i=0;;i++){if(i===a.length)return i===b.length?0:-1;if(i===b.length)return 1;var s=LocalCollection._f._cmp(a[i],b[i]);if(s!==0)return s}}if(ta===5){if(a.length!==b.length)return a.length-b.length;for(i=0;i<a.length;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return 1}return 0}if(ta===8){if(a)return b?0:1;return b?-1:0}if(ta===10)return 0;if(ta===11)throw Error("Sorting not supported on regular expression");if(ta===13)throw Error("Sorting not supported on Javascript code");throw Error("Unknown type to sort")}};LocalCollection._matches=function(selector,doc){return LocalCollection._compileSelector(selector)(doc)};LocalCollection._makeLookupFunction=function(key){var dotLocation=key.indexOf(".");var first,lookupRest,nextIsNumeric;if(dotLocation===-1){first=key}else{first=key.substr(0,dotLocation);var rest=key.substr(dotLocation+1);lookupRest=LocalCollection._makeLookupFunction(rest);nextIsNumeric=/^\d+(\.|$)/.test(rest)}return function(doc){if(doc==null)return[undefined];var firstLevel=doc[first];if(!lookupRest)return[firstLevel];if(isArray(firstLevel)&&firstLevel.length===0)return[undefined];if(!isArray(firstLevel)||nextIsNumeric)firstLevel=[firstLevel];return Array.prototype.concat.apply([],_.map(firstLevel,lookupRest))}};var compileDocumentSelector=function(docSelector){var perKeySelectors=[];_.each(docSelector,function(subSelector,key){if(key.substr(0,1)==="$"){if(!_.has(LOGICAL_OPERATORS,key))throw new Error("Unrecognized logical operator: "+key);perKeySelectors.push(LOGICAL_OPERATORS[key](subSelector))}else{var lookUpByIndex=LocalCollection._makeLookupFunction(key);var valueSelectorFunc=compileValueSelector(subSelector);perKeySelectors.push(function(doc){var branchValues=lookUpByIndex(doc);return _.any(branchValues,valueSelectorFunc)})}});return function(doc){return _.all(perKeySelectors,function(f){return f(doc)})}};LocalCollection._compileSelector=function(selector){if(selector instanceof Function)return function(doc){return selector.call(doc)};if(LocalCollection._selectorIsId(selector)){return function(doc){return EJSON.equals(doc._id,selector)}}if(!selector||"_id"in selector&&!selector._id)return function(doc){return false};if(typeof selector==="boolean"||isArray(selector)||EJSON.isBinary(selector))throw new Error("Invalid selector: "+selector);return compileDocumentSelector(selector)};LocalCollection._compileSort=function(spec){var sortSpecParts=[];if(spec instanceof Array){for(var i=0;i<spec.length;i++){if(typeof spec[i]==="string"){sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(spec[i]),ascending:true})}else{sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(spec[i][0]),ascending:spec[i][1]!=="desc"})}}}else if(typeof spec==="object"){for(var key in spec){sortSpecParts.push({lookup:LocalCollection._makeLookupFunction(key),ascending:spec[key]>=0})}}else{throw Error("Bad sort specification: ",JSON.stringify(spec))}if(sortSpecParts.length===0)return function(){return 0};var reduceValue=function(branchValues,findMin){var reduced;var first=true;_.each(branchValues,function(branchValue){if(!isArray(branchValue))branchValue=[branchValue];if(isArray(branchValue)&&branchValue.length===0)branchValue=[undefined];_.each(branchValue,function(value){if(first){reduced=value;first=false}else{var cmp=LocalCollection._f._cmp(reduced,value);if(findMin&&cmp>0||!findMin&&cmp<0)reduced=value}})});return reduced};return function(a,b){for(var i=0;i<sortSpecParts.length;++i){var specPart=sortSpecParts[i];var aValue=reduceValue(specPart.lookup(a),specPart.ascending);var bValue=reduceValue(specPart.lookup(b),specPart.ascending);var compare=LocalCollection._f._cmp(aValue,bValue);if(compare!==0)return specPart.ascending?compare:-compare}return 0}};exports.compileDocumentSelector=compileDocumentSelector;exports.compileSort=LocalCollection._compileSort},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var helpers_1=__webpack_require__(4);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;function getCoords(coords){if(Array.isArray(coords)){return coords}if(coords.type==="Feature"){if(coords.geometry!==null){return coords.geometry.coordinates}}else{if(coords.coordinates){return coords.coordinates}}throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}exports.getCoords=getCoords;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;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;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;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;function getGeom(geojson){if(geojson.type==="Feature"){return geojson.geometry}return geojson}exports.getGeom=getGeom;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},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.earthRadius=6371008.8;exports.factors={centimeters:exports.earthRadius*100,centimetres:exports.earthRadius*100,degrees:exports.earthRadius/111325,feet:exports.earthRadius*3.28084,inches:exports.earthRadius*39.37,kilometers:exports.earthRadius/1e3,kilometres:exports.earthRadius/1e3,meters:exports.earthRadius,metres:exports.earthRadius,miles:exports.earthRadius/1609.344,millimeters:exports.earthRadius*1e3,millimetres:exports.earthRadius*1e3,nauticalmiles:exports.earthRadius/1852,radians:1,yards:exports.earthRadius/1.0936};exports.unitsFactors={centimeters:100,centimetres:100,degrees:1/111325,feet:3.28084,inches:39.37,kilometers:1/1e3,kilometres:1/1e3,meters:1,metres:1,miles:1/1609.344,millimeters:1e3,millimetres:1e3,nauticalmiles:1/1852,radians:1/exports.earthRadius,yards:1/1.0936};exports.areaFactors={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:3.86e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};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;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;function point(coordinates,properties,options){if(options===void 0){options={}}var geom={type:"Point",coordinates:coordinates};return feature(geom,properties,options)}exports.point=point;function points(coordinates,properties,options){if(options===void 0){options={}}return featureCollection(coordinates.map(function(coords){return point(coords,properties)}),options)}exports.points=points;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++){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;function polygons(coordinates,properties,options){if(options===void 0){options={}}return featureCollection(coordinates.map(function(coords){return polygon(coords,properties)}),options)}exports.polygons=polygons;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;function lineStrings(coordinates,properties,options){if(options===void 0){options={}}return featureCollection(coordinates.map(function(coords){return lineString(coords,properties)}),options)}exports.lineStrings=lineStrings;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;function multiLineString(coordinates,properties,options){if(options===void 0){options={}}var geom={type:"MultiLineString",coordinates:coordinates};return feature(geom,properties,options)}exports.multiLineString=multiLineString;function multiPoint(coordinates,properties,options){if(options===void 0){options={}}var geom={type:"MultiPoint",coordinates:coordinates};return feature(geom,properties,options)}exports.multiPoint=multiPoint;function multiPolygon(coordinates,properties,options){if(options===void 0){options={}}var geom={type:"MultiPolygon",coordinates:coordinates};return feature(geom,properties,options)}exports.multiPolygon=multiPolygon;function geometryCollection(geometries,properties,options){if(options===void 0){options={}}var geom={type:"GeometryCollection",geometries:geometries};return feature(geom,properties,options)}exports.geometryCollection=geometryCollection;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;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;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;function lengthToDegrees(distance,units){return radiansToDegrees(lengthToRadians(distance,units))}exports.lengthToDegrees=lengthToDegrees;function bearingToAzimuth(bearing){var angle=bearing%360;if(angle<0){angle+=360}return angle}exports.bearingToAzimuth=bearingToAzimuth;function radiansToDegrees(radians){var degrees=radians%(2*Math.PI);return degrees*180/Math.PI}exports.radiansToDegrees=radiansToDegrees;function degreesToRadians(degrees){var radians=degrees%360;return radians*Math.PI/180}exports.degreesToRadians=degreesToRadians;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;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;function isNumber(num){return!isNaN(num)&&num!==null&&!Array.isArray(num)&&!/^\s*$/.test(num)}exports.isNumber=isNumber;function isObject(input){return!!input&&input.constructor===Object}exports.isObject=isObject;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;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;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},function(module,exports,__webpack_require__){(function(global,setImmediate,process){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function(){var async={};function noop(){}function identity(v){return v}function toBool(v){return!!v}function notId(v){return!v}var previous_async;var root=typeof self==="object"&&self.self===self&&self||typeof global==="object"&&global.global===global&&global||this;if(root!=null){previous_async=root.async}async.noConflict=function(){root.async=previous_async;return async};function only_once(fn){return function(){if(fn===null)throw new Error("Callback was already called.");fn.apply(this,arguments);fn=null}}function _once(fn){return function(){if(fn===null)return;fn.apply(this,arguments);fn=null}}var _toString=Object.prototype.toString;var _isArray=Array.isArray||function(obj){return _toString.call(obj)==="[object Array]"};var _isObject=function(obj){var type=typeof obj;return type==="function"||type==="object"&&!!obj};function _isArrayLike(arr){return _isArray(arr)||typeof arr.length==="number"&&arr.length>=0&&arr.length%1===0}function _arrayEach(arr,iterator){var index=-1,length=arr.length;while(++index<length){iterator(arr[index],index,arr)}}function _map(arr,iterator){var index=-1,length=arr.length,result=Array(length);while(++index<length){result[index]=iterator(arr[index],index,arr)}return result}function _range(count){return _map(Array(count),function(v,i){return i})}function _reduce(arr,iterator,memo){_arrayEach(arr,function(x,i,a){memo=iterator(memo,x,i,a)});return memo}function _forEachOf(object,iterator){_arrayEach(_keys(object),function(key){iterator(object[key],key)})}function _indexOf(arr,item){for(var i=0;i<arr.length;i++){if(arr[i]===item)return i}return-1}var _keys=Object.keys||function(obj){var keys=[];for(var k in obj){if(obj.hasOwnProperty(k)){keys.push(k)}}return keys};function _keyIterator(coll){var i=-1;var len;var keys;if(_isArrayLike(coll)){len=coll.length;return function next(){i++;return i<len?i:null}}else{keys=_keys(coll);len=keys.length;return function next(){i++;return i<len?keys[i]:null}}}function _restParam(func,startIndex){startIndex=startIndex==null?func.length-1:+startIndex;return function(){var length=Math.max(arguments.length-startIndex,0);var rest=Array(length);for(var index=0;index<length;index++){rest[index]=arguments[index+startIndex]}switch(startIndex){case 0:return func.call(this,rest);case 1:return func.call(this,arguments[0],rest)}}}function _withoutIndex(iterator){return function(value,index,callback){return iterator(value,callback)}}var _setImmediate=typeof setImmediate==="function"&&setImmediate;var _delay=_setImmediate?function(fn){_setImmediate(fn)}:function(fn){setTimeout(fn,0)};if(typeof process==="object"&&typeof process.nextTick==="function"){async.nextTick=process.nextTick}else{async.nextTick=_delay}async.setImmediate=_setImmediate?_delay:async.nextTick;async.forEach=async.each=function(arr,iterator,callback){return async.eachOf(arr,_withoutIndex(iterator),callback)};async.forEachSeries=async.eachSeries=function(arr,iterator,callback){return async.eachOfSeries(arr,_withoutIndex(iterator),callback)};async.forEachLimit=async.eachLimit=function(arr,limit,iterator,callback){return _eachOfLimit(limit)(arr,_withoutIndex(iterator),callback)};async.forEachOf=async.eachOf=function(object,iterator,callback){callback=_once(callback||noop);object=object||[];var iter=_keyIterator(object);var key,completed=0;while((key=iter())!=null){completed+=1;iterator(object[key],key,only_once(done))}if(completed===0)callback(null);function done(err){completed--;if(err){callback(err)}else if(key===null&&completed<=0){callback(null)}}};async.forEachOfSeries=async.eachOfSeries=function(obj,iterator,callback){callback=_once(callback||noop);obj=obj||[];var nextKey=_keyIterator(obj);var key=nextKey();function iterate(){var sync=true;if(key===null){return callback(null)}iterator(obj[key],key,only_once(function(err){if(err){callback(err)}else{key=nextKey();if(key===null){return callback(null)}else{if(sync){async.setImmediate(iterate)}else{iterate()}}}}));sync=false}iterate()};async.forEachOfLimit=async.eachOfLimit=function(obj,limit,iterator,callback){_eachOfLimit(limit)(obj,iterator,callback)};function _eachOfLimit(limit){return function(obj,iterator,callback){callback=_once(callback||noop);obj=obj||[];var nextKey=_keyIterator(obj);if(limit<=0){return callback(null)}var done=false;var running=0;var errored=false;(function replenish(){if(done&&running<=0){return callback(null)}while(running<limit&&!errored){var key=nextKey();if(key===null){done=true;if(running<=0){callback(null)}return}running+=1;iterator(obj[key],key,only_once(function(err){running-=1;if(err){callback(err);errored=true}else{replenish()}}))}})()}}function doParallel(fn){return function(obj,iterator,callback){return fn(async.eachOf,obj,iterator,callback)}}function doParallelLimit(fn){return function(obj,limit,iterator,callback){return fn(_eachOfLimit(limit),obj,iterator,callback)}}function doSeries(fn){return function(obj,iterator,callback){return fn(async.eachOfSeries,obj,iterator,callback)}}function _asyncMap(eachfn,arr,iterator,callback){callback=_once(callback||noop);arr=arr||[];var results=_isArrayLike(arr)?[]:{};eachfn(arr,function(value,index,callback){iterator(value,function(err,v){results[index]=v;callback(err)})},function(err){callback(err,results)})}async.map=doParallel(_asyncMap);async.mapSeries=doSeries(_asyncMap);async.mapLimit=doParallelLimit(_asyncMap);async.inject=async.foldl=async.reduce=function(arr,memo,iterator,callback){async.eachOfSeries(arr,function(x,i,callback){iterator(memo,x,function(err,v){memo=v;callback(err)})},function(err){callback(err,memo)})};async.foldr=async.reduceRight=function(arr,memo,iterator,callback){var reversed=_map(arr,identity).reverse();async.reduce(reversed,memo,iterator,callback)};async.transform=function(arr,memo,iterator,callback){if(arguments.length===3){callback=iterator;iterator=memo;memo=_isArray(arr)?[]:{}}async.eachOf(arr,function(v,k,cb){iterator(memo,v,k,cb)},function(err){callback(err,memo)})};function _filter(eachfn,arr,iterator,callback){var results=[];eachfn(arr,function(x,index,callback){iterator(x,function(v){if(v){results.push({index:index,value:x})}callback()})},function(){callback(_map(results.sort(function(a,b){return a.index-b.index}),function(x){return x.value}))})}async.select=async.filter=doParallel(_filter);async.selectLimit=async.filterLimit=doParallelLimit(_filter);async.selectSeries=async.filterSeries=doSeries(_filter);function _reject(eachfn,arr,iterator,callback){_filter(eachfn,arr,function(value,cb){iterator(value,function(v){cb(!v)})},callback)}async.reject=doParallel(_reject);async.rejectLimit=doParallelLimit(_reject);async.rejectSeries=doSeries(_reject);function _createTester(eachfn,check,getResult){return function(arr,limit,iterator,cb){function done(){if(cb)cb(getResult(false,void 0))}function iteratee(x,_,callback){if(!cb)return callback();iterator(x,function(v){if(cb&&check(v)){cb(getResult(true,x));cb=iterator=false}callback()})}if(arguments.length>3){eachfn(arr,limit,iteratee,done)}else{cb=iterator;iterator=limit;eachfn(arr,iteratee,done)}}}async.any=async.some=_createTester(async.eachOf,toBool,identity);async.someLimit=_createTester(async.eachOfLimit,toBool,identity);async.all=async.every=_createTester(async.eachOf,notId,notId);async.everyLimit=_createTester(async.eachOfLimit,notId,notId);function _findGetResult(v,x){return x}async.detect=_createTester(async.eachOf,identity,_findGetResult);async.detectSeries=_createTester(async.eachOfSeries,identity,_findGetResult);async.detectLimit=_createTester(async.eachOfLimit,identity,_findGetResult);async.sortBy=function(arr,iterator,callback){async.map(arr,function(x,callback){iterator(x,function(err,criteria){if(err){callback(err)}else{callback(null,{value:x,criteria:criteria})}})},function(err,results){if(err){return callback(err)}else{callback(null,_map(results.sort(comparator),function(x){return x.value}))}});function comparator(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0}};async.auto=function(tasks,concurrency,callback){if(typeof arguments[1]==="function"){callback=concurrency;concurrency=null}callback=_once(callback||noop);var keys=_keys(tasks);var remainingTasks=keys.length;if(!remainingTasks){return callback(null)}if(!concurrency){concurrency=remainingTasks}var results={};var runningTasks=0;var hasError=false;var listeners=[];function addListener(fn){listeners.unshift(fn)}function removeListener(fn){var idx=_indexOf(listeners,fn);if(idx>=0)listeners.splice(idx,1)}function taskComplete(){remainingTasks--;_arrayEach(listeners.slice(0),function(fn){fn()})}addListener(function(){if(!remainingTasks){callback(null,results)}});_arrayEach(keys,function(k){if(hasError)return;var task=_isArray(tasks[k])?tasks[k]:[tasks[k]];var taskCallback=_restParam(function(err,args){runningTasks--;if(args.length<=1){args=args[0]}if(err){var safeResults={};_forEachOf(results,function(val,rkey){safeResults[rkey]=val});safeResults[k]=args;hasError=true;callback(err,safeResults)}else{results[k]=args;async.setImmediate(taskComplete)}});var requires=task.slice(0,task.length-1);var len=requires.length;var dep;while(len--){if(!(dep=tasks[requires[len]])){throw new Error("Has nonexistent dependency in "+requires.join(", "))}if(_isArray(dep)&&_indexOf(dep,k)>=0){throw new Error("Has cyclic dependencies")}}function ready(){return runningTasks<concurrency&&_reduce(requires,function(a,x){return a&&results.hasOwnProperty(x)},true)&&!results.hasOwnProperty(k)}if(ready()){runningTasks++;task[task.length-1](taskCallback,results)}else{addListener(listener)}function listener(){if(ready()){runningTasks++;removeListener(listener);task[task.length-1](taskCallback,results)}}})};async.retry=function(times,task,callback){var DEFAULT_TIMES=5;var DEFAULT_INTERVAL=0;var attempts=[];var opts={times:DEFAULT_TIMES,interval:DEFAULT_INTERVAL};function parseTimes(acc,t){if(typeof t==="number"){acc.times=parseInt(t,10)||DEFAULT_TIMES}else if(typeof t==="object"){acc.times=parseInt(t.times,10)||DEFAULT_TIMES;acc.interval=parseInt(t.interval,10)||DEFAULT_INTERVAL}else{throw new Error("Unsupported argument type for 'times': "+typeof t)}}var length=arguments.length;if(length<1||length>3){throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)")}else if(length<=2&&typeof times==="function"){callback=task;task=times}if(typeof times!=="function"){parseTimes(opts,times)}opts.callback=callback;opts.task=task;function wrappedTask(wrappedCallback,wrappedResults){function retryAttempt(task,finalAttempt){return function(seriesCallback){task(function(err,result){seriesCallback(!err||finalAttempt,{err:err,result:result})},wrappedResults)}}function retryInterval(interval){return function(seriesCallback){setTimeout(function(){seriesCallback(null)},interval)}}while(opts.times){var finalAttempt=!(opts.times-=1);attempts.push(retryAttempt(opts.task,finalAttempt));if(!finalAttempt&&opts.interval>0){attempts.push(retryInterval(opts.interval))}}async.series(attempts,function(done,data){data=data[data.length-1];(wrappedCallback||opts.callback)(data.err,data.result)})}return opts.callback?wrappedTask():wrappedTask};async.waterfall=function(tasks,callback){callback=_once(callback||noop);if(!_isArray(tasks)){var err=new Error("First argument to waterfall must be an array of functions");return callback(err)}if(!tasks.length){return callback()}function wrapIterator(iterator){return _restParam(function(err,args){if(err){callback.apply(null,[err].concat(args))}else{var next=iterator.next();if(next){args.push(wrapIterator(next))}else{args.push(callback)}ensureAsync(iterator).apply(null,args)}})}wrapIterator(async.iterator(tasks))()};function _parallel(eachfn,tasks,callback){callback=callback||noop;var results=_isArrayLike(tasks)?[]:{};eachfn(tasks,function(task,key,callback){task(_restParam(function(err,args){if(args.length<=1){args=args[0]}results[key]=args;callback(err)}))},function(err){callback(err,results)})}async.parallel=function(tasks,callback){_parallel(async.eachOf,tasks,callback)};async.parallelLimit=function(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)};async.series=function(tasks,callback){_parallel(async.eachOfSeries,tasks,callback)};async.iterator=function(tasks){function makeCallback(index){function fn(){if(tasks.length){tasks[index].apply(null,arguments)}return fn.next()}fn.next=function(){return index<tasks.length-1?makeCallback(index+1):null};return fn}return makeCallback(0)};async.apply=_restParam(function(fn,args){return _restParam(function(callArgs){return fn.apply(null,args.concat(callArgs))})});function _concat(eachfn,arr,fn,callback){var result=[];eachfn(arr,function(x,index,cb){fn(x,function(err,y){result=result.concat(y||[]);cb(err)})},function(err){callback(err,result)})}async.concat=doParallel(_concat);async.concatSeries=doSeries(_concat);async.whilst=function(test,iterator,callback){callback=callback||noop;if(test()){var next=_restParam(function(err,args){if(err){callback(err)}else if(test.apply(this,args)){iterator(next)}else{callback.apply(null,[null].concat(args))}});iterator(next)}else{callback(null)}};async.doWhilst=function(iterator,test,callback){var calls=0;return async.whilst(function(){return++calls<=1||test.apply(this,arguments)},iterator,callback)};async.until=function(test,iterator,callback){return async.whilst(function(){return!test.apply(this,arguments)},iterator,callback)};async.doUntil=function(iterator,test,callback){return async.doWhilst(iterator,function(){return!test.apply(this,arguments)},callback)};async.during=function(test,iterator,callback){callback=callback||noop;var next=_restParam(function(err,args){if(err){callback(err)}else{args.push(check);test.apply(this,args)}});var check=function(err,truth){if(err){callback(err)}else if(truth){iterator(next)}else{callback(null)}};test(check)};async.doDuring=function(iterator,test,callback){var calls=0;async.during(function(next){if(calls++<1){next(null,true)}else{test.apply(this,arguments)}},iterator,callback)};function _queue(worker,concurrency,payload){if(concurrency==null){concurrency=1}else if(concurrency===0){throw new Error("Concurrency must not be zero")}function _insert(q,data,pos,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()){return async.setImmediate(function(){q.drain()})}_arrayEach(data,function(task){var item={data:task,callback:callback||noop};if(pos){q.tasks.unshift(item)}else{q.tasks.push(item)}if(q.tasks.length===q.concurrency){q.saturated()}});async.setImmediate(q.process)}function _next(q,tasks){return function(){workers-=1;var removed=false;var args=arguments;_arrayEach(tasks,function(task){_arrayEach(workersList,function(worker,index){if(worker===task&&!removed){workersList.splice(index,1);removed=true}});task.callback.apply(task,args)});if(q.tasks.length+workers===0){q.drain()}q.process()}}var workers=0;var workersList=[];var q={tasks:[],concurrency:concurrency,payload:payload,saturated:noop,empty:noop,drain:noop,started:false,paused:false,push:function(data,callback){_insert(q,data,false,callback)},kill:function(){q.drain=noop;q.tasks=[]},unshift:function(data,callback){_insert(q,data,true,callback)},process:function(){while(!q.paused&&workers<q.concurrency&&q.tasks.length){var tasks=q.payload?q.tasks.splice(0,q.payload):q.tasks.splice(0,q.tasks.length);var data=_map(tasks,function(task){return task.data});if(q.tasks.length===0){q.empty()}workers+=1;workersList.push(tasks[0]);var cb=only_once(_next(q,tasks));worker(data,cb)}},length:function(){return q.tasks.length},running:function(){return workers},workersList:function(){return workersList},idle:function(){return q.tasks.length+workers===0},pause:function(){q.paused=true},resume:function(){if(q.paused===false){return}q.paused=false;var resumeCount=Math.min(q.concurrency,q.tasks.length);for(var w=1;w<=resumeCount;w++){async.setImmediate(q.process)}}};return q}async.queue=function(worker,concurrency){var q=_queue(function(items,cb){worker(items[0],cb)},concurrency,1);return q};async.priorityQueue=function(worker,concurrency){function _compareTasks(a,b){return a.priority-b.priority}function _binarySearch(sequence,item,compare){var beg=-1,end=sequence.length-1;while(beg<end){var mid=beg+(end-beg+1>>>1);if(compare(item,sequence[mid])>=0){beg=mid}else{end=mid-1}}return beg}function _insert(q,data,priority,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){return async.setImmediate(function(){q.drain()})}_arrayEach(data,function(task){var item={data:task,priority:priority,callback:typeof callback==="function"?callback:noop};q.tasks.splice(_binarySearch(q.tasks,item,_compareTasks)+1,0,item);if(q.tasks.length===q.concurrency){q.saturated()}async.setImmediate(q.process)})}var q=async.queue(worker,concurrency);q.push=function(data,priority,callback){_insert(q,data,priority,callback)};delete q.unshift;return q};async.cargo=function(worker,payload){return _queue(worker,1,payload)};function _console_fn(name){return _restParam(function(fn,args){fn.apply(null,args.concat([_restParam(function(err,args){if(typeof console==="object"){if(err){if(console.error){console.error(err)}}else if(console[name]){_arrayEach(args,function(x){console[name](x)})}}})]))})}async.log=_console_fn("log");async.dir=_console_fn("dir");async.memoize=function(fn,hasher){var memo={};var queues={};var has=Object.prototype.hasOwnProperty;hasher=hasher||identity;var memoized=_restParam(function memoized(args){var callback=args.pop();var key=hasher.apply(null,args);if(has.call(memo,key)){async.setImmediate(function(){callback.apply(null,memo[key])})}else if(has.call(queues,key)){queues[key].push(callback)}else{queues[key]=[callback];fn.apply(null,args.concat([_restParam(function(args){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};async.unmemoize=function(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}};function _times(mapper){return function(count,iterator,callback){mapper(_range(count),iterator,callback)}}async.times=_times(async.map);async.timesSeries=_times(async.mapSeries);async.timesLimit=function(count,limit,iterator,callback){return async.mapLimit(_range(count),limit,iterator,callback)};async.seq=function(){var fns=arguments;return _restParam(function(args){var that=this;var callback=args[args.length-1];if(typeof callback=="function"){args.pop()}else{callback=noop}async.reduce(fns,args,function(newargs,fn,cb){fn.apply(that,newargs.concat([_restParam(function(err,nextargs){cb(err,nextargs)})]))},function(err,results){callback.apply(that,[err].concat(results))})})};async.compose=function(){return async.seq.apply(null,Array.prototype.reverse.call(arguments))};function _applyEach(eachfn){return _restParam(function(fns,args){var go=_restParam(function(args){var that=this;var callback=args.pop();return eachfn(fns,function(fn,_,cb){fn.apply(that,args.concat([cb]))},callback)});if(args.length){return go.apply(this,args)}else{return go}})}async.applyEach=_applyEach(async.eachOf);async.applyEachSeries=_applyEach(async.eachOfSeries);async.forever=function(fn,callback){var done=only_once(callback||noop);var task=ensureAsync(fn);function next(err){if(err){return done(err)}task(next)}next()};function ensureAsync(fn){return _restParam(function(args){var callback=args.pop();args.push(function(){var innerArgs=arguments;if(sync){async.setImmediate(function(){callback.apply(null,innerArgs)})}else{callback.apply(null,innerArgs)}});var sync=true;fn.apply(this,args);sync=false})}async.ensureAsync=ensureAsync;async.constant=_restParam(function(values){var args=[null].concat(values);return function(callback){return callback.apply(this,args)}});async.wrapSync=async.asyncify=function asyncify(func){return _restParam(function(args){var callback=args.pop();var result;try{result=func.apply(this,args)}catch(e){return callback(e)}if(_isObject(result)&&typeof result.then==="function"){result.then(function(value){callback(null,value)})["catch"](function(err){callback(err.message?err:new Error(err))})}else{callback(null,result)}})};if(typeof module==="object"&&module.exports){module.exports=async}else if(true){!(__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return async}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}else{root.async=async}})()}).call(exports,__webpack_require__(6),__webpack_require__(20).setImmediate,__webpack_require__(8))},function(module,exports){var g;g=function(){return this}();try{g=g||Function("return this")()||(1,eval)("this")}catch(e){if(typeof window==="object")g=window}module.exports=g},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var helpers=__webpack_require__(4);function coordEach(geojson,callback,excludeWrapCoord){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;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;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")}}}}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}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}}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}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}}}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}function coordAll(geojson){var coords=[];coordEach(geojson,function(coord){coords.push(coord)});return coords}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;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;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")}}featureIndex++}}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}function flattenEach(geojson,callback){geomEach(geojson,function(geometry,featureIndex,properties,bbox,id){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;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}})}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}function segmentEach(geojson,callback){flattenEach(geojson,function(feature,featureIndex,multiFeatureIndex){var segmentIndex=0;if(!feature.geometry)return;var type=feature.geometry.type;if(type==="Point"||type==="MultiPoint")return;var previousCoords;var previousFeatureIndex=0;var previousMultiIndex=0;var prevGeomIndex=0;if(coordEach(feature,function(currentCoord,coordIndex,featureIndexCoord,multiPartIndexCoord,geometryIndex){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})}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}function lineEach(geojson,callback){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}})}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}function findSegment(geojson,options){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;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")}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")}function findPoint(geojson,options){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;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")}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},function(module,exports){var process=module.exports={};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){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){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)}};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="";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}},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var invariant_1=__webpack_require__(3);function booleanPointInPolygon(point,polygon,options){if(options===void 0){options={}}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;if(bbox&&inBBox(pt,bbox)===false){return false}if(type==="Polygon"){polys=[polys]}var insidePoly=false;for(var i=0;i<polys.length&&!insidePoly;i++){if(inRing(pt,polys[i][0],options.ignoreBoundary)){var inHole=false;var k=1;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;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}function inBBox(pt,bbox){return bbox[0]<=pt[0]&&bbox[1]<=pt[1]&&bbox[2]>=pt[0]&&bbox[3]>=pt[1]}},function(module,exports,__webpack_require__){var Collection,MemoryDb,async,compileSort,processFind,utils,_,__bind=function(fn,me){return function(){return fn.apply(me,arguments)}};_=__webpack_require__(1);async=__webpack_require__(5);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=MemoryDb=function(){function MemoryDb(options,success){this.collections={};this.options=_.defaults(options,{safety:"clone"});if(success){success(this)}}MemoryDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.options);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};MemoryDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};MemoryDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return MemoryDb}();Collection=function(){function Collection(name,options){this._applySafety=__bind(this._applySafety,this);this.name=name;this.items={};this.upserts={};this.removes={};this.options=options||{}}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(_this){return function(results){if(success!=null){return success(_this._applySafety(results.length>0?results[0]:null))}}}(this),error)};Collection.prototype._findFetch=function(selector,options,success,error){return setTimeout(function(_this){return function(){var allItems,results;if(selector&&selector._id&&_.isString(selector._id)){allItems=_.compact([_this.items[selector._id]])}else{allItems=_.values(_this.items)}results=processFind(allItems,selector,options);if(success!=null){return success(_this._applySafety(results))}}}(this),0)};Collection.prototype._applySafety=function(items){if(!items){return items}if(_.isArray(items)){return _.map(items,this._applySafety)}if(this.options.safety==="clone"||!this.options.safety){return JSON.parse(JSON.stringify(items))}if(this.options.safety==="freeze"){Object.freeze(items);return items}throw new Error("Unsupported safety "+this.options.safety)};Collection.prototype.upsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];items=JSON.parse(JSON.stringify(items));for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(item.base===void 0){if(this.upserts[item.doc._id]){item.base=this.upserts[item.doc._id].base}else{item.base=this.items[item.doc._id]||null}}this.items[item.doc._id]=item.doc;this.upserts[item.doc._id]=item}if(_.isArray(docs)){if(success){return success(this._applySafety(_.pluck(items,"doc")))}}else{if(success){return success(this._applySafety(_.pluck(items,"doc")[0]))}}};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}if(_.has(this.items,id)){this.removes[id]=this.items[id];delete this.items[id];delete this.upserts[id]}else{this.removes[id]={_id:id}}if(success!=null){return success()}};Collection.prototype.cache=function(docs,selector,options,success,error){var doc,docsMap,sort,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];this.cacheOne(doc)}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return this.find(selector,options).fetch(function(_this){return function(results){var result,_j,_len1;for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(!docsMap[result._id]&&!_.has(_this.upserts,result._id)){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}delete _this.items[result._id]}}if(success!=null){return success()}}}(this),error)};Collection.prototype.pendingUpserts=function(success){return success(_.values(this.upserts))};Collection.prototype.pendingRemoves=function(success){return success(_.pluck(this.removes,"_id"))};Collection.prototype.resolveUpserts=function(upserts,success){var id,upsert,_i,_len;for(_i=0,_len=upserts.length;_i<_len;_i++){upsert=upserts[_i];id=upsert.doc._id;if(this.upserts[id]){if(_.isEqual(upsert.doc,this.upserts[id].doc)){delete this.upserts[id]}else{this.upserts[id].base=upsert.doc}}}if(success!=null){return success()}};Collection.prototype.resolveRemove=function(id,success){delete this.removes[id];if(success!=null){return success()}};Collection.prototype.seed=function(docs,success){var doc,_i,_len;if(!_.isArray(docs)){docs=[docs]}for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.items,doc._id)&&!_.has(this.removes,doc._id)){this.items[doc._id]=doc}}if(success!=null){return success()}};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success){var doc,existing,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.upserts,doc._id)&&!_.has(this.removes,doc._id)){existing=this.items[doc._id];if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){this.items[doc._id]=doc}}}if(success!=null){return success()}};Collection.prototype.uncache=function(selector,success,error){var compiledSelector,items;compiledSelector=utils.compileDocumentSelector(selector);items=_.filter(_.values(this.items),function(_this){return function(item){return _this.upserts[item._id]!=null||!compiledSelector(item)}}(this));this.items=_.object(_.pluck(items,"_id"),items);if(success!=null){return success()}};Collection.prototype.uncacheList=function(ids,success,error){var idIndex,items;idIndex=_.indexBy(ids);items=_.filter(_.values(this.items),function(_this){return function(item){return _this.upserts[item._id]!=null||!idIndex[item._id]}}(this));this.items=_.object(_.pluck(items,"_id"),items);if(success!=null){return success()}};return Collection}()},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var meta_1=__webpack_require__(7);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},function(module,exports,__webpack_require__){var Collection,IDBStore,IndexedDb,async,compileSort,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(5);IDBStore=__webpack_require__(35);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=IndexedDb=function(){function IndexedDb(options,success,error){var ex;this.collections={};try{this.store=new IDBStore({dbVersion:1,storeName:"minimongo_"+options.namespace,keyPath:["col","doc._id"],autoIncrement:false,onStoreReady:function(_this){return function(){if(success){return success(_this)}}}(this),onError:error,indexes:[{name:"col",keyPath:"col",unique:false,multiEntry:false},{name:"col-state",keyPath:["col","state"],unique:false,multiEntry:false}]})}catch(_error){ex=_error;if(error){error(ex)}return}}IndexedDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.store);this[name]=collection;this.collections[name]=collection;if(success){return success()}};IndexedDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];return this.store.query(function(_this){return function(matches){var keys;keys=_.map(matches,function(m){return[m.col,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:name}),onError:error})};IndexedDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return IndexedDb}();Collection=function(){function Collection(name,store){this.name=name;this.store=store}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){return this.store.query(function(matches){matches=_.filter(matches,function(m){return m.state!=="removed"});if(success!=null){return success(processFind(_.pluck(matches,"doc"),selector,options))}},{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};Collection.prototype.upsert=function(docs,bases,success,error){var items,keys,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];keys=_.map(items,function(_this){return function(item){return[_this.name,item.doc._id]}}(this));return this.store.getBatch(keys,function(_this){return function(records){var puts;puts=_.map(items,function(item,i){var base;if(item.base!==void 0){base=item.base}else if(records[i]&&records[i].doc&&records[i].state==="cached"){base=records[i].doc}else if(records[i]&&records[i].doc&&records[i].state==="upserted"){base=records[i].base}else{base=null}return{col:_this.name,state:"upserted",doc:item.doc,base:base}});return _this.store.putBatch(puts,function(){if(success){return success(docs)}},error)}}(this),error)};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}return this.store.get([this.name,id],function(_this){return function(record){if(record==null){record={col:_this.name,doc:{_id:id}}}record.state="removed";return _this.store.put(record,function(){if(success){return success(id)}},error)}}(this))};Collection.prototype.cache=function(docs,selector,options,success,error){var keys,puts,step2;step2=function(_this){return function(){var docsMap,sort;docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return _this.find(selector,options).fetch(function(results){var keys,removes;removes=[];keys=_.map(results,function(result){return[_this.name,result._id]});if(keys.length===0){if(success!=null){success()}return}return _this.store.getBatch(keys,function(records){var i,record,result,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];result=results[i];if(!docsMap[result._id]&&record&&record.state==="cached"){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}removes.push([_this.name,result._id])}}if(removes.length>0){return _this.store.removeBatch(removes,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}},error)},error)}}(this);if(docs.length===0){return step2()}keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record==null||record.state==="cached"){if(!record||!doc._rev||!record.doc._rev||doc._rev>record.doc._rev){puts.push({col:_this.name,state:"cached",doc:doc})}}}if(puts.length>0){return _this.store.putBatch(puts,step2,error)}else{return step2()}}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){return this.store.query(function(matches){var upserts;upserts=_.map(matches,function(m){return{doc:m.doc,base:m.base||null}});if(success!=null){return success(upserts)}},{index:"col-state",keyRange:this.store.makeKeyRange({only:[this.name,"upserted"]}),onError:error})};Collection.prototype.pendingRemoves=function(success,error){return this.store.query(function(matches){if(success!=null){return success(_.pluck(_.pluck(matches,"doc"),"_id"))}},{index:"col-state",keyRange:this.store.makeKeyRange({only:[this.name,"removed"]}),onError:error})};Collection.prototype.resolveUpserts=function(upserts,success,error){var keys;keys=_.map(upserts,function(_this){return function(upsert){return[_this.name,upsert.doc._id]}}(this));return this.store.getBatch(keys,function(_this){return function(records){var i,puts,record,_i,_ref;puts=[];for(i=_i=0,_ref=upserts.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];if(record&&record.state==="upserted"){if(_.isEqual(record.doc,upserts[i].doc)){record.state="cached";puts.push(record)}else{record.base=upserts[i].doc;puts.push(record)}}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success){return success()}},error)}else{if(success){return success()}}}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){return this.store.get([this.name,id],function(_this){return function(record){if(!record){if(success!=null){success()}return}if(record.state==="removed"){return _this.store.remove([_this.name,id],function(){if(success!=null){return success()}},error)}}}(this))};Collection.prototype.seed=function(docs,success,error){var keys,puts;if(!_.isArray(docs)){docs=[docs]}keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record==null){puts.push({col:_this.name,state:"cached",doc:doc})}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success,error){var keys,puts;keys=_.map(docs,function(_this){return function(doc){return[_this.name,doc._id]}}(this));puts=[];return this.store.getBatch(keys,function(_this){return function(records){var doc,i,record,_i,_ref;for(i=_i=0,_ref=records.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){record=records[i];doc=docs[i];if(record&&doc._rev&&record.doc._rev&&doc._rev<=record.doc._rev){continue}if(record==null){record={col:_this.name,state:"cached",doc:doc}}if(record.state==="cached"){record.doc=doc;puts.push(record)}}if(puts.length>0){return _this.store.putBatch(puts,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),error)};Collection.prototype.uncache=function(selector,success,error){var compiledSelector;compiledSelector=utils.compileDocumentSelector(selector);return this.store.query(function(_this){return function(matches){var keys;matches=_.filter(matches,function(m){return m.state==="cached"&&compiledSelector(m.doc)});keys=_.map(matches,function(m){return[_this.name,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};Collection.prototype.uncacheList=function(ids,success,error){var idIndex;idIndex=_.indexBy(ids);error=error||function(){};return this.store.query(function(_this){return function(matches){var keys;matches=_.filter(matches,function(m){return m.state==="cached"&&idIndex[m.doc._id]});keys=_.map(matches,function(m){return[_this.name,m.doc._id]});if(keys.length>0){return _this.store.removeBatch(keys,function(){if(success!=null){return success()}},error)}else{if(success!=null){return success()}}}}(this),{index:"col",keyRange:this.store.makeKeyRange({only:this.name}),onError:error})};return Collection}()},function(module,exports,__webpack_require__){var Collection,WebSQLDb,async,compileSort,doNothing,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(5);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;doNothing=function(){};module.exports=WebSQLDb=function(){function WebSQLDb(options,success,error){var checkV2,ex,migrateToV1,migrateToV2;this.collections={};if(options.storage==="sqlite"&&window.sqlitePlugin){window.sqlitePlugin.openDatabase({name:"minimongo_"+options.namespace,location:"default"},function(_this){return function(sqliteDb){console.log("Database open successful");_this.db=sqliteDb;console.log("Checking version");_this.db.executeSql("PRAGMA user_version",[],function(rs){var version;version=rs.rows.item(0).user_version;if(version===0){_this.db.transaction(function(tx){tx.executeSql("CREATE TABLE docs (\ncol TEXT NOT NULL,\nid TEXT NOT NULL,\nstate TEXT NOT NULL,\ndoc TEXT,\nbase TEXT,\nPRIMARY KEY (col, id));",[],doNothing,function(tx,err){return error(err)});tx.executeSql("PRAGMA user_version = 2",[],doNothing,function(tx,err){return error(err)});return success(_this)})}else{success(_this)}},function(err){console.log("version check error :: ",JSON.stringify(err));error(err)})}}(this),function(err){console.log("Error opening databse :: ",JSON.stringify(err));error(err)})}else{try{this.db=window.openDatabase("minimongo_"+options.namespace,"","Minimongo:"+options.namespace,5*1024*1024);if(!this.db){return error(new Error("Failed to create database"))}}catch(_error){ex=_error;if(error){error(ex)}return}}migrateToV1=function(tx){return tx.executeSql("CREATE TABLE docs (\n col TEXT NOT NULL,\n id TEXT NOT NULL,\n state TEXT NOT NULL,\n doc TEXT,\n PRIMARY KEY (col, id));",[],doNothing,function(tx,err){return error(err)})};migrateToV2=function(tx){return tx.executeSql("ALTER TABLE docs ADD COLUMN base TEXT;",[],doNothing,function(tx,err){return error(err)})};checkV2=function(_this){return function(){if(_this.db.version==="1.0"){return _this.db.changeVersion("1.0","2.0",migrateToV2,error,function(){if(success){return success(_this)}})}else if(_this.db.version!=="2.0"){return error("Unknown db version "+_this.db.version)}else{if(success){return success(_this)}}}}(this);if(!options.storage){if(!this.db.version){this.db.changeVersion("","1.0",migrateToV1,error,checkV2)}else{checkV2()}}return this.db}WebSQLDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.db);this[name]=collection;this.collections[name]=collection;if(success){return success()}};WebSQLDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];return this.db.transaction(function(tx){return tx.executeSql("DELETE FROM docs WHERE col = ?",[name],success,function(tx,err){return error(err)})},error)};WebSQLDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return WebSQLDb}();Collection=function(){function Collection(name,db){this.name=name;this.db=db}Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ?",[_this.name],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);if(row.state!=="removed"){docs.push(JSON.parse(row.doc))}}if(success!=null){return success(processFind(docs,selector,options))}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.upsert=function(docs,bases,success,error){var items,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];error=error||function(){};return this.db.transaction(function(_this){return function(tx){var ids;ids=_.map(items,function(item){return item.doc._id});bases={};return async.eachSeries(ids,function(id,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,id],function(tx2,results){var row;tx=tx2;if(results.rows.length>0){row=results.rows.item(0);if(row.state==="upserted"){bases[row.id]=row.base?JSON.parse(row.base):null}else if(row.state==="cached"){bases[row.id]=JSON.parse(row.doc)}}return callback()},function(tx,err){return error(err)})},function(){var base,id,item,_i,_len,_results;_results=[];for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];id=item.doc._id;if(item.base!==void 0){base=item.base}else if(bases[id]){base=bases[id]}else{base=null}_results.push(tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc, base) VALUES (?, ?, ?, ?, ?)",[_this.name,item.doc._id,"upserted",JSON.stringify(item.doc),JSON.stringify(base)],doNothing,function(tx,err){return error(err)}))}return _results})}}(this),error,function(){if(success){return success(docs)}})};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,id],function(tx,results){if(results.rows.length>0){return tx.executeSql('UPDATE docs SET state="removed" WHERE col = ? AND id = ?',[_this.name,id],function(){if(success){return success(id)}},function(tx,err){return error(err)})}else{return tx.executeSql("INSERT INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,id,"removed",JSON.stringify({_id:id})],function(){if(success){return success(id)}},function(tx,err){return error(err)})}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.cache=function(docs,selector,options,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){var existing;if(results.rows.length===0||results.rows.item(0).state==="cached"){existing=results.rows.length>0?JSON.parse(results.rows.item(0).doc):null;if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}}else{return callback()}},function(tx,err){return error(err)})},function(err){var docsMap,sort;if(err){if(error){error(err)}return}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return _this.find(selector,options).fetch(function(results){return _this.db.transaction(function(tx){return async.eachSeries(results,function(result,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,result._id],function(tx,rows){if(!docsMap[result._id]&&rows.rows.length>0&&rows.rows.item(0).state==="cached"){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){return callback()}if(!options.sort){return callback()}}return tx.executeSql("DELETE FROM docs WHERE col = ? AND id = ?",[_this.name,result._id],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}},function(tx,err){return error(err)})},function(err){if(err!=null){if(error!=null){error(err)}return}if(success!=null){return success()}})},error)},error)})}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"upserted"],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);docs.push({doc:JSON.parse(row.doc),base:row.base?JSON.parse(row.base):null})}if(success!=null){return success(docs)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.pendingRemoves=function(success,error){error=error||function(){};return this.db.readTransaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"removed"],function(tx,results){var docs,i,row,_i,_ref;docs=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);docs.push(JSON.parse(row.doc)._id)}if(success!=null){return success(docs)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.resolveUpserts=function(upserts,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(upserts,function(upsert,cb){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,upsert.doc._id],function(tx,results){if(results.rows.length>0&&results.rows.item(0).state==="upserted"){if(_.isEqual(JSON.parse(results.rows.item(0).doc),upsert.doc)){tx.executeSql('UPDATE docs SET state="cached" WHERE col = ? AND id = ?',[_this.name,upsert.doc._id],doNothing,function(tx,err){return error(err)});return cb()}else{tx.executeSql("UPDATE docs SET base=? WHERE col = ? AND id = ?",[JSON.stringify(upsert.doc),_this.name,upsert.doc._id],doNothing,function(tx,err){return error(err)});return cb()}}else{return cb()}},function(tx,err){return error(err)})},function(err){if(err){return error(err)}if(success){return success()}})}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql('DELETE FROM docs WHERE state="removed" AND col = ? AND id = ?',[_this.name,id],function(){if(success){return success(id)}},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.seed=function(docs,success,error){if(!_.isArray(docs)){docs=[docs]}error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){if(results.rows.length===0){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return error(err)})}else{return callback()}},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(docs,function(doc,callback){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND id = ?",[_this.name,doc._id],function(tx,results){var existing;if(results.rows.length===0||results.rows.item(0).state==="cached"){existing=results.rows.length>0?JSON.parse(results.rows.item(0).doc):null;if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){return tx.executeSql("INSERT OR REPLACE INTO docs (col, id, state, doc) VALUES (?, ?, ?, ?)",[_this.name,doc._id,"cached",JSON.stringify(doc)],function(){return callback()},function(tx,err){return callback(err)})}else{return callback()}}else{return callback()}},function(tx,err){return callback(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success(docs)}}})}}(this),error)};Collection.prototype.uncache=function(selector,success,error){var compiledSelector;compiledSelector=utils.compileDocumentSelector(selector);error=error||function(){};return this.db.transaction(function(_this){return function(tx){return tx.executeSql("SELECT * FROM docs WHERE col = ? AND state = ?",[_this.name,"cached"],function(tx,results){var doc,i,row,toRemove,_i,_ref;toRemove=[];for(i=_i=0,_ref=results.rows.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){row=results.rows.item(i);doc=JSON.parse(row.doc);if(compiledSelector(doc)){toRemove.push(doc._id)}}return async.eachSeries(toRemove,function(id,callback){return tx.executeSql('DELETE FROM docs WHERE state="cached" AND col = ? AND id = ?',[_this.name,id],function(){return callback()},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})},function(tx,err){return error(err)})}}(this),error)};Collection.prototype.uncacheList=function(ids,success,error){error=error||function(){};return this.db.transaction(function(_this){return function(tx){return async.eachSeries(ids,function(id,callback){return tx.executeSql('DELETE FROM docs WHERE state="cached" AND col = ? AND id = ?',[_this.name,id],function(){return callback()},function(tx,err){return error(err)})},function(err){if(err){if(error){return error(err)}}else{if(success){return success()}}})}}(this),error)};return Collection}()},function(module,exports,__webpack_require__){var Collection,LocalStorageDb,async,compileSort,processFind,utils,_;_=__webpack_require__(1);async=__webpack_require__(5);utils=__webpack_require__(0);processFind=__webpack_require__(0).processFind;compileSort=__webpack_require__(2).compileSort;module.exports=LocalStorageDb=function(){function LocalStorageDb(options,success){this.collections={};if(options&&options.namespace&&window.localStorage){this.namespace=options.namespace}if(success){success(this)}}LocalStorageDb.prototype.addCollection=function(name,success,error){var collection,namespace;if(this.namespace){namespace=this.namespace+"."+name}collection=new Collection(name,namespace);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};LocalStorageDb.prototype.removeCollection=function(name,success,error){var i,key,keyToMatch,keys,_i,_j,_len,_ref;if(this.namespace&&window.localStorage){keys=[];for(i=_i=0,_ref=window.localStorage.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){keys.push(window.localStorage.key(i))}for(_j=0,_len=keys.length;_j<_len;_j++){key=keys[_j];keyToMatch=this.namespace+"."+name;if(key.substring(0,keyToMatch.length)===keyToMatch){window.localStorage.removeItem(key)}}}delete this[name];delete this.collections[name];if(success!=null){return success()}};LocalStorageDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return LocalStorageDb}();Collection=function(){function Collection(name,namespace){this.name=name;this.namespace=namespace;this.items={};this.upserts={};this.removes={};if(window.localStorage&&namespace!=null){this.loadStorage()}}Collection.prototype.loadStorage=function(){var base,i,item,key,removeItems,upsertKeys,_i,_j,_len,_ref;this.itemNamespace=this.namespace+"_";for(i=_i=0,_ref=window.localStorage.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){key=window.localStorage.key(i);if(key.substring(0,this.itemNamespace.length)===this.itemNamespace){item=JSON.parse(window.localStorage[key]);this.items[item._id]=item}}upsertKeys=window.localStorage[this.namespace+"upserts"]?JSON.parse(window.localStorage[this.namespace+"upserts"]):[];for(_j=0,_len=upsertKeys.length;_j<_len;_j++){key=upsertKeys[_j];this.upserts[key]={doc:this.items[key]};base=window.localStorage[this.namespace+"upsertbase_"+key]?JSON.parse(window.localStorage[this.namespace+"upsertbase_"+key]):null;this.upserts[key].base=base}removeItems=window.localStorage[this.namespace+"removes"]?JSON.parse(window.localStorage[this.namespace+"removes"]):[];return this.removes=_.object(_.pluck(removeItems,"_id"),removeItems)};Collection.prototype.find=function(selector,options){return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var _ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}return this.find(selector,options).fetch(function(results){if(success!=null){return success(results.length>0?results[0]:null)}},error)};Collection.prototype._findFetch=function(selector,options,success,error){if(success!=null){return success(processFind(_.cloneDeep(_.values(this.items)),selector,options))}};Collection.prototype.upsert=function(docs,bases,success,error){var item,items,_i,_len,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];items=JSON.parse(JSON.stringify(items));for(_i=0,_len=items.length;_i<_len;_i++){item=items[_i];if(item.base===void 0){if(this.upserts[item.doc._id]){item.base=this.upserts[item.doc._id].base}else{item.base=this.items[item.doc._id]||null}}item=_.cloneDeep(item);this._putItem(item.doc);this._putUpsert(item)}if(success){return success(docs)}};Collection.prototype.remove=function(id,success,error){if(_.isObject(id)){this.find(id).fetch(function(_this){return function(rows){return async.each(rows,function(row,cb){return _this.remove(row._id,function(){return cb()},cb)},function(){return success()})}}(this),error);return}if(_.has(this.items,id)){this._putRemove(this.items[id]);this._deleteItem(id);this._deleteUpsert(id)}else{this._putRemove({_id:id})}if(success!=null){return success()}};Collection.prototype._putItem=function(doc){this.items[doc._id]=doc;if(this.namespace){return window.localStorage[this.itemNamespace+doc._id]=JSON.stringify(doc)}};Collection.prototype._deleteItem=function(id){delete this.items[id];if(this.namespace){return window.localStorage.removeItem(this.itemNamespace+id)}};Collection.prototype._putUpsert=function(upsert){this.upserts[upsert.doc._id]=upsert;if(this.namespace){window.localStorage[this.namespace+"upserts"]=JSON.stringify(_.keys(this.upserts));return window.localStorage[this.namespace+"upsertbase_"+upsert.doc._id]=JSON.stringify(upsert.base)}};Collection.prototype._deleteUpsert=function(id){delete this.upserts[id];if(this.namespace){return window.localStorage[this.namespace+"upserts"]=JSON.stringify(_.keys(this.upserts))}};Collection.prototype._putRemove=function(doc){this.removes[doc._id]=doc;if(this.namespace){return window.localStorage[this.namespace+"removes"]=JSON.stringify(_.values(this.removes))}};Collection.prototype._deleteRemove=function(id){delete this.removes[id];if(this.namespace){return window.localStorage[this.namespace+"removes"]=JSON.stringify(_.values(this.removes))}};Collection.prototype.cache=function(docs,selector,options,success,error){var doc,docsMap,sort,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];this.cacheOne(doc)}docsMap=_.object(_.pluck(docs,"_id"),docs);if(options.sort){sort=compileSort(options.sort)}return this.find(selector,options).fetch(function(_this){return function(results){var result,_j,_len1;for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(!docsMap[result._id]&&!_.has(_this.upserts,result._id)){if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}_this._deleteItem(result._id)}}if(success!=null){return success()}}}(this),error)};Collection.prototype.pendingUpserts=function(success){return success(_.values(this.upserts))};Collection.prototype.pendingRemoves=function(success){return success(_.pluck(this.removes,"_id"))};Collection.prototype.resolveUpserts=function(upserts,success){var upsert,_i,_len;for(_i=0,_len=upserts.length;_i<_len;_i++){upsert=upserts[_i];if(this.upserts[upsert.doc._id]){if(_.isEqual(upsert.doc,this.upserts[upsert.doc._id].doc)){this._deleteUpsert(upsert.doc._id)}else{this.upserts[upsert.doc._id].base=upsert.doc;this._putUpsert(this.upserts[upsert.doc._id])}}}if(success!=null){return success()}};Collection.prototype.resolveRemove=function(id,success){this._deleteRemove(id);if(success!=null){return success()}};Collection.prototype.seed=function(docs,success){var doc,_i,_len;if(!_.isArray(docs)){docs=[docs]}for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.items,doc._id)&&!_.has(this.removes,doc._id)){this._putItem(doc)}}if(success!=null){return success()}};Collection.prototype.cacheOne=function(doc,success,error){return this.cacheList([doc],success,error)};Collection.prototype.cacheList=function(docs,success){var doc,existing,_i,_len;for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];if(!_.has(this.upserts,doc._id)&&!_.has(this.removes,doc._id)){existing=this.items[doc._id];if(!existing||!doc._rev||!existing._rev||doc._rev>existing._rev){this._putItem(doc)}}}if(success!=null){return success()}};Collection.prototype.uncache=function(selector,success,error){var compiledSelector,item,_i,_len,_ref;compiledSelector=utils.compileDocumentSelector(selector);_ref=_.values(this.items);for(_i=0,_len=_ref.length;_i<_len;_i++){item=_ref[_i];if(this.upserts[item._id]==null&&compiledSelector(item)){this._deleteItem(item._id)}}if(success!=null){return success()}};Collection.prototype.uncacheList=function(ids,success,error){var id,_i,_len;for(_i=0,_len=ids.length;_i<_len;_i++){id=ids[_i];if(this.upserts[id]==null){this._deleteItem(id)}}if(success!=null){return success()}};return Collection}()},function(module,exports,__webpack_require__){var HybridCollection,HybridDb,processFind,utils,_;_=__webpack_require__(1);processFind=__webpack_require__(0).processFind;utils=__webpack_require__(0);module.exports=HybridDb=function(){function HybridDb(localDb,remoteDb){this.localDb=localDb;this.remoteDb=remoteDb;this.collections={}}HybridDb.prototype.addCollection=function(name,options,success,error){var collection,_ref;if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}collection=new HybridCollection(name,this.localDb[name],this.remoteDb[name],options);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};HybridDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};HybridDb.prototype.upload=function(success,error){var cols,uploadCols;cols=_.values(this.collections);uploadCols=function(cols,success,error){var col;col=_.first(cols);if(col){return col.upload(function(){return uploadCols(_.rest(cols),success,error)},function(err){return error(err)})}else{return success()}};return uploadCols(cols,success,error)};HybridDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return HybridDb}();HybridCollection=function(){function HybridCollection(name,localCol,remoteCol,options){this.name=name;this.localCol=localCol;this.remoteCol=remoteCol;this.options=options||{};_.defaults(this.options,{cacheFind:true,cacheFindOne:true,interim:true,useLocalOnRemoteError:true,shortcut:false,timeout:0,sortUpserts:null})}HybridCollection.prototype.find=function(selector,options){if(options==null){options={}}return{fetch:function(_this){return function(success,error){return _this._findFetch(selector,options,success,error)}}(this)}};HybridCollection.prototype.findOne=function(selector,options,success,error){var step2,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}_.defaults(options,this.options);step2=function(_this){return function(localDoc){var findOptions;findOptions=_.cloneDeep(options);findOptions.interim=false;findOptions.cacheFind=options.cacheFindOne;if(selector._id){findOptions.limit=1}else{delete findOptions.limit}return _this.find(selector,findOptions).fetch(function(data){if(data.length>0){if(!_.isEqual(localDoc,data[0])){return success(data[0])}}else{return success(null)}},error)}}(this);if(options.interim||options.shortcut){return this.localCol.findOne(selector,options,function(localDoc){if(localDoc){success(_.cloneDeep(localDoc));if(options.shortcut){return}}return step2(localDoc)},error)}else{return step2()}};HybridCollection.prototype._findFetch=function(selector,options,success,error){var localSuccess,step2;_.defaults(options,this.options);step2=function(_this){return function(localData){var remoteError,remoteOptions,remoteSuccess,timedOut,timer;remoteOptions=_.cloneDeep(options);if(options.cacheFind){delete remoteOptions.fields}remoteOptions.localData=localData;timer=null;timedOut=false;remoteSuccess=function(remoteData){var cacheSuccess,data;if(timer){clearTimeout(timer)}if(timedOut){if(options.cacheFind){_this.localCol.cache(remoteData,selector,options,function(){},error)}return}if(options.cacheFind){cacheSuccess=function(){var localSuccess2;localSuccess2=function(localData2){if(!options.interim||!_.isEqual(localData,localData2)){return success(localData2)}};return _this.localCol.find(selector,options).fetch(localSuccess2,error)};return _this.localCol.cache(remoteData,selector,options,cacheSuccess,error)}else{data=remoteData;return _this.localCol.pendingRemoves(function(removes){var removesMap;if(removes.length>0){removesMap=_.object(_.map(removes,function(id){return[id,id]}));data=_.filter(remoteData,function(doc){return!_.has(removesMap,doc._id)})}return _this.localCol.pendingUpserts(function(upserts){var upsertsMap;if(upserts.length>0){upsertsMap=_.object(_.map(upserts,function(u){return u.doc._id}),_.map(upserts,function(u){return u.doc._id}));data=_.filter(data,function(doc){return!_.has(upsertsMap,doc._id)});data=data.concat(_.pluck(upserts,"doc"));data=processFind(data,selector,options)}if(!options.interim||!_.isEqual(localData,data)){return success(data)}},error)},error)}};remoteError=function(err){if(timer){clearTimeout(timer)}if(timedOut){return}if(!options.interim){if(options.useLocalOnRemoteError){return success(localData)}else{if(error){return error(err)}}}else{}};if(options.timeout){timer=setTimeout(function(){timer=null;timedOut=true;if(!options.interim){if(options.useLocalOnRemoteError){return _this.localCol.find(selector,options).fetch(success,error)}else{if(error){return error(new Error("Remote timed out"))}}}else{}},options.timeout)}return _this.remoteCol.find(selector,remoteOptions).fetch(remoteSuccess,remoteError)}}(this);localSuccess=function(localData){if(options.interim){success(localData)}return step2(localData)};return this.localCol.find(selector,options).fetch(localSuccess,error)};HybridCollection.prototype.upsert=function(docs,bases,success,error){return this.localCol.upsert(docs,bases,function(result){if(_.isFunction(bases)){success=bases}return typeof success==="function"?success(docs):void 0},error)};HybridCollection.prototype.remove=function(id,success,error){return this.localCol.remove(id,function(){if(success!=null){return success()}},error)};HybridCollection.prototype.upload=function(success,error){var uploadRemoves,uploadUpserts;uploadUpserts=function(_this){return function(upserts,success,error){var upsert;upsert=_.first(upserts);if(upsert){return _this.remoteCol.upsert(upsert.doc,upsert.base,function(remoteDoc){return _this.localCol.resolveUpserts([upsert],function(){if(remoteDoc){return _this.localCol.cacheOne(remoteDoc,function(){return uploadUpserts(_.rest(upserts),success,error)},error)}else{return _this.localCol.remove(upsert.doc._id,function(){return _this.localCol.resolveRemove(upsert.doc._id,function(){return uploadUpserts(_.rest(upserts),success,error)},error)},error)}},error)},function(err){if(err.status===410||err.status===403){return _this.localCol.remove(upsert.doc._id,function(){return _this.localCol.resolveRemove(upsert.doc._id,function(){if(err.status===410){return uploadUpserts(_.rest(upserts),success,error)}else{return error(err)}},error)},error)}else{return error(err)}})}else{return success()}}}(this);uploadRemoves=function(_this){return function(removes,success,error){var remove;remove=_.first(removes);if(remove){return _this.remoteCol.remove(remove,function(){return _this.localCol.resolveRemove(remove,function(){return uploadRemoves(_.rest(removes),success,error)},error)},function(err){if(err.status===410||err.status===403){return _this.localCol.resolveRemove(remove,function(){if(err.status===410){return uploadRemoves(_.rest(removes),success,error)}else{return error(err)}},error)}else{return error(err)}},error)}else{return success()}}}(this);return this.localCol.pendingUpserts(function(_this){return function(upserts){if(_this.options.sortUpserts){upserts.sort(function(u1,u2){return _this.options.sortUpserts(u1.doc,u2.doc)})}return uploadUpserts(upserts,function(){return _this.localCol.pendingRemoves(function(removes){return uploadRemoves(removes,success,error)},error)},error)}}(this),error)};return HybridCollection}()},function(module,exports){module.exports=$},function(module,exports,__webpack_require__){var compileSort,hashRows,sha1,shardLength,_;_=__webpack_require__(1);sha1=__webpack_require__(38);compileSort=__webpack_require__(2).compileSort;shardLength=2;exports.encodeRequest=function(clientRows){var request;clientRows=_.groupBy(clientRows,function(row){return row._id.substr(0,shardLength)});request=_.mapValues(clientRows,function(rows){return hashRows(rows)});return request};exports.encodeResponse=function(serverRows,encodedRequest){var key,response,value;serverRows=_.groupBy(serverRows,function(row){return row._id.substr(0,shardLength)});for(key in encodedRequest){value=encodedRequest[key];if(!serverRows[key]){serverRows[key]=[]}}response=_.pick(serverRows,function(rows,key){return hashRows(rows)!==encodedRequest[key]});return response};exports.decodeResponse=function(encodedResponse,clientRows,sort){var serverRows;clientRows=_.groupBy(clientRows,function(row){return row._id.substr(0,shardLength)});serverRows=_.extend(clientRows,encodedResponse);serverRows=_.flatten(_.values(serverRows));if(sort){serverRows.sort(compileSort(sort))}else{serverRows=_.sortBy(serverRows,"_id")}return serverRows};hashRows=function(rows){var hash,row,_i,_len,_ref;hash=sha1.create();_ref=_.sortBy(rows,"_id");for(_i=0,_len=_ref.length;_i<_len;_i++){row=_ref[_i];hash.update(row._id+":"+(row._rev||"")+"|")}return hash.hex().substr(0,20)}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(19)},function(module,exports,__webpack_require__){exports.MemoryDb=__webpack_require__(10);exports.LocalStorageDb=__webpack_require__(14);exports.IndexedDb=__webpack_require__(12);exports.WebSQLDb=__webpack_require__(13);exports.RemoteDb=__webpack_require__(36);exports.HybridDb=__webpack_require__(15);exports.ReplicatingDb=__webpack_require__(40);exports.quickfind=__webpack_require__(17);exports.utils=__webpack_require__(0)},function(module,exports,__webpack_require__){(function(global){var apply=Function.prototype.apply;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){if(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)};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)}};__webpack_require__(21);exports.setImmediate=typeof self!=="undefined"&&self.setImmediate||typeof global!=="undefined"&&global.setImmediate||this&&this.setImmediate;exports.clearImmediate=typeof self!=="undefined"&&self.clearImmediate||typeof global!=="undefined"&&global.clearImmediate||this&&this.clearImmediate}).call(exports,__webpack_require__(6))},function(module,exports,__webpack_require__){(function(global,process){(function(global,undefined){"use strict";if(global.setImmediate){return}var nextHandle=1;var tasksByHandle={};var currentlyRunningATask=false;var doc=global.document;var registerImmediate;function setImmediate(callback){if(typeof callback!=="function"){callback=new Function(""+callback)}var args=new Array(arguments.length-1);for(var i=0;i<args.length;i++){args[i]=arguments[i+1]}var task={callback:callback,args:args};tasksByHandle[nextHandle]=task;registerImmediate(nextHandle);return nextHandle++}function clearImmediate(handle){delete tasksByHandle[handle]}function run(task){var callback=task.callback;var args=task.args;switch(args.length){case 0:callback();break;case 1:callback(args[0]);break;case 2:callback(args[0],args[1]);break;case 3:callback(args[0],args[1],args[2]);break;default:callback.apply(undefined,args);break}}function runIfPresent(handle){if(currentlyRunningATask){setTimeout(runIfPresent,0,handle)}else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=true;try{run(task)}finally{clearImmediate(handle);currentlyRunningATask=false}}}}function installNextTickImplementation(){registerImmediate=function(handle){process.nextTick(function(){runIfPresent(handle)})}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=true;var oldOnMessage=global.onmessage;global.onmessage=function(){postMessageIsAsynchronous=false};global.postMessage("","*");global.onmessage=oldOnMessage;return postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$";var onGlobalMessage=function(event){if(event.source===global&&typeof event.data==="string"&&event.data.indexOf(messagePrefix)===0){runIfPresent(+event.data.slice(messagePrefix.length))}};if(global.addEventListener){global.addEventListener("message",onGlobalMessage,false)}else{global.attachEvent("onmessage",onGlobalMessage)}registerImmediate=function(handle){global.postMessage(messagePrefix+handle,"*")}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)};registerImmediate=function(handle){channel.port2.postMessage(handle)}}function installReadyStateChangeImplementation(){var html=doc.documentElement;registerImmediate=function(handle){var script=doc.createElement("script");script.onreadystatechange=function(){runIfPresent(handle);script.onreadystatechange=null;html.removeChild(script);script=null};html.appendChild(script)}}function installSetTimeoutImplementation(){registerImmediate=function(handle){setTimeout(runIfPresent,0,handle)}}var attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global;if({}.toString.call(global.process)==="[object process]"){installNextTickImplementation()}else if(canUsePostMessage()){installPostMessageImplementation()}else if(global.MessageChannel){installMessageChannelImplementation()}else if(doc&&"onreadystatechange"in doc.createElement("script")){installReadyStateChangeImplementation()}else{installSetTimeoutImplementation()}attachTo.setImmediate=setImmediate;attachTo.clearImmediate=clearImmediate})(typeof self==="undefined"?typeof global==="undefined"?this:global:self)}).call(exports,__webpack_require__(6),__webpack_require__(8))},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__;/*!
* Bowser - a browser detector
* https://github.com/ded/bowser
* MIT License | (c) Dustin Diaz 2014
*/
!function(name,definition){if(typeof module!="undefined"&&module.exports)module.exports["browser"]=definition();else if(true)!(__WEBPACK_AMD_DEFINE_FACTORY__=definition,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.call(exports,__webpack_require__,exports,module):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__));else this[name]=definition()}("bowser",function(){var t=true;function detect(ua){function getFirstMatch(regex){var match=ua.match(regex);return match&&match.length>1&&match[1]||""}function getSecondMatch(regex){var match=ua.match(regex);return match&&match.length>1&&match[2]||""}var iosdevice=getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase(),likeAndroid=/like android/i.test(ua),android=!likeAndroid&&/android/i.test(ua),edgeVersion=getFirstMatch(/edge\/(\d+(\.\d+)?)/i),versionIdentifier=getFirstMatch(/version\/(\d+(\.\d+)?)/i),tablet=/tablet/i.test(ua),mobile=!tablet&&/[^-]mobi/i.test(ua),result;if(/opera|opr/i.test(ua)){result={name:"Opera",opera:t,version:versionIdentifier||getFirstMatch(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}}else if(/windows phone/i.test(ua)){result={name:"Windows Phone",windowsphone:t};if(edgeVersion){result.msedge=t;result.version=edgeVersion}else{result.msie=t;result.version=getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i)}}else if(/msie|trident/i.test(ua)){result={name:"Internet Explorer",msie:t,version:getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i)}}else if(/chrome.+? edge/i.test(ua)){result={name:"Microsoft Edge",msedge:t,version:edgeVersion}}else if(/chrome|crios|crmo/i.test(ua)){result={name:"Chrome",chrome:t,version:getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}}else if(iosdevice){result={name:iosdevice=="iphone"?"iPhone":iosdevice=="ipad"?"iPad":"iPod"};if(versionIdentifier){result.version=versionIdentifier}}else if(/sailfish/i.test(ua)){result={name:"Sailfish",sailfish:t,version:getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}}else if(/seamonkey\//i.test(ua)){result={name:"SeaMonkey",seamonkey:t,version:getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i)}}else if(/firefox|iceweasel/i.test(ua)){result={name:"Firefox",firefox:t,version:getFirstMatch(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)};if(/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)){result.firefoxos=t}}else if(/silk/i.test(ua)){result={name:"Amazon Silk",silk:t,version:getFirstMatch(/silk\/(\d+(\.\d+)?)/i)}}else if(android){result={name:"Android",version:versionIdentifier}}else if(/phantom/i.test(ua)){result={name:"PhantomJS",phantom:t,version:getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i)}}else if(/blackberry|\bbb\d+/i.test(ua)||/rim\stablet/i.test(ua)){result={name:"BlackBerry",blackberry:t,version:versionIdentifier||getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}}else if(/(web|hpw)os/i.test(ua)){result={name:"WebOS",webos:t,version:versionIdentifier||getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)};/touchpad\//i.test(ua)&&(result.touchpad=t)}else if(/bada/i.test(ua)){result={name:"Bada",bada:t,version:getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i)}}else if(/tizen/i.test(ua)){result={name:"Tizen",tizen:t,version:getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||versionIdentifier}}else if(/safari/i.test(ua)){result={name:"Safari",safari:t,version:versionIdentifier}}else{result={name:getFirstMatch(/^(.*)\/(.*) /),version:getSecondMatch(/^(.*)\/(.*) /)}}if(!result.msedge&&/(apple)?webkit/i.test(ua)){result.name=result.name||"Webkit";result.webkit=t;if(!result.version&&versionIdentifier){result.version=versionIdentifier}}else if(!result.opera&&/gecko\//i.test(ua)){result.name=result.name||"Gecko";result.gecko=t;result.version=result.version||getFirstMatch(/gecko\/(\d+(\.\d+)?)/i)}if(!result.msedge&&(android||result.silk)){result.android=t}else if(iosdevice){result[iosdevice]=t;result.ios=t}var osVersion="";if(result.windowsphone){osVersion=getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i)}else if(iosdevice){osVersion=getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i);osVersion=osVersion.replace(/[_\s]/g,".")}else if(android){osVersion=getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i)}else if(result.webos){osVersion=getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i)}else if(result.blackberry){osVersion=getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i)}else if(result.bada){osVersion=getFirstMatch(/bada\/(\d+(\.\d+)*)/i)}else if(result.tizen){osVersion=getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i)}if(osVersion){result.osversion=osVersion}var osMajorVersion=osVersion.split(".")[0];if(tablet||iosdevice=="ipad"||android&&(osMajorVersion==3||osMajorVersion==4&&!mobile)||result.silk){result.tablet=t}else if(mobile||iosdevice=="iphone"||iosdevice=="ipod"||android||result.blackberry||result.webos||result.bada){result.mobile=t}if(result.msedge||result.msie&&result.version>=10||result.chrome&&result.version>=20||result.firefox&&result.version>=20||result.safari&&result.version>=6||result.opera&&result.version>=10||result.ios&&result.osversion&&result.osversion.split(".")[0]>=6||result.blackberry&&result.version>=10.1){result.a=t}else if(result.msie&&result.version<10||result.chrome&&result.version<20||result.firefox&&result.version<20||result.safari&&result.version<6||result.opera&&result.version<10||result.ios&&result.osversion&&result.osversion.split(".")[0]<6){result.c=t}else result.x=t;return result}var bowser=detect(typeof navigator!=="undefined"?navigator.userAgent:"");bowser.test=function(browserList){for(var i=0;i<browserList.length;++i){var browserItem=browserList[i];if(typeof browserItem==="string"){if(browserItem in bowser){return true}}}return false};bowser._detect=detect;return bowser})},function(module,exports,__webpack_require__){var _=__webpack_require__(1);EJSON={};var customTypes={};EJSON.addType=function(name,factory){if(_.has(customTypes,name))throw new Error("Type "+name+" already present");customTypes[name]=factory};var builtinConverters=[{matchJSONValue:function(obj){return _.has(obj,"$date")&&_.size(obj)===1},matchObject:function(obj){return obj instanceof Date},toJSONValue:function(obj){return{$date:obj.getTime()}},fromJSONValue:function(obj){return new Date(obj.$date)}},{matchJSONValue:function(obj){return _.has(obj,"$binary")&&_.size(obj)===1},matchObject:function(obj){return typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&_.has(obj,"$Uint8ArrayPolyfill")},toJSONValue:function(obj){return{$binary:EJSON._base64Encode(obj)}},fromJSONValue:function(obj){return EJSON._base64Decode(obj.$binary)}},{matchJSONValue:function(obj){return _.has(obj,"$escape")&&_.size(obj)===1},matchObject:function(obj){if(_.isEmpty(obj)||_.size(obj)>2){return false}return _.any(builtinConverters,function(converter){return converter.matchJSONValue(obj)})},toJSONValue:function(obj){var newObj={};_.each(obj,function(value,key){newObj[key]=EJSON.toJSONValue(value)});return{$escape:newObj}},fromJSONValue:function(obj){var newObj={};_.each(obj.$escape,function(value,key){newObj[key]=EJSON.fromJSONValue(value)});return newObj}},{matchJSONValue:function(obj){return _.has(obj,"$type")&&_.has(obj,"$value")&&_.size(obj)===2},matchObject:function(obj){return EJSON._isCustomType(obj)},toJSONValue:function(obj){return{$type:obj.typeName(),$value:obj.toJSONValue()}},fromJSONValue:function(obj){var typeName=obj.$type;var converter=customTypes[typeName];return converter(obj.$value)}}];EJSON._isCustomType=function(obj){return obj&&typeof obj.toJSONValue==="function"&&typeof obj.typeName==="function"&&_.has(customTypes,obj.typeName())};var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(obj){if(obj===null)return null;var maybeChanged=toJSONValueHelper(obj);if(maybeChanged!==undefined)return maybeChanged;_.each(obj,function(value,key){if(typeof value!=="object"&&value!==undefined)return;var changed=toJSONValueHelper(value);if(changed){obj[key]=changed;return}adjustTypesToJSONValue(value)});return obj};var toJSONValueHelper=function(item){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchObject(item)){return converter.toJSONValue(item)}}return undefined};EJSON.toJSONValue=function(item){var changed=toJSONValueHelper(item);if(changed!==undefined)return changed;if(typeof item==="object"){item=EJSON.clone(item);adjustTypesToJSONValue(item)}return item};var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(obj){if(obj===null)return null;var maybeChanged=fromJSONValueHelper(obj);if(maybeChanged!==obj)return maybeChanged;_.each(obj,function(value,key){if(typeof value==="object"){var changed=fromJSONValueHelper(value);if(value!==changed){obj[key]=changed;return}adjustTypesFromJSONValue(value)}});return obj};var fromJSONValueHelper=function(value){if(typeof value==="object"&&value!==null){if(_.size(value)<=2&&_.all(value,function(v,k){return typeof k==="string"&&k.substr(0,1)==="$"})){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchJSONValue(value)){return converter.fromJSONValue(value)}}}}return value};EJSON.fromJSONValue=function(item){var changed=fromJSONValueHelper(item);if(changed===item&&typeof item==="object"){item=EJSON.clone(item);adjustTypesFromJSONValue(item);return item}else{return changed}};EJSON.stringify=function(item){return JSON.stringify(EJSON.toJSONValue(item))};EJSON.parse=function(item){return EJSON.fromJSONValue(JSON.parse(item))};EJSON.isBinary=function(obj){return typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&obj.$Uint8ArrayPolyfill};EJSON.equals=function(a,b,options){var i;var keyOrderSensitive=!!(options&&options.keyOrderSensitive);if(a===b)return true;if(!a||!b)return false;if(!(typeof a==="object"&&typeof b==="object"))return false;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(a[i]!==b[i])return false}return true}if(typeof a.equals==="function")return a.equals(b,options);if(a instanceof Array){if(!(b instanceof Array))return false;if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(!EJSON.equals(a[i],b[i],options))return false}return true}var ret;if(keyOrderSensitive){var bKeys=[];_.each(b,function(val,x){bKeys.push(x)});i=0;ret=_.all(a,function(val,x){if(i>=bKeys.length){return false}if(x!==bKeys[i]){return false}if(!EJSON.equals(val,b[bKeys[i]],options)){return false}i++;return true});return ret&&i===bKeys.length}else{i=0;ret=_.all(a,function(val,key){if(!_.has(b,key)){return false}if(!EJSON.equals(val,b[key],options)){return false}i++;return true});return ret&&_.size(b)===i}};EJSON.clone=function(v){var ret;if(typeof v!=="object")return v;if(v===null)return null;if(v instanceof Date)return new Date(v.getTime());if(EJSON.isBinary(v)){ret=EJSON.newBinary(v.length);for(var i=0;i<v.length;i++){ret[i]=v[i]}return ret}if(_.isArray(v)||_.isArguments(v)){ret=[];for(i=0;i<v.length;i++)ret[i]=EJSON.clone(v[i]);return ret}if(typeof v.clone==="function"){return v.clone()}ret={};_.each(v,function(value,key){ret[key]=EJSON.clone(value)});return ret};module.exports=EJSON},function(module,exports,__webpack_require__){"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=__webpack_require__(4);var invariant_1=__webpack_require__(3);var martinez=__importStar(__webpack_require__(25));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=[];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")}}}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"){return intersect(geom2,geom1)}else{throw new Error("poly1 and poly2 must be either polygons or multiPolygons")}}exports.default=intersect},function(module,exports,__webpack_require__){/**
* 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){true?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){if(gp){if(gp.left===p){if(p.right){gp.left=p.right;gp.left.parent=gp}else{gp.left=null}p.right=gp;gp.parent=p}else{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{if(gp){if(gp.right===p){if(p.left){gp.right=p.left;gp.right.parent=gp}else{gp.right=null}p.left=gp;gp.parent=p}else{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};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--};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};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};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};SplayTree.prototype.forEach=function forEach(callback){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();callback(current,i++);current=current.right}else{done=true}}}return this};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}}node=node.right}}return this};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};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};SplayTree.prototype.at=function at(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};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};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;function computeFields(event,prev,operation){if(prev===null){event.inOut=false;event.otherInOut=true}else{if(event.isSubject===prev.isSubject){event.inOut=!prev.inOut;event.otherInOut=prev.otherInOut}else{event.inOut=!prev.otherInOut;event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut}if(prev){event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev}}event.inResult=inResult(event,operation)}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;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}var SweepEvent=function SweepEvent(point,left,otherEvent,isSubject,edgeType){this.left=left;this.point=point;this.otherEvent=otherEvent;this.isSubject=isSubject;this.type=edgeType||NORMAL;this.inOut=false;this.otherInOut=false;this.prevInResult=null;this.inResult=false;this.resultInOut=false;this.isExteriorRing=true};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:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0};SweepEvent.prototype.isAbove=function isAbove(p){return!this.isBelow(p)};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}function signedArea(p0,p1,p2){return(p0[0]-p2[0])*(p1[1]-p2[1])-(p1[0]-p2[0])*(p0[1]-p2[1])}function compareEvents(e1,e2){var p1=e1.point;var p2=e2.point;if(p1[0]>p2[0]){return 1}if(p1[0]<p2[0]){return-1}if(p1[1]!==p2[1]){return p1[1]>p2[1]?1:-1}return specialCases(e1,e2,p1,p2)}function specialCases(e1,e2,p1,p2){if(e1.left!==e2.left){return e1.left?1:-1}if(signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)!==0){return!e1.isBelow(e2.otherEvent.point)?1:-1}return!e1.isSubject&&e2.isSubject?1:-1}function divideSegment(se,p,queue){var r=new SweepEvent(p,false,se,se.isSubject);var l=new SweepEvent(p,true,se.otherEvent,se.isSubject);if(equals(se.point,se.otherEvent.point)){console.warn("what is that, a collapsed segment?",se)}r.contourId=l.contourId=se.contourId;if(compareEvents(l,se.otherEvent)>0){se.otherEvent.left=true;l.left=false}se.otherEvent.otherEvent=l;se.otherEvent=r;queue.push(l);queue.push(r);return queue}function crossProduct(a,b){return a[0]*b[1]-a[1]*b[0]}function dotProduct(a,b){return a[0]*b[0]+a[1]*b[1]}function intersection(a1,a2,b1,b2,noEndpointTouch){var va=[a2[0]-a1[0],a2[1]-a1[1]];var vb=[b2[0]-b1[0],b2[1]-b1[1]];function toPoint(p,s,d){return[p[0]+s*d[0],p[1]+s*d[1]]}var e=[b1[0]-a1[0],b1[1]-a1[1]];var kross=crossProduct(va,vb);var sqrKross=kross*kross;var sqrLenA=dotProduct(va,va);if(sqrKross>0){var s=crossProduct(e,vb)/kross;if(s<0||s>1){return null}var t=crossProduct(e,va)/kross;if(t<0||t>1){return null}if(s===0||s===1){return noEndpointTouch?null:[toPoint(a1,s,va)]}if(t===0||t===1){return noEndpointTouch?null:[toPoint(b1,t,vb)]}return[toPoint(a1,s,va)]}kross=crossProduct(e,va);sqrKross=kross*kross;if(sqrKross>0){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);if(smin<=1&&smax>=0){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}return[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]}return null}function possibleIntersection(se1,se2,queue){var inter=intersection(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point);var nintersections=inter?inter.length:0;if(nintersections===0){return 0}if(nintersections===1&&(equals(se1.point,se2.point)||equals(se1.otherEvent.point,se2.otherEvent.point))){return 0}if(nintersections===2&&se1.isSubject===se2.isSubject){return 0}if(nintersections===1){if(!equals(se1.point,inter[0])&&!equals(se1.otherEvent.point,inter[0])){divideSegment(se1,inter[0],queue)}if(!equals(se2.point,inter[0])&&!equals(se2.otherEvent.point,inter[0])){divideSegment(se2,inter[0],queue)}return 1}var events=[];var leftCoincide=false;var rightCoincide=false;if(equals(se1.point,se2.point)){leftCoincide=true}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){se2.type=NON_CONTRIBUTING;se1.type=se2.inOut===se1.inOut?SAME_TRANSITION:DIFFERENT_TRANSITION;if(leftCoincide&&!rightCoincide){divideSegment(events[1].otherEvent,events[0].point,queue)}return 2}if(rightCoincide){divideSegment(events[0],events[1].point,queue);return 3}if(events[0]!==events[3].otherEvent){divideSegment(events[0],events[1].point,queue);divideSegment(events[1],events[2].point,queue);return 3}divideSegment(events[0],events[1].point,queue);divideSegment(events[3].otherEvent,events[2].point,queue);return 3}function compareSegments(le1,le2){if(le1===le2){return 0}if(signedArea(le1.point,le1.otherEvent.point,le2.point)!==0||signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point)!==0){if(equals(le1.point,le2.point)){return le1.isBelow(le2.otherEvent.point)?-1:1}if(le1.point[0]===le2.point[0]){return le1.point[1]<le2.point[1]?-1:1}if(compareEvents(le1,le2)===1){return le2.isAbove(le1.point)?-1:1}return le1.isBelow(le2.point)?-1:1}if(le1.isSubject===le2.isSubject){var p1=le1.point,p2=le2.point;if(p1[0]===p2[0]&&p1[1]===p2[1]){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{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);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}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)}}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}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}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(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}function connectEdges(sortedEvents,operation){var i,len;var resultEvents=orderEvents(sortedEvents);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}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}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);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;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];var eventQueue=fillQueue(subject,clipping,sbbox,cbbox,operation);trivial=compareBBoxes(subject,clipping,sbbox,cbbox,operation);if(trivial){return trivial===EMPTY?null:trivial}var sortedEvents=subdivide(eventQueue,subject,clipping,sbbox,cbbox,operation);var result=connectEdges(sortedEvents,operation);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)}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})})},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var line_intersect_1=__webpack_require__(27);var polygon_to_line_1=__webpack_require__(32);var boolean_point_in_polygon_1=__webpack_require__(9);var invariant_1=__webpack_require__(3);var helpers_1=__webpack_require__(4);function booleanCrosses(feature1,feature2){var type1=invariant_1.getType(feature1);var type2=invariant_1.getType(feature2);var geom1=invariant_1.getGeom(feature1);var geom2=invariant_1.getGeom(feature2);switch(type1){case"MultiPoint":switch(type2){case"LineString":return doMultiPointAndLineStringCross(geom1,geom2);case"Polygon":return doesMultiPointCrossPoly(geom1,geom2);default:throw new Error("feature2 "+type2+" geometry not supported")}case"LineString":switch(type2){case"MultiPoint":return doMultiPointAndLineStringCross(geom2,geom1);case"LineString":return doLineStringsCross(geom1,geom2);case"Polygon":return doLineStringAndPolygonCross(geom1,geom2);default:throw new Error("feature2 "+type2+" geometry not supported")}case"Polygon":switch(type2){case"MultiPoint":return doesMultiPointCrossPoly(geom2,geom1);case"LineString":return doLineStringAndPolygonCross(geom2,geom1);default:throw new Error("feature2 "+type2+" geometry not supported")}default:throw new Error("feature1 "+type1+" geometry not supported")}}function doMultiPointAndLineStringCross(multiPoint,lineString){var foundIntPoint=false;var foundExtPoint=false;var pointLength=multiPoint.coordinates.length;var i=0;while(i<pointLength&&!foundIntPoint&&!foundExtPoint){for(var i2=0;i2<lineString.coordinates.length-1;i2++){var incEndVertices=true;if(i2===0||i2===lineString.coordinates.length-2){incEndVertices=false}if(isPointOnLineSegment(lineString.coordinates[i2],lineString.coordinates[i2+1],multiPoint.coordinates[i],incEndVertices)){foundIntPoint=true}else{foundExtPoint=true}}i++}return foundIntPoint&&foundExtPoint}function doLineStringsCross(lineString1,lineString2){var doLinesIntersect=line_intersect_1.default(lineString1,lineString2);if(doLinesIntersect.features.length>0){for(var i=0;i<lineString1.coordinates.length-1;i++){for(var i2=0;i2<lineString2.coordinates.length-1;i2++){var incEndVertices=true;if(i2===0||i2===lineString2.coordinates.length-2){incEndVertices=false}if(isPointOnLineSegment(lineString1.coordinates[i],lineString1.coordinates[i+1],lineString2.coordinates[i2],incEndVertices)){return true}}}}return false}function doLineStringAndPolygonCross(lineString,polygon){var line=polygon_to_line_1.polygonToLine(polygon);var doLinesIntersect=line_intersect_1.default(lineString,line);if(doLinesIntersect.features.length>0){return true}return false}function doesMultiPointCrossPoly(multiPoint,polygon){var foundIntPoint=false;var foundExtPoint=false;var pointLength=multiPoint.coordinates[0].length;var i=0;while(i<pointLength&&foundIntPoint&&foundExtPoint){if(boolean_point_in_polygon_1.default(helpers_1.point(multiPoint.coordinates[0][i]),polygon)){foundIntPoint=true}else{foundExtPoint=true}i++}return foundExtPoint&&foundExtPoint}function isPointOnLineSegment(lineSegmentStart,lineSegmentEnd,pt,incEnd){var dxc=pt[0]-lineSegmentStart[0];var dyc=pt[1]-lineSegmentStart[1];var dxl=lineSegmentEnd[0]-lineSegmentStart[0];var dyl=lineSegmentEnd[1]-lineSegmentStart[1];var cross=dxc*dyl-dyc*dxl;if(cross!==0){return false}if(incEnd){if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?lineSegmentStart[0]<=pt[0]&&pt[0]<=lineSegmentEnd[0]:lineSegmentEnd[0]<=pt[0]&&pt[0]<=lineSegmentStart[0]}return dyl>0?lineSegmentStart[1]<=pt[1]&&pt[1]<=lineSegmentEnd[1]:lineSegmentEnd[1]<=pt[1]&&pt[1]<=lineSegmentStart[1]}else{if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?lineSegmentStart[0]<pt[0]&&pt[0]<lineSegmentEnd[0]:lineSegmentEnd[0]<pt[0]&&pt[0]<lineSegmentStart[0]}return dyl>0?lineSegmentStart[1]<pt[1]&&pt[1]<lineSegmentEnd[1]:lineSegmentEnd[1]<pt[1]&&pt[1]<lineSegmentStart[1]}}exports.default=booleanCrosses},function(module,exports,__webpack_require__){"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=__webpack_require__(4);var invariant_1=__webpack_require__(3);var line_segment_1=__importDefault(__webpack_require__(28));var meta_1=__webpack_require__(7);var geojson_rbush_1=__importDefault(__webpack_require__(29));function lineIntersect(line1,line2){var unique={};var results=[];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)}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){var key=invariant_1.getCoords(intersect).join(",");if(!unique[key]){unique[key]=true;results.push(intersect)}}})});return helpers_1.featureCollection(results)}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},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var helpers_1=__webpack_require__(4);var invariant_1=__webpack_require__(3);var meta_1=__webpack_require__(7);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)}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)})})}}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}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},function(module,exports,__webpack_require__){var rbush=__webpack_require__(30);var helpers=__webpack_require__(4);var meta=__webpack_require__(7);var turfBBox=__webpack_require__(11).default;var featureEach=meta.featureEach;var coordEach=meta.coordEach;var polygon=helpers.polygon;var featureCollection=helpers.featureCollection;function geojsonRbush(maxEntries){var tree=rbush(maxEntries);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)};tree.load=function(features){var load=[];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{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)};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)};tree.clear=function(){return rbush.prototype.clear.call(this)};tree.search=function(geojson){var features=rbush.prototype.search.call(this,this.toBBox(geojson));return featureCollection(features)};tree.collides=function(geojson){return rbush.prototype.collides.call(this,this.toBBox(geojson))};tree.all=function(){var features=rbush.prototype.all.call(this);return featureCollection(features)};tree.toJSON=function(){return rbush.prototype.toJSON.call(this)};tree.fromJSON=function(json){return rbush.prototype.fromJSON.call(this,json)};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},function(module,exports,__webpack_require__){"use strict";module.exports=rbush;module.exports.default=rbush;var quickselect=__webpack_require__(31);function rbush(maxEntries,format){if(!(this instanceof rbush))return new rbush(maxEntries,format);this._maxEntries=Math.max(4,maxEntries||9);this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.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}var node=this._build(data.slice(),0,data.length-1,0);if(!this.data.children.length){this.data=node}else if(this.data.height===node.height){this._splitRoot(this.data,node)}else{if(this.data.height<node.height){var tmpNode=this.data;this.data=node;node=tmpNode}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;while(node||path.length){if(!node){node=path.pop();parent=path[path.length-1];i=indexes.pop();goingUp=true}if(node.leaf){index=findItem(item,node.children,equalsFn);if(index!==-1){node.children.splice(index,1);path.push(node);this._condense(path);return this}}if(!goingUp&&!node.leaf&&contains(node,bbox)){path.push(node);indexes.push(i);i=0;parent=node;node=node.children[0]}else if(parent){i++;node=parent.children[i];goingUp=false}else node=null}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){node=createNode(items.slice(left,right+1));calcBBox(node,this.toBBox);return node}if(!height){height=Math.ceil(Math.log(N)/Math.log(M));M=Math.ceil(N/Math.pow(M,height-1))}node=createNode([]);node.leaf=false;node.height=height;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);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;if(enlargement<minEnlargement){minEnlargement=enlargement;minArea=area<minArea?area:minArea;targetNode=child}else if(enlargement===minEnlargement){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=[];var node=this._chooseSubtree(bbox,this.data,level,insertPath);node.children.push(item);extend(node,bbox);while(level>=0){if(insertPath[level].children.length>this._maxEntries){this._split(insertPath,level);level--}else break}this._adjustParentBBoxes(bbox,insertPath,level)},_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){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);if(overlap<minOverlap){minOverlap=overlap;index=i;minArea=area<minArea?area:minArea}else if(overlap===minOverlap){if(area<minArea){minArea=area;index=i}}}return index},_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(xMargin<yMargin)node.children.sort(compareMinX)},_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){for(var i=level;i>=0;i--){extend(path[i],bbox)}},_condense:function(path){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){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}function calcBBox(node,toBBox){distBBox(node,0,node.children.length,toBBox,node)}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}}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)}}},function(module,exports,__webpack_require__){(function(global,factory){true?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=.5*Math.exp(2*z/3);var sd=.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})},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var helpers_1=__webpack_require__(4);var invariant_1=__webpack_require__(3);function default_1(poly,options){if(options===void 0){options={}}var geom=invariant_1.getGeom(poly);if(!options.properties&&poly.type==="Feature"){options.properties=poly.properties}switch(geom.type){case"Polygon":return polygonToLine(geom,options);case"MultiPolygon":return multiPolygonToLine(geom,options);default:throw new Error("invalid poly")}}exports.default=default_1;function polygonToLine(poly,options){if(options===void 0){options={}}var geom=invariant_1.getGeom(poly);var type=geom.type;var coords=geom.coordinates;var properties=options.properties?options.properties:poly.type==="Feature"?poly.properties:{};return coordsToLine(coords,properties)}exports.polygonToLine=polygonToLine;function multiPolygonToLine(multiPoly,options){if(options===void 0){options={}}var geom=invariant_1.getGeom(multiPoly);var type=geom.type;var coords=geom.coordinates;var properties=options.properties?options.properties:multiPoly.type==="Feature"?multiPoly.properties:{};var lines=[];coords.forEach(function(coord){lines.push(coordsToLine(coord,properties))});return helpers_1.featureCollection(lines)}exports.multiPolygonToLine=multiPolygonToLine;function coordsToLine(coords,properties){if(coords.length>1){return helpers_1.multiLineString(coords,properties)}return helpers_1.lineString(coords[0],properties)}exports.coordsToLine=coordsToLine},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var bbox_1=__webpack_require__(11);var boolean_point_on_line_1=__webpack_require__(34);var boolean_point_in_polygon_1=__webpack_require__(9);var invariant_1=__webpack_require__(3);function booleanWithin(feature1,feature2){var type1=invariant_1.getType(feature1);var type2=invariant_1.getType(feature2);var geom1=invariant_1.getGeom(feature1);var geom2=invariant_1.getGeom(feature2);switch(type1){case"Point":switch(type2){case"MultiPoint":return isPointInMultiPoint(geom1,geom2);case"LineString":return boolean_point_on_line_1.default(geom1,geom2,{ignoreEndVertices:true});case"Polygon":case"MultiPolygon":return boolean_point_in_polygon_1.default(geom1,geom2,{ignoreBoundary:true});default:throw new Error("feature2 "+type2+" geometry not supported")}case"MultiPoint":switch(type2){case"MultiPoint":return isMultiPointInMultiPoint(geom1,geom2);case"LineString":return isMultiPointOnLine(geom1,geom2);case"Polygon":case"MultiPolygon":return isMultiPointInPoly(geom1,geom2);default:throw new Error("feature2 "+type2+" geometry not supported")}case"LineString":switch(type2){case"LineString":return isLineOnLine(geom1,geom2);case"Polygon":case"MultiPolygon":return isLineInPoly(geom1,geom2);default:throw new Error("feature2 "+type2+" geometry not supported")}case"Polygon":switch(type2){case"Polygon":case"MultiPolygon":return isPolyInPoly(geom1,geom2);default:throw new Error("feature2 "+type2+" geometry not supported")}default:throw new Error("feature1 "+type1+" geometry not supported")}}function isPointInMultiPoint(point,multiPoint){var i;var output=false;for(i=0;i<multiPoint.coordinates.length;i++){if(compareCoords(multiPoint.coordinates[i],point.coordinates)){output=true;break}}return output}function isMultiPointInMultiPoint(multiPoint1,multiPoint2){for(var i=0;i<multiPoint1.coordinates.length;i++){var anyMatch=false;for(var i2=0;i2<multiPoint2.coordinates.length;i2++){if(compareCoords(multiPoint1.coordinates[i],multiPoint2.coordinates[i2])){anyMatch=true}}if(!anyMatch){return false}}return true}function isMultiPointOnLine(multiPoint,lineString){var foundInsidePoint=false;for(var i=0;i<multiPoint.coordinates.length;i++){if(!boolean_point_on_line_1.default(multiPoint.coordinates[i],lineString)){return false}if(!foundInsidePoint){foundInsidePoint=boolean_point_on_line_1.default(multiPoint.coordinates[i],lineString,{ignoreEndVertices:true})}}return foundInsidePoint}function isMultiPointInPoly(multiPoint,polygon){var output=true;var oneInside=false;for(var i=0;i<multiPoint.coordinates.length;i++){var isInside=boolean_point_in_polygon_1.default(multiPoint.coordinates[1],polygon);if(!isInside){output=false;break}if(!oneInside){isInside=boolean_point_in_polygon_1.default(multiPoint.coordinates[1],polygon,{ignoreBoundary:true})}}return output&&isInside}function isLineOnLine(lineString1,lineString2){for(var i=0;i<lineString1.coordinates.length;i++){if(!boolean_point_on_line_1.default(lineString1.coordinates[i],lineString2)){return false}}return true}function isLineInPoly(linestring,polygon){var polyBbox=bbox_1.default(polygon);var lineBbox=bbox_1.default(linestring);if(!doBBoxOverlap(polyBbox,lineBbox)){return false}var foundInsidePoint=false;for(var i=0;i<linestring.coordinates.length-1;i++){if(!boolean_point_in_polygon_1.default(linestring.coordinates[i],polygon)){return false}if(!foundInsidePoint){foundInsidePoint=boolean_point_in_polygon_1.default(linestring.coordinates[i],polygon,{ignoreBoundary:true})}if(!foundInsidePoint){var midpoint=getMidpoint(linestring.coordinates[i],linestring.coordinates[i+1]);foundInsidePoint=boolean_point_in_polygon_1.default(midpoint,polygon,{ignoreBoundary:true})}}return foundInsidePoint}function isPolyInPoly(feature1,feature2){var poly1Bbox=bbox_1.default(feature1);var poly2Bbox=bbox_1.default(feature2);if(!doBBoxOverlap(poly2Bbox,poly1Bbox)){return false}for(var i=0;i<feature1.coordinates[0].length;i++){if(!boolean_point_in_polygon_1.default(feature1.coordinates[0][i],feature2)){return false}}return true}function doBBoxOverlap(bbox1,bbox2){if(bbox1[0]>bbox2[0])return false;if(bbox1[2]<bbox2[2])return false;if(bbox1[1]>bbox2[1])return false;if(bbox1[3]<bbox2[3])return false;return true}function compareCoords(pair1,pair2){return pair1[0]===pair2[0]&&pair1[1]===pair2[1]}function getMidpoint(pair1,pair2){return[(pair1[0]+pair2[0])/2,(pair1[1]+pair2[1])/2]}exports.default=booleanWithin},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var invariant_1=__webpack_require__(3);function booleanPointOnLine(pt,line,options){if(options===void 0){options={}}var ptCoords=invariant_1.getCoord(pt);var lineCoords=invariant_1.getCoords(line);for(var i=0;i<lineCoords.length-1;i++){var ignoreBoundary=false;if(options.ignoreEndVertices){if(i===0){ignoreBoundary="start"}if(i===lineCoords.length-2){ignoreBoundary="end"}if(i===0&&i+1===lineCoords.length-1){ignoreBoundary="both"}}if(isPointOnLineSegment(lineCoords[i],lineCoords[i+1],ptCoords,ignoreBoundary)){return true}}return false}function isPointOnLineSegment(lineSegmentStart,lineSegmentEnd,pt,excludeBoundary){var x=pt[0];var y=pt[1];var x1=lineSegmentStart[0];var y1=lineSegmentStart[1];var x2=lineSegmentEnd[0];var y2=lineSegmentEnd[1];var dxc=pt[0]-x1;var dyc=pt[1]-y1;var dxl=x2-x1;var dyl=y2-y1;var cross=dxc*dyl-dyc*dxl;if(cross!==0){return false}if(!excludeBoundary){if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?x1<=x&&x<=x2:x2<=x&&x<=x1}return dyl>0?y1<=y&&y<=y2:y2<=y&&y<=y1}else if(excludeBoundary==="start"){if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?x1<x&&x<=x2:x2<=x&&x<x1}return dyl>0?y1<y&&y<=y2:y2<=y&&y<y1}else if(excludeBoundary==="end"){if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?x1<=x&&x<x2:x2<x&&x<=x1}return dyl>0?y1<=y&&y<y2:y2<y&&y<=y1}else if(excludeBoundary==="both"){if(Math.abs(dxl)>=Math.abs(dyl)){return dxl>0?x1<x&&x<x2:x2<x&&x<x1}return dyl>0?y1<y&&y<y2:y2<y&&y<y1}return false}exports.default=booleanPointOnLine},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__;/**
* @license IDBWrapper - A cross-browser wrapper for IndexedDB
* Version 1.7.1
* Copyright (c) 2011 - 2016 Jens Arps
* http://jensarps.de/
*
* Licensed under the MIT (X11) license
*/
(function(name,definition,global){"use strict";if(true){!(__WEBPACK_AMD_DEFINE_FACTORY__=definition,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.call(exports,__webpack_require__,exports,module):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}else if(typeof module!=="undefined"&&module.exports){module.exports=definition()}else{global[name]=definition()}})("IDBStore",function(){"use strict";var defaultErrorHandler=function(error){throw error};var defaultSuccessHandler=function(){};var defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:true,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]};var IDBStore=function(kwArgs,onStoreReady){if(typeof onStoreReady=="undefined"&&typeof kwArgs=="function"){onStoreReady=kwArgs}if(Object.prototype.toString.call(kwArgs)!="[object Object]"){kwArgs={}}for(var key in defaults){this[key]=typeof kwArgs[key]!="undefined"?kwArgs[key]:defaults[key]}this.dbName=this.storePrefix+this.storeName;this.dbVersion=parseInt(this.dbVersion,10)||1;onStoreReady&&(this.onStoreReady=onStoreReady);var env=typeof window=="object"?window:self;var availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0];this.idb=env[this.implementation];this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange;this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"};this.openDB()};var proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion);var preventSuccessCallback=false;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent)){this.onError(new Error("The version number provided is lower than the existing one."))}else{var error;if(errorEvent.target.error){error=errorEvent.target.error}else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;if("errorCode"in errorEvent.target){errorMessage+=" with error code "+errorEvent.target.errorCode}error=new Error(errorMessage)}this.onError(error)}}.bind(this);openRequest.onsuccess=function(event){if(preventSuccessCallback){return}if(this.db){this.onStoreReady();return}this.db=event.target.result;if(typeof this.db.version=="string"){this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));return}if(!this.db.objectStoreNames.contains(this.storeName)){this.onError(new Error("Object store couldn't be created."));return}var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName){preventSuccessCallback=true;this.onError(new Error("Cannot create index: No index name given."));return}this.normalizeIndexData(indexData);if(this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);var complies=this.indexComplies(actualIndex,indexData);if(!complies){preventSuccessCallback=true;this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else{preventSuccessCallback=true;this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}},this);if(existingIndexes.length){preventSuccessCallback=true;this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))}preventSuccessCallback||this.onStoreReady()}.bind(this);openRequest.onupgradeneeded=function(event){this.db=event.target.result;if(this.db.objectStoreNames.contains(this.storeName)){this.store=event.target.transaction.objectStore(this.storeName)}else{var optionalParameters={autoIncrement:this.autoIncrement};if(this.keyPath!==null){optionalParameters.keyPath=this.keyPath}this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName){preventSuccessCallback=true;this.onError(new Error("Cannot create index: No index name given."))}this.normalizeIndexData(indexData);if(this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);var complies=this.indexComplies(actualIndex,indexData);if(!complies){this.store.deleteIndex(indexName);this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})}existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else{this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})}},this);if(existingIndexes.length){existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess;deleteRequest.onerror=onError}else{onError(new Error("Browser does not support IndexedDB deleteDatabase!"))}},put:function(key,value,onSuccess,onError){if(this.keyPath!==null){onError=onSuccess;onSuccess=value;value=key}onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null,putRequest;var putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);putTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};putTransaction.onabort=onError;putTransaction.onerror=onError;if(this.keyPath!==null){this._addIdPropertyIfNeeded(value);putRequest=putTransaction.objectStore(this.storeName).put(value)}else{putRequest=putTransaction.objectStore(this.storeName).put(value,key)}putRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};putRequest.onerror=onError;return putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getTransaction.onabort=onError;getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};getRequest.onerror=onError;return getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};removeTransaction.onabort=onError;removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};deleteRequest.onerror=onError;return removeTransaction},batch:function(dataArray,onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);if(Object.prototype.toString.call(dataArray)!="[object Array]"){onError(new Error("dataArray argument must be of type Array."))}else if(dataArray.length===0){return onSuccess(true)}var count=dataArray.length;var called=false;var hasSuccess=false;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(hasSuccess)};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(){count--;if(count===0&&!called){called=true;hasSuccess=true}};dataArray.forEach(function(operation){var type=operation.type;var key=operation.key;var value=operation.value;var onItemError=function(err){batchTransaction.abort();if(!called){called=true;onError(err,type,key)}};if(type=="remove"){var deleteRequest=batchTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=onItemSuccess;deleteRequest.onerror=onItemError}else if(type=="put"){var putRequest;if(this.keyPath!==null){this._addIdPropertyIfNeeded(value);putRequest=batchTransaction.objectStore(this.storeName).put(value)}else{putRequest=batchTransaction.objectStore(this.storeName).put(value,key)}putRequest.onsuccess=onItemSuccess;putRequest.onerror=onItemError}},this);return batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){if(typeof options=="function"){onSuccess=options;onError=onSuccess;options={}}onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);options||(options={});if(Object.prototype.toString.call(dataArray)!="[object Array]"){onError(new Error("dataArray argument must be of type Array."))}var keyField=options.keyField||this.keyPath;var count=dataArray.length;var called=false;var hasSuccess=false;var index=0;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){if(hasSuccess){onSuccess(dataArray)}else{onError(false)}};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(event){var record=dataArray[index++];record[keyField]=event.target.result;count--;if(count===0&&!called){called=true;hasSuccess=true}};dataArray.forEach(function(record){var key=record.key;var onItemError=function(err){batchTransaction.abort();if(!called){called=true;onError(err)}};var putRequest;if(this.keyPath!==null){this._addIdPropertyIfNeeded(record);putRequest=batchTransaction.objectStore(this.storeName).put(record)}else{putRequest=batchTransaction.objectStore(this.storeName).put(record,key)}putRequest.onsuccess=onItemSuccess;putRequest.onerror=onItemError},this);return batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);arrayType||(arrayType="sparse");if(Object.prototype.toString.call(keyArray)!="[object Array]"){onError(new Error("keyArray argument must be of type Array."))}else if(keyArray.length===0){return onSuccess([])}var data=[];var count=keyArray.length;var called=false;var hasSuccess=false;var result=null;var batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};batchTransaction.onabort=onError;batchTransaction.onerror=onError;var onItemSuccess=function(event){if(event.target.result||arrayType=="dense"){data.push(event.target.result)}else if(arrayType=="sparse"){data.length++}count--;if(count===0){called=true;hasSuccess=true;result=data}};keyArray.forEach(function(key){var onItemError=function(err){called=true;result=err;onError(err);batchTransaction.abort()};var getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess;getRequest.onerror=onItemError},this);return batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);var store=getAllTransaction.objectStore(this.storeName);if(store.getAll){this._getAllNative(getAllTransaction,store,onSuccess,onError)}else{this._getAllCursor(getAllTransaction,store,onSuccess,onError)}return getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=false,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getAllTransaction.onabort=onError;getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=false,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};getAllTransaction.onabort=onError;getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor){all.push(cursor.value);cursor["continue"]()}else{hasSuccess=true;result=all}};cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler);onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=false,result=null;var clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};clearTransaction.onabort=onError;clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();clearRequest.onsuccess=function(event){hasSuccess=true;result=event.target.result};clearRequest.onerror=onError;return clearTransaction},_addIdPropertyIfNeeded:function(dataObj){if(typeof dataObj[this.keyPath]=="undefined"){dataObj[this.keyPath]=this._insertIdCount+++Date.now()}},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name;indexData.unique=!!indexData.unique;indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){var complies=["keyPath","unique","multiEntry"].every(function(key){if(key=="multiEntry"&&actual[key]===undefined&&expected[key]===false){return true}if(key=="keyPath"&&Object.prototype.toString.call(expected[key])=="[object Array]"){var exp=expected.keyPath;var act=actual.keyPath;if(typeof act=="string"){return exp.toString()==act}if(!(typeof act.contains=="function"||typeof act.indexOf=="function")){return false}if(act.length!==exp.length){return false}for(var i=0,m=exp.length;i<m;i++){if(!(act.contains&&act.contains(exp[i])||act.indexOf(exp[i]!==-1))){return false}}return true}return expected[key]==actual[key]});return complies},iterate:function(onItem,options){options=mixin({index:null,order:"ASC",autoContinue:true,filterDuplicates:false,keyRange:null,writeAccess:false,onEnd:null,onError:defaultErrorHandler,limit:Infinity,offset:0,allowItemRejection:false},options||{});var directionType=options.order.toLowerCase()=="desc"?"PREV":"NEXT";if(options.filterDuplicates){directionType+="_NO_DUPLICATE"}var hasSuccess=false;var cursorTransaction=this.db.transaction([this.storeName],this.consts[options.writeAccess?"READ_WRITE":"READ_ONLY"]);var cursorTarget=cursorTransaction.objectStore(this.storeName);if(options.index){cursorTarget=cursorTarget.index(options.index)}var recordCount=0;cursorTransaction.oncomplete=function(){if(!hasSuccess){options.onError(null);return}if(options.onEnd){options.onEnd()}else{onItem(null)}};cursorTransaction.onabort=options.onError;cursorTransaction.onerror=options.onError;var cursorRequest=cursorTarget.openCursor(options.keyRange,this.consts[directionType]);cursorRequest.onerror=options.onError;cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor){if(options.offset){cursor.advance(options.offset);options.offset=0}else{var onItemReturn=onItem(cursor.value,cursor,cursorTransaction);if(!options.allowItemRejection||onItemReturn!==false){recordCount++}if(options.autoContinue){if(recordCount+options.offset<options.limit){cursor["continue"]()}else{hasSuccess=true}}}}else{hasSuccess=true}};return cursorTransaction},query:function(onSuccess,options){var result=[],processedItems=0;options=options||{};options.autoContinue=true;options.writeAccess=false;options.allowItemRejection=!!options.filter;options.onEnd=function(){onSuccess(result,processedItems)};return this.iterate(function(item){processedItems++;var accept=options.filter?options.filter(item):true;if(accept!==false){result.push(item)}return accept},options)},count:function(onSuccess,options){options=mixin({index:null,keyRange:null},options||{});var onError=options.onError||defaultErrorHandler;var hasSuccess=false,result=null;var cursorTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);cursorTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)};cursorTransaction.onabort=onError;cursorTransaction.onerror=onError;var cursorTarget=cursorTransaction.objectStore(this.storeName);if(options.index){cursorTarget=cursorTarget.index(options.index)}var countRequest=cursorTarget.count(options.keyRange);countRequest.onsuccess=function(evt){hasSuccess=true;result=evt.target.result};countRequest.onError=onError;return cursorTransaction},makeKeyRange:function(options){var keyRange,hasLower=typeof options.lower!="undefined",hasUpper=typeof options.upper!="undefined",isOnly=typeof options.only!="undefined";switch(true){case isOnly:keyRange=this.keyRange.only(options.only);break;case hasLower&&hasUpper:keyRange=this.keyRange.bound(options.lower,options.upper,options.excludeLower,options.excludeUpper);break;case hasLower:keyRange=this.keyRange.lowerBound(options.lower,options.excludeLower);break;case hasUpper:keyRange=this.keyRange.upperBound(options.upper,options.excludeUpper);break;default:throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.')}return keyRange}};var empty={};function mixin(target,source){var name,s;for(name in source){s=source[name];if(s!==empty[name]&&s!==target[name]){target[name]=s}}return target}function hasVersionError(errorEvent){if("error"in errorEvent.target){return errorEvent.target.error.name=="VersionError"}else if("errorCode"in errorEvent.target){return errorEvent.target.errorCode==12}return false}IDBStore.prototype=proto;IDBStore.version=proto.version;return IDBStore},this)},function(module,exports,__webpack_require__){var $,Collection,RemoteDb,async,jQueryHttpClient,quickfind,utils,_;_=__webpack_require__(1);$=__webpack_require__(16);async=__webpack_require__(5);utils=__webpack_require__(0);jQueryHttpClient=__webpack_require__(37);quickfind=__webpack_require__(17);module.exports=RemoteDb=function(){function RemoteDb(url,client,httpClient,useQuickFind,usePostFind){if(useQuickFind==null){useQuickFind=false}if(usePostFind==null){usePostFind=false}this.url=url;this.client=client;this.collections={};this.httpClient=httpClient;this.useQuickFind=useQuickFind;this.usePostFind=usePostFind}RemoteDb.prototype.addCollection=function(name,options,success,error){var collection,url,usePostFind,useQuickFind,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}if(options.url){url=options.url}else{if(_.isArray(this.url)){url=_.map(this.url,function(url){return url+name})}else{url=this.url+name}}useQuickFind=this.useQuickFind;if(options.useQuickFind!=null){useQuickFind=options.useQuickFind}usePostFind=this.usePostFind;if(options.usePostFind!=null){usePostFind=options.usePostFind}collection=new Collection(name,url,this.client,this.httpClient,useQuickFind,usePostFind);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};RemoteDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};RemoteDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return RemoteDb}();Collection=function(){function Collection(name,url,client,httpClient,useQuickFind,usePostFind){this.name=name;this.url=url;this.client=client;this.httpClient=httpClient||jQueryHttpClient;this.useQuickFind=useQuickFind;this.usePostFind=usePostFind}Collection.prototype.getUrl=function(){var url;if(_.isArray(this.url)){url=this.url.pop();this.url.unshift(url);return url}return this.url};Collection.prototype.find=function(selector,options){if(options==null){options={}}return{fetch:function(_this){return function(success,error){var body,method,params;if(_this.useQuickFind&&options.localData&&(!options.fields||options.fields._rev)&&!(options.limit&&!options.sort&&!options.orderByExprs)){method="quickfind"}else if(_this.usePostFind&&JSON.stringify({selector:selector,sort:options.sort,fields:options.fields}).length>500){method="post"}else{method="get"}if(method==="get"){params={};params.selector=JSON.stringify(selector||{});if(options.sort){params.sort=JSON.stringify(options.sort)}if(options.limit){params.limit=options.limit}if(options.skip){params.skip=options.skip}if(options.fields){params.fields=JSON.stringify(options.fields)}if(options.whereExpr){params.whereExpr=JSON.stringify(options.whereExpr)}if(options.orderByExprs){params.orderByExprs=JSON.stringify(options.orderByExprs)}if(_this.client){params.client=_this.client}if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}_this.httpClient("GET",_this.getUrl(),params,null,success,error);return}body={selector:selector||{}};if(options.sort){body.sort=options.sort}if(options.limit!=null){body.limit=options.limit}if(options.skip!=null){body.skip=options.skip}if(options.fields){body.fields=options.fields}if(options.whereExpr){body.whereExpr=options.whereExpr}if(options.orderByExprs){body.orderByExprs=options.orderByExprs}params={};if(_this.client){params.client=_this.client}if(method==="quickfind"){body.quickfind=quickfind.encodeRequest(options.localData);_this.httpClient("POST",_this.getUrl()+"/quickfind",params,body,function(encodedResponse){return success(quickfind.decodeResponse(encodedResponse,options.localData,options.sort))},error);return}return _this.httpClient("POST",_this.getUrl()+"/find",params,body,function(encodedResponse){return success(quickfind.decodeResponse(encodedResponse,options.localData,options.sort))},error)}}(this)}};Collection.prototype.findOne=function(selector,options,success,error){var params,_ref;if(options==null){options={}}if(_.isFunction(options)){_ref=[{},options,success],options=_ref[0],success=_ref[1],error=_ref[2]}params={};if(options.sort){params.sort=JSON.stringify(options.sort)}params.limit=1;if(this.client){params.client=this.client}params.selector=JSON.stringify(selector||{});if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}return this.httpClient("GET",this.getUrl(),params,null,function(results){if(results&&results.length>0){return success(results[0])}else{return success(null)}},error)};Collection.prototype.upsert=function(docs,bases,success,error){var basesPresent,items,params,results,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];if(!this.client){throw new Error("Client required to upsert")}results=[];basesPresent=_.compact(_.pluck(items,"base")).length>0;params={client:this.client};if(typeof navigator!=="undefined"&&navigator!==null&&navigator.userAgent.toLowerCase().indexOf("android 2.3")!==-1){params._=(new Date).getTime()}if(items.length===1){if(basesPresent){return this.httpClient("PATCH",this.getUrl(),params,items[0],function(result){if(_.isArray(docs)){return success([result])}else{return success(result)}},function(err){if(error){return error(err)}})}else{return this.httpClient("POST",this.getUrl(),params,items[0].doc,function(result){if(_.isArray(docs)){return success([result])}else{return success(result)}},function(err){if(error){return error(err)}})}}else{if(basesPresent){return this.httpClient("PATCH",this.getUrl(),params,{doc:_.pluck(items,"doc"),base:_.pluck(items,"base")},function(result){return success(result)},function(err){if(error){return error(err)}})}else{return this.httpClient("POST",this.getUrl(),params,_.pluck(items,"doc"),function(result){return success(result)},function(err){if(error){return error(err)}})}}};Collection.prototype.remove=function(id,success,error){var params;if(!this.client){throw new Error("Client required to remove")}params={client:this.client};return this.httpClient("DELETE",this.getUrl()+"/"+id,params,null,success,function(err){if(err.status===410){return success()}else{return error(err)}})};return Collection}()},function(module,exports,__webpack_require__){var $;$=__webpack_require__(16);module.exports=function(method,url,params,data,success,error){var fullUrl,req;fullUrl=url+"?"+$.param(params);if(method==="GET"){req=$.ajax(fullUrl,{dataType:"json",timeout:18e4})}else if(method==="DELETE"){req=$.ajax(fullUrl,{type:"DELETE",timeout:6e4})}else if(method==="POST"||method==="PATCH"){req=$.ajax(fullUrl,{data:JSON.stringify(data),contentType:"application/json",timeout:6e4,type:method})}else{throw new Error("Unknown method "+method)}req.done(function(response,textStatus,jqXHR){return success(response||null)});return req.fail(function(jqXHR,textStatus,errorThrown){if(error){return error(jqXHR)}})}},function(module,exports,__webpack_require__){(function(process,global){var __WEBPACK_AMD_DEFINE_RESULT__;/*
* [js-sha1]{@link https://github.com/emn178/js-sha1}
*
* @version 0.6.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*/
(function(){"use strict";var root=typeof window==="object"?window:{};var NODE_JS=!root.JS_SHA1_NO_NODE_JS&&typeof process==="object"&&process.versions&&process.versions.node;if(NODE_JS){root=global}var COMMON_JS=!root.JS_SHA1_NO_COMMON_JS&&typeof module==="object"&&module.exports;var AMD="function"==="function"&&__webpack_require__(39);var HEX_CHARS="0123456789abcdef".split("");var EXTRA=[-2147483648,8388608,32768,128];var SHIFT=[24,16,8,0];var OUTPUT_TYPES=["hex","array","digest","arrayBuffer"];var blocks=[];var createOutputMethod=function(outputType){return function(message){return new Sha1(true).update(message)[outputType]()}};var createMethod=function(){var method=createOutputMethod("hex");if(NODE_JS){method=nodeWrap(method)}method.create=function(){return new Sha1};method.update=function(message){return method.create().update(message)};for(var i=0;i<OUTPUT_TYPES.length;++i){var type=OUTPUT_TYPES[i];method[type]=createOutputMethod(type)}return method};var nodeWrap=function(method){var crypto=eval("require('crypto')");var Buffer=eval("require('buffer').Buffer");var nodeMethod=function(message){if(typeof message==="string"){return crypto.createHash("sha1").update(message,"utf8").digest("hex")}else if(message.constructor===ArrayBuffer){message=new Uint8Array(message)}else if(message.length===undefined){return method(message)}return crypto.createHash("sha1").update(new Buffer(message)).digest("hex")};return nodeMethod};function Sha1(sharedMemory){if(sharedMemory){blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0;this.blocks=blocks}else{this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}this.h0=1732584193;this.h1=4023233417;this.h2=2562383102;this.h3=271733878;this.h4=3285377520;this.block=this.start=this.bytes=this.hBytes=0;this.finalized=this.hashed=false;this.first=true}Sha1.prototype.update=function(message){if(this.finalized){return}var notString=typeof message!=="string";if(notString&&message.constructor===root.ArrayBuffer){message=new Uint8Array(message)}var code,index=0,i,length=message.length||0,blocks=this.blocks;while(index<length){if(this.hashed){this.hashed=false;blocks[0]=this.block;blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0}if(notString){for(i=this.start;index<length&&i<64;++index){blocks[i>>2]|=message[index]<<SHIFT[i++&3]}}else{for(i=this.start;index<length&&i<64;++index){code=message.charCodeAt(index);if(code<128){blocks[i>>2]|=code<<SHIFT[i++&3]}else if(code<2048){blocks[i>>2]|=(192|code>>6)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else if(code<55296||code>=57344){blocks[i>>2]|=(224|code>>12)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}else{code=65536+((code&1023)<<10|message.charCodeAt(++index)&1023);blocks[i>>2]|=(240|code>>18)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>12&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code>>6&63)<<SHIFT[i++&3];blocks[i>>2]|=(128|code&63)<<SHIFT[i++&3]}}}this.lastByteIndex=i;this.bytes+=i-this.start;if(i>=64){this.block=blocks[16];this.start=i-64;this.hash();this.hashed=true}else{this.start=i}}if(this.bytes>4294967295){this.hBytes+=this.bytes/4294967296<<0;this.bytes=this.bytes%4294967296}return this};Sha1.prototype.finalize=function(){if(this.finalized){return}this.finalized=true;var blocks=this.blocks,i=this.lastByteIndex;blocks[16]=this.block;blocks[i>>2]|=EXTRA[i&3];this.block=blocks[16];if(i>=56){if(!this.hashed){this.hash()}blocks[0]=this.block;blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0}blocks[14]=this.hBytes<<3|this.bytes>>>29;blocks[15]=this.bytes<<3;this.hash()};Sha1.prototype.hash=function(){var a=this.h0,b=this.h1,c=this.h2,d=this.h3,e=this.h4;var f,j,t,blocks=this.blocks;for(j=16;j<80;++j){t=blocks[j-3]^blocks[j-8]^blocks[j-14]^blocks[j-16];blocks[j]=t<<1|t>>>31}for(j=0;j<20;j+=5){f=b&c|~b&d;t=a<<5|a>>>27;e=t+f+e+1518500249+blocks[j]<<0;b=b<<30|b>>>2;f=a&b|~a&c;t=e<<5|e>>>27;d=t+f+d+1518500249+blocks[j+1]<<0;a=a<<30|a>>>2;f=e&a|~e&b;t=d<<5|d>>>27;c=t+f+c+1518500249+blocks[j+2]<<0;e=e<<30|e>>>2;f=d&e|~d&a;t=c<<5|c>>>27;b=t+f+b+1518500249+blocks[j+3]<<0;d=d<<30|d>>>2;f=c&d|~c&e;t=b<<5|b>>>27;a=t+f+a+1518500249+blocks[j+4]<<0;c=c<<30|c>>>2}for(;j<40;j+=5){f=b^c^d;t=a<<5|a>>>27;e=t+f+e+1859775393+blocks[j]<<0;b=b<<30|b>>>2;f=a^b^c;t=e<<5|e>>>27;d=t+f+d+1859775393+blocks[j+1]<<0;a=a<<30|a>>>2;f=e^a^b;t=d<<5|d>>>27;c=t+f+c+1859775393+blocks[j+2]<<0;e=e<<30|e>>>2;f=d^e^a;t=c<<5|c>>>27;b=t+f+b+1859775393+blocks[j+3]<<0;d=d<<30|d>>>2;f=c^d^e;t=b<<5|b>>>27;a=t+f+a+1859775393+blocks[j+4]<<0;c=c<<30|c>>>2}for(;j<60;j+=5){f=b&c|b&d|c&d;t=a<<5|a>>>27;e=t+f+e-1894007588+blocks[j]<<0;b=b<<30|b>>>2;f=a&b|a&c|b&c;t=e<<5|e>>>27;d=t+f+d-1894007588+blocks[j+1]<<0;a=a<<30|a>>>2;f=e&a|e&b|a&b;t=d<<5|d>>>27;c=t+f+c-1894007588+blocks[j+2]<<0;e=e<<30|e>>>2;f=d&e|d&a|e&a;t=c<<5|c>>>27;b=t+f+b-1894007588+blocks[j+3]<<0;d=d<<30|d>>>2;f=c&d|c&e|d&e;t=b<<5|b>>>27;a=t+f+a-1894007588+blocks[j+4]<<0;c=c<<30|c>>>2}for(;j<80;j+=5){f=b^c^d;t=a<<5|a>>>27;e=t+f+e-899497514+blocks[j]<<0;b=b<<30|b>>>2;f=a^b^c;t=e<<5|e>>>27;d=t+f+d-899497514+blocks[j+1]<<0;a=a<<30|a>>>2;f=e^a^b;t=d<<5|d>>>27;c=t+f+c-899497514+blocks[j+2]<<0;e=e<<30|e>>>2;f=d^e^a;t=c<<5|c>>>27;b=t+f+b-899497514+blocks[j+3]<<0;d=d<<30|d>>>2;f=c^d^e;t=b<<5|b>>>27;a=t+f+a-899497514+blocks[j+4]<<0;c=c<<30|c>>>2}this.h0=this.h0+a<<0;this.h1=this.h1+b<<0;this.h2=this.h2+c<<0;this.h3=this.h3+d<<0;this.h4=this.h4+e<<0};Sha1.prototype.hex=function(){this.finalize();var h0=this.h0,h1=this.h1,h2=this.h2,h3=this.h3,h4=this.h4;return HEX_CHARS[h0>>28&15]+HEX_CHARS[h0>>24&15]+HEX_CHARS[h0>>20&15]+HEX_CHARS[h0>>16&15]+HEX_CHARS[h0>>12&15]+HEX_CHARS[h0>>8&15]+HEX_CHARS[h0>>4&15]+HEX_CHARS[h0&15]+HEX_CHARS[h1>>28&15]+HEX_CHARS[h1>>24&15]+HEX_CHARS[h1>>20&15]+HEX_CHARS[h1>>16&15]+HEX_CHARS[h1>>12&15]+HEX_CHARS[h1>>8&15]+HEX_CHARS[h1>>4&15]+HEX_CHARS[h1&15]+HEX_CHARS[h2>>28&15]+HEX_CHARS[h2>>24&15]+HEX_CHARS[h2>>20&15]+HEX_CHARS[h2>>16&15]+HEX_CHARS[h2>>12&15]+HEX_CHARS[h2>>8&15]+HEX_CHARS[h2>>4&15]+HEX_CHARS[h2&15]+HEX_CHARS[h3>>28&15]+HEX_CHARS[h3>>24&15]+HEX_CHARS[h3>>20&15]+HEX_CHARS[h3>>16&15]+HEX_CHARS[h3>>12&15]+HEX_CHARS[h3>>8&15]+HEX_CHARS[h3>>4&15]+HEX_CHARS[h3&15]+HEX_CHARS[h4>>28&15]+HEX_CHARS[h4>>24&15]+HEX_CHARS[h4>>20&15]+HEX_CHARS[h4>>16&15]+HEX_CHARS[h4>>12&15]+HEX_CHARS[h4>>8&15]+HEX_CHARS[h4>>4&15]+HEX_CHARS[h4&15]};Sha1.prototype.toString=Sha1.prototype.hex;Sha1.prototype.digest=function(){this.finalize();var h0=this.h0,h1=this.h1,h2=this.h2,h3=this.h3,h4=this.h4;return[h0>>24&255,h0>>16&255,h0>>8&255,h0&255,h1>>24&255,h1>>16&255,h1>>8&255,h1&255,h2>>24&255,h2>>16&255,h2>>8&255,h2&255,h3>>24&255,h3>>16&255,h3>>8&255,h3&255,h4>>24&255,h4>>16&255,h4>>8&255,h4&255]};Sha1.prototype.array=Sha1.prototype.digest;Sha1.prototype.arrayBuffer=function(){this.finalize();var buffer=new ArrayBuffer(20);var dataView=new DataView(buffer);dataView.setUint32(0,this.h0);dataView.setUint32(4,this.h1);dataView.setUint32(8,this.h2);dataView.setUint32(12,this.h3);dataView.setUint32(16,this.h4);return buffer};var exports=createMethod();if(COMMON_JS){module.exports=exports}else{root.sha1=exports;if(AMD){!(__WEBPACK_AMD_DEFINE_RESULT__=function(){return exports}.call(exports,__webpack_require__,exports,module),__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}}})()}).call(exports,__webpack_require__(8),__webpack_require__(6))},function(module,exports){(function(__webpack_amd_options__){module.exports=__webpack_amd_options__}).call(exports,{})},function(module,exports,__webpack_require__){var Collection,ReplicatingDb,compileSort,utils,_;_=__webpack_require__(1);utils=__webpack_require__(0);compileSort=__webpack_require__(2).compileSort;module.exports=ReplicatingDb=function(){function ReplicatingDb(masterDb,replicaDb){this.collections={};this.masterDb=masterDb;this.replicaDb=replicaDb}ReplicatingDb.prototype.addCollection=function(name,success,error){var collection;collection=new Collection(name,this.masterDb[name],this.replicaDb[name]);this[name]=collection;this.collections[name]=collection;if(success!=null){return success()}};ReplicatingDb.prototype.removeCollection=function(name,success,error){delete this[name];delete this.collections[name];if(success!=null){return success()}};ReplicatingDb.prototype.getCollectionNames=function(){return _.keys(this.collections)};return ReplicatingDb}();Collection=function(){function Collection(name,masterCol,replicaCol){this.name=name;this.masterCol=masterCol;this.replicaCol=replicaCol}Collection.prototype.find=function(selector,options){return this.masterCol.find(selector,options)};Collection.prototype.findOne=function(selector,options,success,error){return this.masterCol.findOne(selector,options,success,error)};Collection.prototype.upsert=function(docs,bases,success,error){var items,_ref;_ref=utils.regularizeUpsert(docs,bases,success,error),items=_ref[0],success=_ref[1],error=_ref[2];return this.masterCol.upsert(_.pluck(items,"doc"),_.pluck(items,"base"),function(_this){return function(){return _this.replicaCol.upsert(_.pluck(items,"doc"),_.pluck(items,"base"),function(results){return success(docs)},error)}}(this),error)};Collection.prototype.remove=function(id,success,error){return this.masterCol.remove(id,function(_this){return function(){return _this.replicaCol.remove(id,success,error)}}(this),error)};Collection.prototype.cache=function(docs,selector,options,success,error){var docsMap,sort;docsMap=_.indexBy(docs,"_id");if(options.sort){sort=compileSort(options.sort)}return this.masterCol.find(selector,options).fetch(function(_this){return function(results){var doc,performCaches,performUncaches,result,resultsMap,toCache,toUncache,_i,_j,_len,_len1;resultsMap=_.indexBy(results,"_id");toCache=[];for(_i=0,_len=docs.length;_i<_len;_i++){doc=docs[_i];result=resultsMap[doc._id];if(!result){toCache.push(doc);continue}if(doc._rev&&result._rev&&doc._rev<=result._rev){continue}if(!_.isEqual(doc,result)){toCache.push(doc)}}toUncache=[];for(_j=0,_len1=results.length;_j<_len1;_j++){result=results[_j];if(options.limit&&docs.length===options.limit){if(options.sort&&sort(result,_.last(docs))>=0){continue}if(!options.sort){continue}}if(!docsMap[result._id]){toUncache.push(result._id)}}performCaches=function(next){if(toCache.length>0){return _this.masterCol.cacheList(toCache,function(){return _this.replicaCol.cacheList(toCache,function(){return next()},error)},error)}else{return next()}};performUncaches=function(next){if(toUncache.length>0){return _this.masterCol.uncacheList(toUncache,function(){return _this.replicaCol.uncacheList(toUncache,function(){return next()},error)},error)}else{return next()}};return performCaches(function(){return performUncaches(function(){if(success!=null){success()}})})}}(this),error)};Collection.prototype.pendingUpserts=function(success,error){return this.masterCol.pendingUpserts(success,error)};Collection.prototype.pendingRemoves=function(success,error){return this.masterCol.pendingRemoves(success,error)};Collection.prototype.resolveUpserts=function(upserts,success,error){return this.masterCol.resolveUpserts(upserts,function(_this){return function(){return _this.replicaCol.resolveUpserts(upserts,success,error)}}(this),error)};Collection.prototype.resolveRemove=function(id,success,error){return this.masterCol.resolveRemove(id,function(_this){return function(){return _this.replicaCol.resolveRemove(id,success,error)}}(this),error)};Collection.prototype.seed=function(docs,success,error){return this.masterCol.seed(docs,function(_this){return function(){return _this.replicaCol.seed(docs,success,error)}}(this),error)};Collection.prototype.cacheOne=function(doc,success,error){return this.masterCol.cacheOne(doc,function(_this){return function(){return _this.replicaCol.cacheOne(doc,success,error)}}(this),error)};Collection.prototype.cacheList=function(docs,success,error){return this.masterCol.cacheList(docs,function(_this){return function(){return _this.replicaCol.cacheList(docs,success,error)}}(this),error)};Collection.prototype.uncache=function(selector,success,error){return this.masterCol.uncache(selector,function(_this){return function(){return _this.replicaCol.uncache(selector,success,error)}}(this),error)};Collection.prototype.uncacheList=function(ids,success,error){return this.masterCol.uncacheList(ids,function(_this){return function(){return _this.replicaCol.uncacheList(ids,success,error)}}(this),error)};return Collection}()}]);