!function(global){var exports,isOnline,isOfflineMode,isSynchronizing,logger,_exports_js=((exports={})._stores={},exports.baseUrl="",exports.isProduction=!0,exports.constants={},exports.isBrowser=!0,exports.urlsGraph={},exports.cacheGraph={},exports.isOfflineStrategies=!1,exports.version="",exports.setOptions=function(options){for(option in options)exports[option]=options[option]},exports),_logger_js=function(imports,exports){var exportsLunaris=imports[0];function log(strings,msg,baseMessage,fn){if(!exportsLunaris.IS_PRODUCTION){Array.isArray(strings)||(strings=[strings]);var _message=baseMessage+strings.join(" ");if(!msg)return fn(_message);fn(baseMessage+strings.join(" "),msg)}}return{info:function(strings,msg){return log(strings,msg,"[Lunaris info]",console.log)},warn:function(strings,error){return log(strings,error,"[Lunaris error] ",console.error)},tip:function(strings,tip){return log(strings,tip,"[Lunaris tip] ",console.warn)},deprecated:function(strings,info){return log(strings,info,"[Lunaris deprecated]",console.warn)},debug:function(strings,debug){return log(strings,debug,"[Lunaris debug]",console.log)}}}([_exports_js]),_store_store_hook_js=function(imports,exports){var logger=imports[0],lunarisExports=imports[1];function _extractHookAndStore(hook){var _hook=/(.*)@(.*)/.exec(hook);if(!_hook||_hook.length<3)throw new Error("A hook must be: <event>@<store>");return{event:_hook[1],store:_hook[2]}}function _isFunction(handler){if("function"!=typeof handler)throw new Error("A handler must be a Function")}return exports.hook=function(hook,handler,isUnique,isInternalHook){try{_isFunction(handler);var _hook=_extractHookAndStore(hook),_store=imports[2]._stores[_hook.store];if(!_store)throw new Error('Cannot register hook "'+hook+'", store "'+_hook.store+'" has not been defined!');if(_store.isInternalHooks||(_store.isInternalHooks={}),_store.realHooks||(_store.realHooks={}),_store.hooks[_hook.event]||(_store.hooks[_hook.event]=[],_store.realHooks[_hook.event]=[],_store.isInternalHooks[_hook.event]=[]),isUnique){for(var _handlers=_store.realHooks[_hook.event],_hasBeenFound=!1,i=0;i<_handlers.length;i++)if(_handlers[i].toString()===handler.toString()){_hasBeenFound=!0;break}if(_hasBeenFound)return}var _hookHandler=handler;handler.length<=1&&(_hookHandler=function(payload,next){handler(payload),next()}),_store.hooks[_hook.event].push(_hookHandler),_store.isInternalHooks[_hook.event].push(isInternalHook||!1),_store.realHooks[_hook.event].push(handler)}catch(e){logger.warn(["lunaris.hook:"+hook],e)}},exports.removeHook=function(hook,handler){try{_isFunction(handler);var _hook=_extractHookAndStore(hook),_store=imports[3]._stores[_hook.store];if(!_store)throw new Error('Cannot remove hook "'+hook+'", store "'+_hook.store+'" has not been defined!');var _handlers=_store.realHooks[_hook.event];if(!_handlers)throw new Error('Cannot remove hook "'+hook+'", it has not been defined!');for(var i=0;i<_handlers.length;i++)_handlers[i]===handler&&(_handlers.splice(i,1),_store.isInternalHooks[_hook.event].splice(i,1),_store.hooks[_hook.event].splice(i,1))}catch(e){logger.warn(["lunaris.removeHook:"+hook],e)}},exports.pushToHandlers=function(store,hook,payload,callback){var _storeHooks=store.hooks[hook];if(callback||(callback=function(){}),!_storeHooks)return callback();!function(items,payload,done){var iterator=-1;!function next(){if(++iterator,!items[iterator])return done();items[iterator](payload,next)}()}(_storeHooks,payload,callback)},exports.removeAllHooks=function(){var _stores=lunarisExports._stores;for(var _storename in _stores){var _hooks=_stores[_storename].hooks;for(var _hook in _hooks)for(var _handlers=_hooks[_hook],_isInternalHooks=_stores[_storename].isInternalHooks[_hook],i=_handlers.length-1;i>=0;i--)_isInternalHooks&&_isInternalHooks[i]||(_handlers.splice(i,1),_isInternalHooks.splice(i,1),_stores[_storename].realHooks[_hook].splice(i,1))}},exports}([_logger_js,_exports_js,_exports_js,_exports_js],{}),_utils_js=function(imports,exports){var isBrowser=imports[0].isBrowser;function clone(value){var out=null;if("object"!=typeof value||null==value)return value;if(Array.isArray(value)){out=[];for(var index=0;index<value.length;++index){var subArray=value[index];"object"!==typeof subArray?out.push(subArray):out.push(clone(subArray))}return out}for(var key in out={},value){var subObject=value[key],typeObjValue=typeof subObject;subObject&&subObject.constructor===Object||Array.isArray(subObject)?out[key]=clone(subObject):out[key]="object"===typeObjValue&&subObject?subObject.toISOString?subObject.toISOString():subObject.toString():"function"!==typeObjValue?subObject:void 0}return out}function freeze(value){return Object.freeze(value)}exports.cloneAndFreeze=function(value,cloneFn){var _value=(cloneFn||clone)(value);if(!Array.isArray(_value))return freeze(_value);for(var i=0;i<_value.length;i++)_value[i]=freeze(_value[i]);return _value},exports.keepTheReferenceAndChangeTheAttributes=function(obj1,obj2){for(var _keys=Object.keys(obj1),i=0;i<_keys.length;i++)delete obj1[_keys[i]];for(_keys=Object.keys(obj2),i=0;i<_keys.length;i++)obj1[_keys[i]]=obj2[_keys[i]]},exports.clone=clone,exports.freeze=freeze,exports.offlineStore="lunarisOfflineTransactions",exports.OPERATIONS={DELETE:"DELETE",INSERT:"POST",UPDATE:"PUT",PATCH:"PATCH",LIST:"GET",RESET:"RESET"},exports.OPERATORS={"=":":=",ILIKE:":",">":":>","<":":<",">=":":>=","<=":":<=","<>":":!="},exports.merge=function merge(parent,child){if(!child)return parent;if("object"==typeof parent&&"object"==typeof child){for(var _keys=Object.keys(child),i=0;i<_keys.length;i++){var _key=_keys[i];parent[_key]&&"object"==typeof child[_key]?parent[_key]=merge(parent[_key],child[_key]):parent[_key]=child[_key]}return parent}},exports.distance=function(str1,str2){if(null===str1||null===str2)return 0;var distance=function(str1,str2){for(var prev,value,current=[],i=0;i<=str2.length;i++)for(var j=0;j<=str1.length;j++)value=i&&j?str1.charAt(j-1)===str2.charAt(i-1)?prev:Math.min(current[j],current[j-1],prev)+1:i+j,prev=current[j],current[j]=value;return current.pop()}(str1=String(str1),str2=String(str2));return str1.length>str2.length?1-distance/str1.length:1-distance/str2.length},exports.index={sort:function(a,b){return null===a&&null===b?0:null===a?-1:null===b?1:a<b?-1:a>b?1:0},insertAt:function(array,index,value){return array.splice(index,0,value),array},removeAt:function(array,index){return array.splice(index,1),array},getValue:function(value){if("string"==typeof value){var _value=value.replace(/^_/,"");return/^-?[0-9]+$/.test(_value)?parseInt(_value,10):_value}return value},binarySearch:function(array,value){for(var compared,mid,comparedValue,lo=0,hi=array.length,val=this.getValue(value);lo<hi;){if(mid=(lo+hi)/2|0,comparedValue=this.getValue(array[mid]),0===(compared=this.sort(val,comparedValue)))return{found:!0,index:mid};compared<0?hi=mid:lo=mid+1}return{found:!1,index:hi}}};for(var defaultDiacriticsRemovalMap=[{base:"A",letters:"AⒶＡÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ"},{base:"AA",letters:"Ꜳ"},{base:"AE",letters:"ÆǼǢ"},{base:"AO",letters:"Ꜵ"},{base:"AU",letters:"Ꜷ"},{base:"AV",letters:"ꜸꜺ"},{base:"AY",letters:"Ꜽ"},{base:"B",letters:"BⒷＢḂḄḆɃƂƁ"},{base:"C",letters:"CⒸＣĆĈĊČÇḈƇȻꜾ"},{base:"D",letters:"DⒹＤḊĎḌḐḒḎĐƋƊƉꝹÐ"},{base:"DZ",letters:"ǱǄ"},{base:"Dz",letters:"ǲǅ"},{base:"E",letters:"EⒺＥÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ"},{base:"F",letters:"FⒻＦḞƑꝻ"},{base:"G",letters:"GⒼＧǴĜḠĞĠǦĢǤƓꞠꝽꝾ"},{base:"H",letters:"HⒽＨĤḢḦȞḤḨḪĦⱧⱵꞍ"},{base:"I",letters:"IⒾＩÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ"},{base:"J",letters:"JⒿＪĴɈ"},{base:"K",letters:"KⓀＫḰǨḲĶḴƘⱩꝀꝂꝄꞢ"},{base:"L",letters:"LⓁＬĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ"},{base:"LJ",letters:"Ǉ"},{base:"Lj",letters:"ǈ"},{base:"M",letters:"MⓂＭḾṀṂⱮƜ"},{base:"N",letters:"NⓃＮǸŃÑṄŇṆŅṊṈȠƝꞐꞤ"},{base:"NJ",letters:"Ǌ"},{base:"Nj",letters:"ǋ"},{base:"O",letters:"OⓄＯÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ"},{base:"OI",letters:"Ƣ"},{base:"OO",letters:"Ꝏ"},{base:"OU",letters:"Ȣ"},{base:"OE",letters:"Œ"},{base:"oe",letters:"œ"},{base:"P",letters:"PⓅＰṔṖƤⱣꝐꝒꝔ"},{base:"Q",letters:"QⓆＱꝖꝘɊ"},{base:"R",letters:"RⓇＲŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ"},{base:"S",letters:"SⓈＳẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ"},{base:"T",letters:"TⓉＴṪŤṬȚŢṰṮŦƬƮȾꞆ"},{base:"TZ",letters:"Ꜩ"},{base:"U",letters:"UⓊＵÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ"},{base:"V",letters:"VⓋＶṼṾƲꝞɅ"},{base:"VY",letters:"Ꝡ"},{base:"W",letters:"WⓌＷẀẂŴẆẄẈⱲ"},{base:"X",letters:"XⓍＸẊẌ"},{base:"Y",letters:"YⓎＹỲÝŶỸȲẎŸỶỴƳɎỾ"},{base:"Z",letters:"ZⓏＺŹẐŻŽẒẔƵȤⱿⱫꝢ"},{base:"a",letters:"aⓐａẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ"},{base:"aa",letters:"ꜳ"},{base:"ae",letters:"æǽǣ"},{base:"ao",letters:"ꜵ"},{base:"au",letters:"ꜷ"},{base:"av",letters:"ꜹꜻ"},{base:"ay",letters:"ꜽ"},{base:"b",letters:"bⓑｂḃḅḇƀƃɓ"},{base:"c",letters:"cⓒｃćĉċčçḉƈȼꜿↄ"},{base:"d",letters:"dⓓｄḋďḍḑḓḏđƌɖɗꝺ"},{base:"dz",letters:"ǳǆ"},{base:"e",letters:"eⓔｅèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ"},{base:"f",letters:"fⓕｆḟƒꝼ"},{base:"g",letters:"gⓖｇǵĝḡğġǧģǥɠꞡᵹꝿ"},{base:"h",letters:"hⓗｈĥḣḧȟḥḩḫẖħⱨⱶɥ"},{base:"hv",letters:"ƕ"},{base:"i",letters:"iⓘｉìíîĩīĭïḯỉǐȉȋịįḭɨı"},{base:"j",letters:"jⓙｊĵǰɉ"},{base:"k",letters:"kⓚｋḱǩḳķḵƙⱪꝁꝃꝅꞣ"},{base:"l",letters:"lⓛｌŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ"},{base:"lj",letters:"ǉ"},{base:"m",letters:"mⓜｍḿṁṃɱɯ"},{base:"n",letters:"nⓝｎǹńñṅňṇņṋṉƞɲŉꞑꞥ"},{base:"nj",letters:"ǌ"},{base:"o",letters:"oⓞｏòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ"},{base:"oi",letters:"ƣ"},{base:"ou",letters:"ȣ"},{base:"oo",letters:"ꝏ"},{base:"p",letters:"pⓟｐṕṗƥᵽꝑꝓꝕ"},{base:"q",letters:"qⓠｑɋꝗꝙ"},{base:"r",letters:"rⓡｒŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ"},{base:"s",letters:"sⓢｓßśṥŝṡšṧṣṩșşȿꞩꞅẛ"},{base:"t",letters:"tⓣｔṫẗťṭțţṱṯŧƭʈⱦꞇ"},{base:"tz",letters:"ꜩ"},{base:"u",letters:"uⓤｕùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ"},{base:"v",letters:"vⓥｖṽṿʋꝟʌ"},{base:"vy",letters:"ꝡ"},{base:"w",letters:"wⓦｗẁẃŵẇẅẘẉⱳ"},{base:"x",letters:"xⓧｘẋẍ"},{base:"y",letters:"yⓨｙỳýŷỹȳẏÿỷẙỵƴɏỿ"},{base:"z",letters:"zⓩｚźẑżžẓẕƶȥɀⱬꝣ"}],diacriticsMap={},i=0;i<defaultDiacriticsRemovalMap.length;i++)for(var letters=defaultDiacriticsRemovalMap[i].letters,j=0;j<letters.length;j++)diacriticsMap[letters[j]]=defaultDiacriticsRemovalMap[i].base;return exports.unaccent=function(str){return str.replace(/[^u0000-u007E]/g,(function(a){return diacriticsMap[a]||a}))},exports.queue=function(items,handler,done){var iterator=-1;!function next(){if(iterator++,!items[iterator])return done();handler(items[iterator],next)}()},exports.getProcessTime=function(before){return isBrowser?before?window.performance.now()-before:window.performance.now():0},exports.deleteRows=function(data){for(var i=data.length-1;i>=0;i--)1!==data[i]._version.length&&data.splice(i,1)},exports}([_exports_js],{}),_localStorageDriver_js=function(imports,exports){var database,logger=imports[0],lunarisExports=imports[1];var _queue=[],_isQueueing=!1;function _startQueue(){_isQueueing||(_isQueueing=!0,function _processQueue(){var _currentItem=_queue.shift();if(!_currentItem)return void(_isQueueing=!1);var _callback=_currentItem.pop(),_args=_currentItem.slice(1);if(3===_currentItem.length&&Array.isArray(_currentItem[2])&&_currentItem[2].length>1e4)return function(_currentItem,callback){var _data=_currentItem[2];for(;_data.length>1e4;)_addInQueue([_currentItem[0],_currentItem[1],_data.splice(0,1e4),_data.length?null:callback]);_data.length&&_addInQueue([_currentItem[0],_currentItem[1],_data.splice(0,_data.length),callback])}(_currentItem,_callback),_processQueue();_args.push((function(err,data){_callback&&_callback(err,data),_processQueue()})),_currentItem[0].apply(null,_args)}())}function _addInQueue(args){if(lunarisExports.isOfflineStrategies)_queue.push(args),_startQueue();else{var _callback=args.pop();"function"==typeof _callback&&_callback()}}function _add(key,value,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readwrite")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)},_transaction.oncomplete=function(){callback()};var _objectStore=_transaction.objectStore(key);Array.isArray(value)||(value=[value]);for(var i=0,len=value.length;i<len;i++)_objectStore.add(value[i])}function _upsert(key,value,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readwrite")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)},_transaction.oncomplete=function(){callback()};var _objectStore=_transaction.objectStore(key);Array.isArray(value)||(value=[value]);for(var i=0,len=value.length;i<len;i++)_objectStore.put(value[i])}function _del(key,value,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readwrite")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)},_transaction.oncomplete=function(){callback()};var _objectStore=_transaction.objectStore(key);Array.isArray(value)||(value=[value]);for(var i=0,len=value.length;i<len;i++)_objectStore.delete(value[i])}function _get(key,value,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readonly")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)};var _request=_transaction.objectStore(key).get(value);_request.onsuccess=function(e){callback(null,e.target.result)},_request.onerror=function(e){callback(e)}}function _getAll(key,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readonly")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)};var _request=_transaction.objectStore(key).getAll();_request.onsuccess=function(e){callback(null,e.target.result)},_request.onerror=function(e){callback(e)}}function _clear(key,callback){if(!database)return callback();try{var _transaction=database.transaction(key,"readwrite")}catch(e){return callback(e)}_transaction.onerror=function(e){callback(e)},_transaction.onblocked=function(e){callback(e)},_transaction.oncomplete=function(){callback()},_transaction.objectStore(key).clear()}var drivers={indexedDB:{init:function(versionNumber,stores,callback){var _request;window.indexedDB=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,window.indexedDB?(window.IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction||window.msIDBTransaction||{READ_WRITE:"readwrite"},window.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange,(_request=window.indexedDB.open("lunaris",versionNumber)).onerror=function(e){logger.warn("Error when requesting indexedDB",e.target.error),callback&&callback(!0)},_request.onsuccess=function(e){database=e.target.result,callback&&callback(null,database),database.onerror=function(e){logger.warn("[IndexedDB]",e.target.errorCode)}},_request.onupgradeneeded=function(e){drivers.localStorage.set("lunaris:indexedDB_version",versionNumber);for(var _db=e.target.result,i=0;i<stores.length;i++){var _key=stores[i];_db.objectStoreNames.contains(_key)||_db.createObjectStore(_key,{keyPath:"_rowId"})}_db.objectStoreNames.contains("_states")||_db.createObjectStore("_states",{keyPath:"store"}),_db.objectStoreNames.contains("_invalidations")||_db.createObjectStore("_invalidations",{keyPath:"url"}),_db.objectStoreNames.contains("cache")||_db.createObjectStore("cache",{keyPath:"hash"})}):callback&&callback(!0)},add:function(key,value,callback){if(!database)return callback?callback():void 0;_addInQueue([_add,key,value,callback])},upsert:function(key,value,callback){if(!database)return callback?callback():void 0;_addInQueue([_upsert,key,value,callback])},del:function(key,value,callback){if(!database)return callback?callback():void 0;_addInQueue([_del,key,value,callback])},get:function(key,value,callback){if(!database)return callback?callback():void 0;_addInQueue([_get,key,value,callback])},getAll:function(key,callback){if(!database)return callback?callback():void 0;_addInQueue([_getAll,key,callback])},clear:function(key,callback){if(!database)return callback?callback():void 0;_addInQueue([_clear,key,callback])}},localStorage:{get:function(key){if(lunarisExports.isBrowser&&"undefined"!=typeof localStorage){var _val=localStorage.getItem(key);return _val?JSON.parse(_val):null}},set:function(key,value){if(lunarisExports.isBrowser&&"undefined"!=typeof localStorage)return localStorage.setItem(key,null!=value?JSON.stringify(value):null)},clear:function(key){if(lunarisExports.isBrowser&&"undefined"!=typeof localStorage)return localStorage.setItem(key,null)}}};return drivers}([_logger_js,_exports_js]),_store_store_utils_js=function(imports,exports){var lunarisExports=imports[0],logger=imports[1],utils=imports[2],database=imports[3].indexedDB;function getStore(storeName){/@/.test(storeName)&&(storeName=(storeName=storeName.split("@"))[storeName.length-1]);var lunarisExports=imports[4];if(!lunarisExports._stores[storeName])throw new Error('The store "'+storeName+'" has not been defined');return lunarisExports._stores[storeName]}function getPrimaryKeyValue(store,value,isInsertOrMassiveUpdate){var _id=null;if(isInsertOrMassiveUpdate)return _id;if(store.getPrimaryKeyFn)return store.getPrimaryKeyFn.call(null,value);if(!store.primaryKey&&!store.isStoreObject)return logger.tip('No primary key has been found in store "'+store.name+'", fallback to lunaris object attribute "_id".',"To declare a primary key, use the notation ['<<int>>'] in the map or add the 'primaryKey' attribute in the store description."),value._id;var _primaryKey=store.primaryKey;if(Array.isArray(_primaryKey)){_id=[];for(var i=0;i<_primaryKey.length;i++){var _value=value[_primaryKey[i]];if(null==_value)return null;_id.push(_value)}return _id.length>1&&(_id=_id.join("-")),_id[0]}return value[store.primaryKey]}function setPathValue(objectPathParts,value,obj){var _parts=utils.clone(objectPathParts),_obj=obj||{},_part=_parts.shift();return _parts.length?(_obj[_part]=setPathValue(_parts,value),_obj):(_obj[_part]=value,_obj)}return exports.getStore=getStore,exports.getCollection=function(store){var _collection=store.data;if(!_collection)throw new Error('"'+store+'" has not been defined!');return _collection},exports.getCache=function(store){return store.cache},exports.getPrimaryKeyValue=getPrimaryKeyValue,exports.setPrimaryKeyValue=function(store,value,id){var _valueId=getPrimaryKeyValue(store,value,!1);if(null==_valueId){if(store.setPrimaryKeyFn)return store.setPrimaryKeyFn.call(null,value,id);if(!store.primaryKey||store.primaryKey&&!store.primaryKey.length)return null;var _primaryKey=store.primaryKey;return Array.isArray(_primaryKey)?(null!==value[_primaryKey[0]]&&void 0!==value[_primaryKey[0]]||(value[_primaryKey[0]]="_"+id),_primaryKey.length>1?logger.tip("lunaris cannot set a composite primary key"):"_"):value[store.primaryKey]="_"+id}},exports.checkArgs=function(store,value,isNoValue){if(void 0===value&&!isNoValue)throw new Error("Must have a value, provided value: "+value);if(!store||"string"!=typeof store)throw new Error("Must have a correct store value: @<store>")},exports.getTranslatedStoreName=function(storeName){return getStore(storeName).nameTranslated},exports.getPathValue=function getPathValue(objectPathParts){var _parts=utils.clone(objectPathParts),_part=_parts.shift();return _parts.length?getPathValue(objectPathParts)||null:{}[_part]},exports.setPathValue=setPathValue,exports.setObjectPathValues=function(objectPathValues,data){for(var _paths=Object.keys(objectPathValues),i=0;i<_paths.length;i++)setPathValue(_paths[i].split("."),objectPathValues[_paths[i]],data)},exports.getJSONPatchPath=function(path){return path.replace(".","/")},exports.saveState=function(store,collection,callback){if(!lunarisExports.isBrowser)return callback?callback():void 0;var _state={store:store.name,massOperations:store.massOperations,collection:{currentId:collection.getCurrentId(),currentRowId:collection.getCurrentRowId()}};database.upsert("_states",_state,callback)},exports}([_exports_js,_logger_js,_utils_js,_localStorageDriver_js,_exports_js],{}),_store_store_collection_js=function(imports,exports){var utils=imports[0],OPERATIONS=(utils.index,utils.OPERATIONS),aggregates=imports[1].aggregates,lunarisExports=imports[2],logger=imports[3],localStorageDriver=imports[4],localStorage=localStorageDriver.localStorage,localDatabase=localStorageDriver.indexedDB,currentVersionNumber=1,_savedCurrentVersionNumber=localStorage.get("lunaris:versionNumber",1);function incrementVersionNumber(){currentVersionNumber++,localStorage.set("lunaris:versionNumber",currentVersionNumber)}return _savedCurrentVersionNumber&&(currentVersionNumber=_savedCurrentVersionNumber),exports.collection=function(getPrimaryKeyFn,isStoreObject,joinsDescriptor,aggregateFn,computedsFn,storeName,referencesDescriptor,cloneFn){var _data=[],_dataCache=[],_dataCacheIndex={},_currentId=1,_currentRowId=1,_transactions={},_isTransactionCommit=!1,_transactionVersionNumber=null,_isStoreObject=isStoreObject||!1,_joinsDescriptor=joinsDescriptor||{},_joins=joinsDescriptor?Object.keys(_joinsDescriptor.joins):[],_referencesDescriptor=referencesDescriptor||{},_references=_referencesDescriptor.stores&&_referencesDescriptor.stores.length?_referencesDescriptor.stores:[],_getPrimaryKey=getPrimaryKeyFn,_aggregateFn=aggregateFn,_computedsFn=computedsFn,_storeName=storeName,_locaDatabaseActions=[],_idIndex={},_indexes={id:[[],[]],references:{}};function _addActionToLocalDatabase(actionFn,data){if(null==_transactionVersionNumber)return actionFn(_storeName,data);_locaDatabaseActions.push(data)}function _addTransaction(versionNumber,data,operation){_transactions[versionNumber]&&_transactions[versionNumber].push([versionNumber,data,operation])}function _setReferencedValues(value){if(_references.length)for(var _reference in _referencesDescriptor.references){var _store=_referencesDescriptor.references[_reference],_ids=_referencesDescriptor.referencesFn.get[_reference](value);_indexes.references[_store]||(_indexes.references[_store]={});for(var j=0;j<_ids.length;j++)_indexes.references[_store][_ids[j]]||(_indexes.references[_store][_ids[j]]=[]),-1===_indexes.references[_store][_ids[j]].indexOf(value._id)&&_indexes.references[_store][_ids[j]].push(value._id)}}function _buildDataCache(){for(var _id in _dataCache=[],_dataCacheIndex)null!=_dataCacheIndex[_id]&&_dataCache.push(_data[_dataCacheIndex[_id]])}function _addToValues(value,versionNumber,isFromUpsert,isFromIndex){if(value._id&&isFromUpsert){if(_getPrimaryKey){var _id=_getPrimaryKey(value);if(null!=_id){var _search=_idIndex[_id];null==_search&&(_idIndex[_id]=value._id)}}return value._rowId=_currentRowId++,_setReferencedValues(value),_aggregateFn&&_aggregateFn(value,aggregates,lunarisExports.constants,logger),_addActionToLocalDatabase(localDatabase.upsert,value),_dataCacheIndex[value._id]=_data.length,_data.push(value)}return value._id=_currentId,_currentId++,_setReferencedValues(value),function(value){if(_joins.length){for(var _joinValues={},i=0;i<_joins.length;i++){var _collection=_joinsDescriptor.collections[_joins[i]];_joinValues[_joins[i]]=_collection?_collection.getAll():null}_joinsDescriptor.joinFns.set(value,_joinValues,aggregates,lunarisExports.constants,logger)}}(value),_aggregateFn&&_aggregateFn(value,aggregates,lunarisExports.constants,logger),isFromIndex||!_getPrimaryKey||null===(_id=_getPrimaryKey(value))||void 0===value._id?(value._rowId=_currentRowId++,_addActionToLocalDatabase(localDatabase.upsert,value),_dataCacheIndex[value._id]=_data.length,_data.push(value)):null!=(_search=_idIndex[_id])?(value._id=_idIndex[_id],value._rowId=_currentRowId,void upsert(value,versionNumber,!1,!0)):(_idIndex[_id]=value._id,_dataCacheIndex[value._id]=_data.length,value._rowId=_currentRowId++,_data.push(value),void _addActionToLocalDatabase(localDatabase.upsert,value))}function _removeFromIndex(_id,id){null!=_idIndex[id]&&(_idIndex[id]=null)}function add(value,versionNumber,isFromUpsert,isFromIndex){if(null==value||"object"!=typeof value)throw new Error("add must have a value. It must be an Object.");if(!versionNumber||_isTransactionCommit)return _computedsFn&&_computedsFn(value,lunarisExports.constants,logger),value._version=[versionNumber||currentVersionNumber],_isTransactionCommit||incrementVersionNumber(),_addToValues(value,versionNumber,isFromUpsert,isFromIndex),_isTransactionCommit||_buildDataCache(),value;_addTransaction(versionNumber,value,OPERATIONS.INSERT)}function upsert(value,versionNumber,isRemove,isFromIndex){if((null===value._id||void 0===value._id)&&!isRemove)return add(value,versionNumber);if(!versionNumber||_isTransactionCommit){var _search=_dataCacheIndex[value._id];if(null==_search){if(isRemove)return;return add(value,_transactionVersionNumber||null,!0)}var _version=_transactionVersionNumber||currentVersionNumber,_dataObject=_data[_search],_lowerVersion=_dataObject._version[0],_upperVersion=_dataObject._version[1]||_version,_objToUpdate=cloneFn(value);return _dataObject._version[1]=_version,function(value){if(_references.length)for(var _reference in _referencesDescriptor.references){var _store=_referencesDescriptor.references[_reference],_ids=_referencesDescriptor.referencesFn.get[_reference](value);_indexes.references[_store]||(_indexes.references[_store]=[[],[]]);for(var j=0;j<_ids.length;j++)if(_indexes.references[_store][_ids[j]]){var _searchIndex=_indexes.references[_store][_ids[j]].indexOf(value._id);-1!==_searchIndex&&(_indexes.references[_store][_ids[j]].splice(_searchIndex,1),_indexes.references[_store][_ids[j]].length||(_indexes.references[_store][_ids[j]]=null))}}}(_dataObject),_lowerVersion===_version&&_upperVersion===_version&&_dataObject._version[1]>=0?isRemove?(_addActionToLocalDatabase(localDatabase.upsert,_dataObject),void(_dataCacheIndex[value._id]=null)):(utils.merge(_dataObject,_objToUpdate),_dataObject._version.pop(),_addActionToLocalDatabase(localDatabase.upsert,_dataObject),_dataObject):(_addActionToLocalDatabase(localDatabase.upsert,_dataObject),isRemove?(_dataCacheIndex[value._id]=null,_isTransactionCommit||_buildDataCache(),_dataObject):add(_objToUpdate,_transactionVersionNumber||null,!0,isFromIndex))}_addTransaction(versionNumber,value,OPERATIONS.UPDATE)}function remove(value,versionNumber,isPK){if(!versionNumber||_isTransactionCommit){if(_getPrimaryKey&&!isPK){var _obj=get(value._id);_obj&&_removeFromIndex(value._id,_getPrimaryKey(_obj))}else if(_getPrimaryKey&&isPK){var _pk=_getPrimaryKey(value),_search=_idIndex[_pk];null!=_search&&(value._id=_search,_idIndex[_pk]=null)}return upsert({_id:value._id},versionNumber,!0)}_addTransaction(versionNumber,{value:value,isPK:!!isPK},OPERATIONS.DELETE)}function get(id,isPrimaryKey){if(isPrimaryKey){if(null==_idIndex[id])return null;id=_idIndex[id]}return null==_dataCacheIndex[id]?null:_data[_dataCacheIndex[id]]}function begin(){return _transactions[currentVersionNumber]=[],_locaDatabaseActions=[],currentVersionNumber}function _internalCommit(versionNumber){var _res=[],_transaction=_transactions[versionNumber];if(_transaction){_isTransactionCommit=!0,_transactionVersionNumber=currentVersionNumber;for(var i=0;i<_transaction.length;i++)if(_transaction[i][2]===OPERATIONS.INSERT)_res.push(add(_transaction[i][1],null,!0));else if(_transaction[i][2]===OPERATIONS.UPDATE)_res.push(upsert(_transaction[i][1]));else{var _remove=remove(_transaction[i][1].value,null,_transaction[i][1].isPK);_remove&&_res.push(_remove)}return _locaDatabaseActions.length&&(localDatabase.upsert(_storeName,_locaDatabaseActions),_locaDatabaseActions=[]),_transactions[versionNumber]=_transactionVersionNumber,_isTransactionCommit=!1,_transactionVersionNumber=null,incrementVersionNumber(),_buildDataCache(),cloneFn(_res)}}return{get:get,add:add,upsert:upsert,remove:remove,clear:function(){_data=[],_currentId=1,_currentRowId=1,_idIndex={},_indexes.references={},_dataCache=[],_dataCacheIndex={}},getFirst:function(){if(_data[0])return get(_data[0]._id)},begin:begin,commit:function(versionNumber){var _res=_internalCommit(versionNumber);return _isStoreObject?_res.length?_res[0]:null:_res},rollback:function(versionNumber){var _transaction=_transactions[versionNumber];if(_transaction){versionNumber=_transaction;for(var _objToRollback=[],i=_data.length-1;i>=0;i--){var _lowerVersion=_data[i]._version[0],_upperVersion=_data[i]._version[1];(versionNumber===_upperVersion||versionNumber===_lowerVersion&&!_upperVersion)&&_objToRollback.push(cloneFn(_data[i]))}for(var _version=begin(),j=0;j<_objToRollback.length;j++)_objToRollback[j]._version[0]!==_objToRollback[j]._version[1]&&(_objToRollback[j]._version[1]?add(_objToRollback[j],_version):remove({_id:_objToRollback[j]._id},_version,!1));return _internalCommit(_version)}},propagate:function(store,data,operation){if(_joinsDescriptor.joinFns[store]){data&&!Array.isArray(data)&&(data=[data]);for(var _version=begin(),i=0;i<_data.length;i++){var _item=_data[i],_lowerVersion=_item._version[0],_upperVersion=_item._version[1];if(_lowerVersion<=currentVersionNumber&&!_upperVersion){var _obj=cloneFn(_item);if(data&&data.length)for(var j=0;j<data.length;j++)_obj=_updateObject(_obj,data[j],operation);else _obj=_updateObject(_obj,null,operation);upsert(_obj,_version)}}return _internalCommit(_version)}function _updateObject(object,data,operation){return operation===OPERATIONS.INSERT||operation===OPERATIONS.UPDATE?(_joinsDescriptor.joinFns[store].delete(object,data,aggregates,lunarisExports.constants,logger),_joinsDescriptor.joinFns[store].insert(object,data,aggregates,lunarisExports.constants,logger)):operation===OPERATIONS.DELETE?_joinsDescriptor.joinFns[store].delete(object,data,aggregates,lunarisExports.constants,logger):void 0}},replaceReferences:function(store,lastPK,newPK){if(!_referencesDescriptor.referencesFn)return[];if(!_indexes.references[store])return[];if(!_indexes.references[store][lastPK])return[];for(var _version=begin(),_index=_indexes.references[store][lastPK],i=0;i<_data.length;i++){var _item=_data[i],_lowerVersion=_item._version[0],_upperVersion=_item._version[1];if(_lowerVersion<=currentVersionNumber&&!_upperVersion&&-1!==_index.indexOf(_item._id)){var _obj=cloneFn(_item);for(var path in _referencesDescriptor.references)_referencesDescriptor.referencesFn.update[path](lastPK,newPK,_obj);upsert(_obj,_version)}}return _internalCommit(_version)},getIndexId:function(){return _idIndex},getIndexReferences:function(){return _indexes.references},getIndexDataCache:function(){return _dataCacheIndex},removeIndexIdValue:function(key){null!=key&&_removeFromIndex(0,"_"+key)},_getAll:function(){return _data},_getAllCache:function(){return _dataCache},setData:function(value){_data=value,function(){for(var _iterator=0,i=0,len=_data.length;i<len;i++){var _item=_data[i];if(!(_item._version.length>1)){if(_dataCacheIndex[_item._id]=_iterator,_iterator++,_getPrimaryKey){var _pk=_getPrimaryKey(_item);_idIndex[_pk]=_item._id}_setReferencedValues(_item)}}}(),_buildDataCache()},getAll:function(ids,isPK,isClone){var _res=[];if(null==ids)_res=_dataCache;else for(var i=0;i<ids.length;i++){var _id=ids[i];if(isPK)null!=(_search=_idIndex[_id])&&_res.push(_data[_dataCacheIndex[_search]]);else{var _search=_dataCacheIndex[_id];null!=_search&&_res.push(_data[_search])}}return _isStoreObject&&(_res=_res.length?_res[0]:null),!1===isClone?_res:cloneFn(_res)},getCurrentId:function(){return _currentId},setCurrentId:function(value){_currentId=value},getCurrentVersionNumber:function(){return currentVersionNumber},getCurrentRowId:function(){return _currentRowId},setCurrentRowId:function(value){_currentRowId=value}}},exports.resetVersionNumber=function(){currentVersionNumber=1,localStorage.set("lunaris:versionNumber",1)},exports}([_utils_js,function(imports,exports){var index=imports[0].index,aggregates={sumAgg:{type:"number",init:{start:0},add:function(prevState,value){return prevState||(prevState={value:this.init.start}),{value:prevState.value+(value||this.init.start)}},remove:function(prevState,value){return prevState||(prevState={value:this.init.start}),{value:prevState.value-(value||this.init.start)}},getStartValue:function(){return this.init.start}},countAgg:{type:"int",init:{start:0},add:function(prevState){return prevState||(prevState={value:this.init.start}),{value:prevState.value+1}},remove:function(prevState){return prevState||(prevState={value:this.init.start}),{value:prevState.value-1}},getStartValue:function(){return this.init.start}},avgAgg:{type:"number",init:{start:0,count:0},add:function(prevState,value){return prevState||(prevState={value:this.init.start,count:this.init.count}),value||(value=0),prevState.count++,prevState.value+=(value-prevState.value)/prevState.count,prevState},remove:function(prevState,value){return prevState||(prevState={value:this.init.start,count:this.init.count}),value||(value=0),prevState.count--,prevState.value-=(value-prevState.value)/prevState.count,prevState},getStartValue:function(){return this.init.start}},minAgg:{type:"*",init:{start:null,values:[]},add:function(prevState,value){if(prevState||(prevState={value:this.init.start,values:[]}),!value)return prevState;var _search=index.binarySearch(prevState.values,value);return index.insertAt(prevState.values,_search.index,value),prevState.value=prevState.values[0],prevState},remove:function(prevState,value){if(prevState||(prevState={value:this.init.start,values:[]}),!prevState.value)return prevState;var _search=index.binarySearch(prevState.values,value);return _search.found&&(index.removeAt(prevState.values,_search.index),prevState.value=prevState.values[0]),prevState},getStartValue:function(){return this.init.start}},maxAgg:{type:"*",init:{start:null,values:[]},add:function(prevState,value){if(prevState||(prevState={value:this.init.start,values:[]}),!value)return prevState;var _search=index.binarySearch(prevState.values,value);return index.insertAt(prevState.values,_search.index,value),prevState.value=prevState.values[prevState.values.length-1],prevState},remove:function(prevState,value){if(prevState||(prevState={value:this.init.start,values:[]}),!prevState.value)return prevState;var _search=index.binarySearch(prevState.values,value);return _search.found&&(index.removeAt(prevState.values,_search.index),prevState.value=prevState.values[prevState.values.length-1]),prevState},getStartValue:function(){return this.init.start}},countBoolTrueAgg:{type:"int",init:{start:0},add:function(prevState,value){return prevState||(prevState={value:this.init.start}),!0===value&&(prevState.value=prevState.value+1),prevState},remove:function(prevState,value){return prevState||(prevState={value:this.init.start}),!0!==value||0===prevState.value||(prevState.value=prevState.value-1),prevState},getStartValue:function(){return this.init.start}}};return exports.aggregates=aggregates,exports}([_utils_js],{}),_exports_js,_logger_js,_localStorageDriver_js],{}),_offline_js=(isOnline=!0,isOfflineMode=!1,isSynchronizing=!1,"undefined"!=typeof navigator&&(isOnline=void 0===navigator.onLine||navigator.onLine,window.addEventListener("online",(function(){isOnline=!0})),window.addEventListener("offline",(function(){isOnline=!1}))),{get isOnline(){return!isOfflineMode&&isOnline},get isRealOnline(){return isOnline},set isOnline(value){isOnline=value},get isOfflineMode(){return isOfflineMode},set isOfflineMode(value){isOfflineMode=value},get isSynchronizing(){return isSynchronizing},set isSynchronizing(value){isSynchronizing=value}}),_store_crud_crudUtils_js=function(imports,exports){var storeUtils=imports[0],hook=imports[1],utils=imports[2],queue=utils.queue;function pushCommitResToHandlers(store,hookKey,res,callback){if(res&&res.length)return store.isStoreObject&&(res=res[0]),res=utils.cloneAndFreeze(res,store.clone),hook.pushToHandlers(store,hookKey,res,callback);callback()}return exports.beforeAction=function(store,value,isNoValue){storeUtils.checkArgs(store,value,isNoValue);var _store=storeUtils.getStore(store),_collection=storeUtils.getCollection(_store);return isNoValue||(value=_store.clone(value)),{value:value,store:_store,collection:_collection}},exports.afterAction=function(store,event,value,message,callback){var _value=null;value&&(_value=utils.cloneAndFreeze(value,store.clone)),hook.pushToHandlers(store,event,_value,(function(){if(message)return hook.pushToHandlers(store,"success",message,callback);callback()}))},exports.pushCommitResToHandlers=pushCommitResToHandlers,exports.propagate=function(store,data,operation,callback){return store.storesToPropagate.length?!data&&operation!==utils.OPERATIONS.DELETE||data&&Array.isArray(data)&&!data.length?callback():void queue(store.storesToPropagate,(function(storeToPropagate,next){var _store=storeUtils.getStore("@"+storeToPropagate);pushCommitResToHandlers(_store,"update",storeUtils.getCollection(_store).propagate(store.name,data,operation),next)}),callback):callback()},exports.propagateReferences=function(store,primaryKeys,callback){if(!store.storesToPropagateReferences||!store.storesToPropagateReferences.length)return callback();queue(store.storesToPropagateReferences,(function(storeToPropagate,next){for(var _store=storeUtils.getStore("@"+storeToPropagate),_collection=storeUtils.getCollection(_store),_res=[],i=0;i<primaryKeys.length;i++)_res=_res.concat(_collection.replaceReferences(store.name,primaryKeys[i][0],primaryKeys[i][1]));pushCommitResToHandlers(_store,"update",_res,next)}),callback)},exports}([_store_store_utils_js,_store_store_hook_js,_utils_js],{}),_cache_js=function(imports,exports){var logger=imports[0],database=imports[1].indexedDB,cacheGraph=imports[2].cacheGraph,offline=imports[3];Array.prototype.equals=function(array){if(!array)return!1;if(this.length!==array.length)return!1;for(var i=0,l=this.length;i<l;i++)if(this[i]instanceof Array&&array[i]instanceof Array){if(!this[i].equals(array[i]))return!1}else if(this[i]!==array[i])return!1;return!0};var cache=[];function _getOrUpdatevalues(store,hash,values){for(var _cacheValue=null,i=0;i<cache.length;i++){var _isFilterMatchValue=!1;if(cache[i].hash===hash){_isFilterMatchValue=!0,_cacheValue=cache[i];break}}return _isFilterMatchValue&&!values?_cacheValue.values:_isFilterMatchValue&&values?(-1===_cacheValue.stores.indexOf(store)&&(_cacheValue.stores.push(store),offline.isOnline&&database.upsert("cache",_cacheValue)),_cacheValue.values=values):_cacheValue}function _internalInvalidate(store){for(var i=cache.length-1;i>=0;i--)-1!==cache[i].stores.indexOf(store)&&(database.del("cache",cache[i].hash),cache.splice(i,1))}return{init:function(callback){database.getAll("cache",(function(err,res){err&&logger.warn("Error when init cache",err),cache=res||[],callback()}))},add:function(store,hash,values){if(!_getOrUpdatevalues(store,hash,values)){var _caheObj={hash:hash,values:values,stores:[store]};cache.push(_caheObj),offline.isOnline&&database.upsert("cache",_caheObj)}},get:_getOrUpdatevalues,invalidate:function(store){_internalInvalidate(store=store.replace(/^@/,""));var _aliasStores=cacheGraph[store];if(_aliasStores)for(var i=0;i<_aliasStores.length;i++)_internalInvalidate(_aliasStores[i])},clear:function(){database.clear("cache"),cache=[]},_cache:function(){return cache}}}([_logger_js,_localStorageDriver_js,_exports_js,_offline_js]),_http_js=function(imports,exports){var lunarisExports=imports[0],utils=imports[1],baseOptions={onComplete:null,headers:{"Client-Version":2}};return exports.request=function(method,request,body,callback,options){var _body=body,_headers=utils.clone(baseOptions.headers);options=options||{},_headers["Content-Type"]=options["Content-Type"]||"application/json",options.isOffline&&(_headers["Is-Offline"]=options.isOffline),"application/json"===_headers["Content-Type"]&&body&&(_body=JSON.stringify(body),lunarisExports.isProduction&&(_headers["Content-Encoding"]="gzip",_body=pako.gzip(_body))),fetch(lunarisExports.baseUrl+request,{method:method,credentials:"same-origin",headers:_headers,body:_body}).then((function(response){const isJSON=function(headers){const contentType=headers.get("content-type");return!(!contentType||-1===contentType.indexOf("application/json"))}(response.headers);return 200===response.status||isJSON?(window.origin||(window.origin=""),-1===decodeURIComponent(response.url).indexOf(decodeURIComponent(request))?window.location=response.url:(baseOptions.onComplete&&baseOptions.onComplete(response),response.json().then(json=>{if(!1===json.success)return callback({error:json.error,message:json.message,errors:json.errors});callback(null,json.data)}).catch(err=>{if(200!==response.status)return Promise.reject({error:response.status,message:response.statusText,errors:[]});console.log(err)}))):Promise.reject({error:response.status,message:response.statusText,errors:[]})})).catch((function(err){callback(err)}))},exports.setup=function(options){baseOptions=utils.merge(baseOptions,options)},exports}([_exports_js,_utils_js],{}),_store_store_url_js=function(imports,exports){var storeUtils=imports[0],utils=imports[1],logger=imports[2],exportsLunaris=imports[3],offline=imports[4];function fixedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[!'()*]/g,(function(c){return"%"+c.charCodeAt(0).toString(16)}))}function _runWhereCondition(whereFn,item){if("function"!=typeof whereFn)return logger.tip("A filter where must be a function : filter.sourceWhere = function (item) { return Boolean }."),!1;var _res=whereFn.call(null,item,exportsLunaris.constants);return"boolean"!=typeof _res?(logger.tip("A filter where must return a boolean."),!1):_res}function _getSearchOption(filterValues){for(var _search="",_operators=utils.OPERATORS,j=0;j<filterValues.length;j++){var _operator=utils.OPERATORS.ILIKE;filterValues[j][3]&&(_operator=_operators[filterValues[j][3]]||_operator);var _value=filterValues[j][2];Array.isArray(_value)&&(_value="["+_value.join(",")+"]",_operator===utils.OPERATORS["="]&&(_operator=utils.OPERATORS.ILIKE),_operator===utils.OPERATORS["<>"]&&(_operator=":!")),_search+=(filterValues[j][0]||filterValues[j][1])+fixedEncodeURIComponent(_operator)+fixedEncodeURIComponent(_value)+fixedEncodeURIComponent("+")}return["search",_search=_search.slice(0,_search.length-fixedEncodeURIComponent("+").length)]}return exports.create=function(store,method,primaryKeyValue,isPagination){var _request={request:"/",cache:{}},_isGet="GET"===method&&!1!==isPagination,_url=store.url||store.name;_request.request+=_url,null!=primaryKeyValue&&(_request.request+="/"+primaryKeyValue),_isGet&&(_request.cache.limit=store.paginationLimit,_request.cache.offset=store.paginationOffset);var _filterValues=function(store,method){var _filterValues={isRequiredOptionsFilled:!0,constructedRequiredOptions:"",requiredOptions:{},optionalOptions:{},optionalUnsearchableOptions:{},cache:{}},_nbRequiredFIlters=0,_nbRequiredFilledFilters=0;if(!store.filters.length)return _filterValues;for(var i=0;i<store.filters.length;i++){var _filter=store.filters[i],_value=[];if(offline.isOnline||!1!==_filter.isOffline){var _sourceStore=storeUtils.getStore(_filter.source),_sourceValue=storeUtils.getCollection(_sourceStore).getAll();_sourceValue&&!Array.isArray(_sourceValue)?_sourceValue=[_sourceValue]:_sourceValue||(_sourceValue=[]);var _methods=[];_filter.httpMethods?Array.isArray(_filter.httpMethods)&&(_methods=_filter.httpMethods):_methods.push(method),_filter.isRequired&&-1!==_methods.indexOf(method)&&_nbRequiredFIlters++;for(var _operator=_filter.operator,j=_sourceValue.length-1;j>=0;j--)!_filter.sourceWhere||_filter.sourceWhere&&_runWhereCondition(_filter.sourceWhere,_sourceValue[j])?_sourceValue[j]=_sourceValue[j][_filter.sourceAttribute]:_sourceValue.splice(j,1);if(_sourceValue.length||(_sourceValue=void 0),_sourceStore.isStoreObject&&(_sourceValue=_sourceValue?_sourceValue[0]:void 0),void 0!==_sourceValue){var _filterKey=i;if(_value.push(_filter.attributeUrl,_filter.localAttribute,_sourceValue,_operator),-1!==_methods.indexOf(method)){if(_filter.isRequired&&_nbRequiredFilledFilters++,!1===_filter.isSearchable)_filterValues.optionalUnsearchableOptions[_filterKey]=_value;else if(_value[3]&&!_filter.isRequired)_filterValues.optionalOptions[_filterKey]=_value;else{if(Array.isArray(_sourceValue))throw new Error("A required filter must be a store object!");_filterValues.constructedRequiredOptions+="/"+(_value[0]||_value[1])+"/"+fixedEncodeURIComponent(_value[2]),_filterValues.requiredOptions[_filterKey]=_value}_filterValues.cache[_filterKey]=_value[2]}}}}return _filterValues.isRequiredOptionsFilled=_nbRequiredFIlters===_nbRequiredFilledFilters,_filterValues}(store,method);return _filterValues.isRequiredOptionsFilled?(_request.request+=_filterValues.constructedRequiredOptions,store.urlSuffix&&(_request.request+="/"+store.urlSuffix,logger.deprecated("store.urlSuffix is deprecated. It will be removed!")),_request.request+=function(store,isPagination,filterValues){var _optionsStr="",_options=[];if(isPagination){var _limit=store.paginationLimit,_offset=store.paginationOffset;_options.push(["limit",_limit]),_options.push(["offset",_offset])}for(var filterValue,_value,_keys=Object.keys(filterValues.optionalUnsearchableOptions),i=0;i<_keys.length;i++)_options.push((filterValue=filterValues.optionalUnsearchableOptions[_keys[i]],_value=void 0,_value=filterValue[2],Array.isArray(_value)&&(_value="["+_value.join(",")+"]"),_value=fixedEncodeURIComponent(_value),[filterValue[0]||filterValue[1],_value]));var _optionsSearchable=[];for(_keys=Object.keys(filterValues.optionalOptions),i=0;i<_keys.length;i++)_optionsSearchable.push(filterValues.optionalOptions[_keys[i]]);for(_optionsSearchable.length&&_options.push(_getSearchOption(_optionsSearchable)),_options.length&&(_optionsStr+="?"),i=0;i<_options.length;i++)_optionsStr+=_options[i][0]+"="+_options[i][1]+"&";return _optionsStr=_optionsStr.slice(0,_optionsStr.length-1)}(store,_isGet,_filterValues),utils.merge(_request.cache,_filterValues.cache),_request.requiredOptions=_filterValues.requiredOptions,_request.optionalOptions=_filterValues.optionalOptions,_request.constructedRequiredOptions=_filterValues.constructedRequiredOptions,_request):null},exports.createForOffline=function(store,urlObj){var _request="/";_request+=store.url||store.name,_request+=urlObj.constructedRequiredOptions;for(var _options=[],_keys=Object.keys(urlObj.optionalOptions),i=0;i<_keys.length;i++)_options.push(urlObj.optionalOptions[_keys[i]]);var _search=_getSearchOption(_options);return _request+="?limit="+urlObj.cache.limit+"&offset="+urlObj.cache.offset+"&"+_search[0]+"="+_search[1]},exports}([_store_store_utils_js,_utils_js,_logger_js,_exports_js,_offline_js],{}),_store_store_template_js=function(imports,exports){function _replaceTemplateWords(store,method,methodFemale,template,isPlural){return template.replace("$methodFemale",methodFemale).replace("$method",method).replace("$storeName",store.nameTranslated||store.name).replace("$pronounMale",isPlural?"${thePlural}":"${the}").replace("$pronounFemale",isPlural?"${thePlural}":"${theFemale}")}return exports.getSuccess=function(message,store,method,isPlural){return store.successTemplate?_replaceTemplateWords(store,{GET:"${loaded}",PUT:"${edited}",POST:"${created}",DELETE:"${deleted}"}[method],{GET:"${loadedFemale}",PUT:"${editedFemale}",POST:"${createdFemale}",DELETE:"${deletedFemale}"}[method],store.successTemplate,isPlural):message},exports.getError=function(err,store,method,isPlural,is){return store.errorTemplate?_replaceTemplateWords(store,{GET:"${load}",PUT:"${edit}",POST:"${create}",DELETE:"${delete}"}[method],{GET:"${loadFemale}",PUT:"${editFemale}",POST:"${createFemale}",DELETE:"${deleteFemale}"}[method],store.errorTemplate,isPlural):"${An error has occured}"},exports}(0,{}),_store_store_transaction_js=(logger=[_exports_js,_logger_js][1],{begin:function(){return logger.deprecated("lunaris.begin has been removed!")},commit:function(callback){return logger.deprecated("lunaris.commit has been removed!")}}),_store_store_synchronisation_js=function(imports,exports){var lunarisExports=imports[0],hook=imports[1],utils=imports[2],storeUtils=imports[3],collection=imports[4],cache=(imports[5],imports[6]),indexedDB=imports[7].indexedDB,localStorage=imports[8].localStorage,OPERATIONS=utils.OPERATIONS,offlineTransactions=[],offlineTransactionsInError=[],OFFLINE_STORE=utils.offlineStore,isPushingOfflineTransaction=!1;imports={};function _getObjectFromCollection(storeName,_id){var _collection=storeUtils.getCollection(storeUtils.getStore(storeName));if(_collection)return _collection.get(_id)}function computeStoreTransactions(transactions,storeName,method,request,value){var _mustBeAdded=!0,_isArrayValue=Array.isArray(value);_isArrayValue||(value=[value]);for(var _lengthValue=value.length,_nbInInserts=0,j=_lengthValue-1;j>=0;j--)for(var i=transactions.length-1;i>=0;i--){var _transaction=transactions[i],_isTransactionValueAnArray=Array.isArray(_transaction.data);_isTransactionValueAnArray||(_transaction.data=[_transaction.data]);var _lengthTransactionValue=_transaction.data.length;if(_transaction.store===storeName){for(var k=_lengthTransactionValue-1;k>=0;k--){if(_transaction.method===OPERATIONS.INSERT&&method===OPERATIONS.UPDATE){if(value[j]._id!==_transaction.data[k]._id)continue;_transaction.data[k]=value[j],value.splice(j,1),_nbInInserts++,j||_nbInInserts!==_lengthValue||(_mustBeAdded=!1);break}if(_transaction.method===OPERATIONS.UPDATE&&method===OPERATIONS.UPDATE){if(value[j]._id!==_transaction.data[k]._id)continue;_transaction.data[k]=value[j],_mustBeAdded=!1;break}}if(_isTransactionValueAnArray||(_transaction.data=_transaction.data[0]),!value[j])break}else _isTransactionValueAnArray||(_transaction.data=_transaction.data[0])}return _mustBeAdded&&transactions.push({store:storeName,method:method,url:request,data:_isArrayValue?value:value[0],date:Date.now()}),transactions}return lunarisExports._stores.lunarisOfflineTransactions={name:OFFLINE_STORE,data:collection.collection(null,null,null,null,null,OFFLINE_STORE,null,utils.clone),filters:[],paginationLimit:50,paginationOffset:0,paginationCurrentPage:1,hooks:{},isLocal:!0,storesToPropagate:[],isStoreObject:!1,massOperations:{},clone:utils.clone},{get isPushingOfflineTransaction(){return isPushingOfflineTransaction},OFFLINE_STORE:OFFLINE_STORE,updateOfflineTransactionData:function(storesToUpdate){var _lengthStoresToUpdate=storesToUpdate.length;if(_lengthStoresToUpdate)for(var i=0,len=offlineTransactions.length;i<len;i++)for(var _transaction=offlineTransactions[i],j=0;j<_lengthStoresToUpdate;j++)if(_transaction.store===storesToUpdate[j]&&-1!==storesToUpdate.indexOf(_transaction.store))if(Array.isArray(_transaction.data))for(var k=0;k<_transaction.data.length;k++)_transaction.data[k]=_getObjectFromCollection(storesToUpdate[j],_transaction.data[k]._id);else _transaction.data=_getObjectFromCollection(storesToUpdate[j],_transaction.data._id)},pushOfflineHttpTransactions:function(callback){offlineTransactions=lunarisExports._stores.lunarisOfflineTransactions.data.getAll(),isPushingOfflineTransaction=!0,function _processNextOfflineTransaction(){var _currentTransaction=offlineTransactions.shift();if(!_currentTransaction)return isPushingOfflineTransaction=!1,function(){for(var _collection=lunarisExports._stores.lunarisOfflineTransactions.data,_version=_collection.begin(),j=0;j<offlineTransactionsInError.length;j++)_collection.remove(utils.clone(offlineTransactionsInError[j]),_version),delete offlineTransactionsInError[j]._id,offlineTransactionsInError[j].isInError=!0,_collection.add(offlineTransactionsInError[j],_version);_collection.commit(_version),offlineTransactionsInError=[],storeUtils.saveState(lunarisExports._stores.lunarisOfflineTransactions,_collection)}(),localStorage.set(OFFLINE_STORE,new Date),callback();function onEnd(error){cache.invalidate(_currentTransaction.store),error?(offlineTransactionsInError.push(_currentTransaction),_currentTransaction.method===OPERATIONS.INSERT&&function(storesToUpdate){var _lengthStoresToUpdate=storesToUpdate.length;if(_lengthStoresToUpdate)for(var i=offlineTransactions.length-1;i>=0;i--)for(var _transaction=offlineTransactions[i],j=0;j<_lengthStoresToUpdate;j++)_transaction.store===storesToUpdate[j]&&-1!==storesToUpdate.indexOf(_transaction.store)&&(indexedDB.del(OFFLINE_STORE,_transaction._id),offlineTransactionsInError.splice(1,0,offlineTransactions.splice(i,1)[0]))}(storeUtils.getStore(_currentTransaction.store).storesToPropagateReferences),hook.pushToHandlers(lunarisExports._stores.lunarisOfflineTransactions,"syncError")):hook.pushToHandlers(lunarisExports._stores.lunarisOfflineTransactions,"syncSuccess"),lunarisExports._stores.lunarisOfflineTransactions.data.remove(_currentTransaction),hook.pushToHandlers(lunarisExports._stores.lunarisOfflineTransactions,"delete",_currentTransaction),_processNextOfflineTransaction()}_currentTransaction.method===OPERATIONS.INSERT||_currentTransaction.method===OPERATIONS.UPDATE?imports.upsert(_currentTransaction.store,_currentTransaction.data,{isLocal:!1,retryOptions:_currentTransaction},onEnd):_currentTransaction.method===OPERATIONS.DELETE&&imports.deleteStore(_currentTransaction.store,_currentTransaction.data,{retryOptions:_currentTransaction},onEnd)}()},computeStoreTransactions:computeStoreTransactions,setOfflineHttpTransaction:function(storeName,method,request,value){var _collection=lunarisExports._stores.lunarisOfflineTransactions.data,_transactions=_collection.getAll();imports._clear(OFFLINE_STORE,!0),computeStoreTransactions(_transactions,storeName,method,request,value);for(var _version=_collection.begin(),i=0;i<_transactions.length;i++)delete _transactions[i]._id,_collection.add(_transactions[i],_version);_collection.commit(_version),storeUtils.saveState(lunarisExports._stores.lunarisOfflineTransactions,_collection),hook.pushToHandlers(lunarisExports._stores.lunarisOfflineTransactions,"insert")},getLastSyncDate:function(){return localStorage.get(OFFLINE_STORE)},setImportFunction:function(fn){imports[fn.name]=fn}}}([_exports_js,_store_store_hook_js,_utils_js,_store_store_utils_js,_store_store_collection_js,_store_store_transaction_js,_cache_js,_localStorageDriver_js,_localStorageDriver_js]),_store_crud__lazyLoad_js=function(imports,exports){var utils=imports[0],indexedDB=imports[1].indexedDB,lunarisExports=imports[2],storeUtils=imports[3],hooks=imports[4];function _end(store,fnAndParams){!function(store,callback){var _dependentStores=[];_dependentStores=_dependentStores.concat(store.storesToPropagate||[]).concat(store.storesToPropagateReferences||[]),utils.queue(_dependentStores,(function(storeToLoad,next){try{var _store=storeUtils.getStore("@"+storeToLoad)}catch(e){return next()}if(_store.isInitialized)return next();load(_store,[next,null])}),callback)}(store,(function(){fnAndParams[0].apply(null,fnAndParams[1])}))}function load(store,fnAndParams,isRetry){if(!lunarisExports.isBrowser)return store.isInitialized=!0,_end(store,fnAndParams);indexedDB.get("_states",store.name,(function(err,state){return err?isRetry?(lunaris.warn("lazy_load@"+store.name,err),_end(store,fnAndParams)):(store.isInitialized=!0,load(store,fnAndParams,!0)):state?(store.data.setCurrentId(state.collection.currentId),store.data.setCurrentRowId(state.collection.currentRowId),store.massOperations=state.massOperations,void indexedDB.getAll(store.name,(function(err,data){if(err)return isRetry?(lunaris.logger.warn(["lazy_load@"+store.name,"Error when retrieving store collection"],err),_end(store,fnAndParams)):(store.isInitialized=!0,load(store,fnAndParams,!0));utils.deleteRows(data),store.data.setData(data),store.isInitialized=!0,_end(store,fnAndParams)}))):(store.isInitialized=!0,_end(store,fnAndParams))}))}return exports.load=load,exports.register=function(store){var _watchedStores=[];for(i=0;i<store.filters.length;i++){var _handler=function(item){store.paginationCurrentPage=1,store.paginationOffset=0,hooks.pushToHandlers(store,"reset")},_filter=store.filters[i].source;-1===_watchedStores.indexOf(_filter)&&(hooks.hook("filterUpdated"+_filter,_handler,!1,!0),hooks.hook("reset"+_filter,_handler,!1,!0),_watchedStores.push(_filter),_filter=_filter.replace("@",""),lunarisExports._stores[_filter].isFilter=!0)}},exports}([_utils_js,_localStorageDriver_js,_exports_js,_store_store_utils_js,_store_store_hook_js],{}),_store_crud_upsert_js=function(imports,exports){var logger=imports[0],cache=imports[1],utils=imports[2],storeUtils=imports[3],offline=imports[4],hook=imports[5],crudUtils=imports[6],http=imports[7],url=imports[8],template=imports[9],sync=imports[10],lazyLoad=imports[11],OPERATIONS=utils.OPERATIONS;const MERGE_STRATEGIES_MERGE="merge",MERGE_STRATEGIES_ONLY_SERVER="only-server";imports={};function _updateCollectionIndexId(collection,value){return collection.removeIndexIdValue(value._id)}function _upsertCollection(store,collection,value,version,isMultipleItems,isUpdate,pathParts,request,method,isLocal,callback){var _inputValue=value;if(pathParts.length){store.massOperations[pathParts.join(".")]=value;var _data=collection.getAll();version=collection.begin();for(var i=0;i<_data.length;i++)storeUtils.setPathValue(pathParts,value,_data[i]),collection.upsert(_data[i],version)}else if(version=collection.begin(),isMultipleItems)for(i=0;i<value.length;i++)storeUtils.setObjectPathValues(store.massOperations,value[i]),collection.upsert(value[i],version);else{if(store.isStoreObject){var _value=collection.getAll(),_id=_value?_value._id:null;value._id=_id}offline.isOnline||isUpdate||storeUtils.setPrimaryKeyValue(store,value,store.isStoreObject?value._id:collection.getCurrentId()),storeUtils.setObjectPathValues(store.massOperations,value),collection.upsert(value,version)}if(value=collection.commit(version),isMultipleItems&&!offline.isOnline&&!isUpdate){for(version=collection.begin(),i=0;i<value.length;i++)storeUtils.setPrimaryKeyValue(store,value[i],value[i]._id),collection.upsert(value[i],version);value=collection.commit(version)}cache.invalidate(store.name);var _requestValue=value;if(isMultipleItems||store.isStoreObject||(_requestValue=_requestValue[0]),pathParts.length&&(_inputValue={op:"replace",path:storeUtils.getJSONPatchPath(pathParts.join(".")),value:_inputValue},_requestValue=_inputValue),!(request=url.create(store,method,storeUtils.getPrimaryKeyValue(store,_requestValue,!isUpdate||isUpdate&&isMultipleItems))))return callback("No url. Maybe the required filters are not set");request=request.request,offline.isOnline||store.isLocal||isLocal||sync.setOfflineHttpTransaction(store.name,method,request,isMultipleItems||store.isStoreObject?value:value[0]),crudUtils.propagate(store,value,method,(function(){crudUtils.afterAction(store,isUpdate?"update":"insert",value,null,(function(){storeUtils.saveState(store,collection,(function(){callback(null,{version:version,value:_requestValue,request:request})}))}))}))}function _upsertHTTPEvents(store,collection,value,isUpdate,method,callback){crudUtils.propagate(store,value,utils.OPERATIONS.UPDATE,(function(){crudUtils.afterAction(store,"update",value,null,(function(){crudUtils.afterAction(store,isUpdate?"updated":"inserted",value,template.getSuccess(null,store,method,!1),(function(){storeUtils.saveState(store,collection,(function(){if(store.isFilter)return hook.pushToHandlers(store,"filterUpdated",null,callback);callback(null,value)}))}))}))}))}function _mergeValue(collectionValue,serverValue,cloneFn,strategy=MERGE_STRATEGIES_MERGE){return strategy===MERGE_STRATEGIES_MERGE?utils.merge(cloneFn?cloneFn(collectionValue):collectionValue,serverValue):strategy===MERGE_STRATEGIES_ONLY_SERVER?(serverValue._id=collectionValue._id,serverValue._rowId=collectionValue._rowId,serverValue._version=collectionValue._version,serverValue):collectionValue}function _upsertHTTP(method,request,isUpdate,store,collection,value,isMultipleItems,version,options,callback){http.request(method,request,value,(function(err,data){if(err){var _error=template.getError(err,store,method,!1);return setLunarisError(store.name,method,request,value,version,err,_error),logger.warn(["lunaris."+(isUpdate?"update":"insert")+"@"+store.name],err),hook.pushToHandlers(store,"errorHttp",{error:_error,data:utils.cloneAndFreeze(value)},(function(){callback(err)}))}if(method===OPERATIONS.PATCH)return crudUtils.afterAction(store,"patched",null,callback);var _isEvent=!0,_pks=[];if(store.isStoreObject||!isMultipleItems){if(store.isStoreObject&&Array.isArray(data))return callback('The store "'+store.name+'" is a store object. The '+method+" method tries to "+(isUpdate?"update":"insert")+" multiple elements!");Array.isArray(data)&&(data=data[0]),value=_mergeValue(value,data,null,options.mergeStrategy);var _version=collection.begin();collection.upsert(value,_version),sync.isPushingOfflineTransaction&&method===OPERATIONS.INSERT&&(_updateCollectionIndexId(collection,value),_pks.push(["_"+value._id,storeUtils.getPrimaryKeyValue(store,value)])),(value=collection.commit(_version))||(_isEvent=!1)}else{var _isMultiple=Array.isArray(data);_version=collection.begin();for(var i=0;i<value.length;i++)if(_isMultiple)for(var j=0;j<data.length;j++)value[i]._id===data[j]._id&&(value[i]=_mergeValue(value[i],data[j],store.clone,options.mergeStrategy),collection.upsert(value[i],_version),sync.isPushingOfflineTransaction&&method===OPERATIONS.INSERT&&(_updateCollectionIndexId(collection,value[i]),_pks.push(["_"+value[i]._id,storeUtils.getPrimaryKeyValue(store,value[i])])));else value[i]=_mergeValue(value[i],data,null,options.mergeStrategy),collection.upsert(value[i],_version),sync.isPushingOfflineTransaction&&method===OPERATIONS.INSERT&&(_updateCollectionIndexId(collection,value[i]),_pks.push(["_"+value[i]._id,storeUtils.getPrimaryKeyValue(store,value[i])]));value=collection.commit(_version)}return sync.isPushingOfflineTransaction&&method===OPERATIONS.INSERT?crudUtils.propagateReferences(store,_pks,(function(){if(sync.updateOfflineTransactionData(store.storesToPropagateReferences),!_isEvent)return callback();_upsertHTTPEvents(store,collection,value,isUpdate,method,callback)})):_isEvent?void _upsertHTTPEvents(store,collection,value,isUpdate,method,callback):callback()}))}function _upsertLocal(store,value,isUpdate,isLocal,callback){if(store.isLocal||isLocal)return store.isFilter?crudUtils.propagate(store,value,isUpdate?utils.OPERATIONS.UPDATE:utils.OPERATIONS.INSERT,(function(){hook.pushToHandlers(store,"filterUpdated",null,callback)})):crudUtils.propagate(store,value,isUpdate?utils.OPERATIONS.UPDATE:utils.OPERATIONS.INSERT,callback);callback()}function _upsert(store,collection,pathParts,value,isUpdate,options,callback){if(!store.isInitialized)return lazyLoad.load(store,[_upsert,arguments]);var _version,_isMultipleItems=Array.isArray(value),_request="/";options.retryOptions&&(_request=options.retryOptions.url);var _method=OPERATIONS.UPDATE;return isUpdate||(_method=OPERATIONS.INSERT),pathParts.length&&(_method=OPERATIONS.PATCH),options.retryOptions?(_version=options.retryOptions.version,offline.isOnline?void _upsertHTTP(_method,_request,isUpdate,store,collection,value,_isMultipleItems,_version,options,callback):callback(null,value)):_upsertCollection(store,collection,value,_version,_isMultipleItems,isUpdate,pathParts,_request,_method,options.isLocal,(function(err,_res){if(err)return callback(err);_version=_res.version,value=_res.value,_request=_res.request,_upsertLocal(store,value,isUpdate,options.isLocal,(function(){if(store.isLocal||options.isLocal||!offline.isOnline)return callback(null,value);_upsertHTTP(_method,_request,isUpdate,store,collection,value,_isMultipleItems,_version,options,callback)}))}))}function upsert(store,value,options,callback){"function"==typeof options&&(callback=options,options={}),options||(options={});var _isUpdate=!1,_storeParts=store&&"string"==typeof store?store.split(":"):[];_storeParts.length&&(store=_storeParts.shift()),_storeParts.length&&(_isUpdate=!0);var _eventName="lunaris."+(_isUpdate?"update":"insert")+store;try{options.retryOptions&&(value=options.retryOptions.data);var _options=crudUtils.beforeAction(store,value);if((Array.isArray(value)&&null!==value[0]._id&&void 0!==value[0]._id||null!==value._id&&void 0!==value._id)&&(_isUpdate=!0),options.retryOptions&&options.retryOptions.method===OPERATIONS.INSERT&&(_isUpdate=!1),_options.store.validateFn&&!_storeParts.length&&!options.retryOptions)return imports.validate(store,_options.value,_isUpdate,(function(res){if(!res){let error="Error when validating data";if(callback)return callback(error)}_upsert(_options.store,_options.collection,_storeParts,_options.value,_isUpdate,options,(function(err,res){if(err){if(callback)return callback(err);throw err}callback&&callback(null,res)}))}),_eventName);_upsert(_options.store,_options.collection,_storeParts,_options.value,_isUpdate,options,(function(err,res){if(err){if(callback)return callback(err);throw err}callback&&callback(null,res)}))}catch(e){logger.warn([_eventName],e)}}function setLunarisError(storeName,method,request,value,version,err,error){upsert("@lunarisErrors",{version:version,data:value,url:request,method:method,storeName:storeName,date:dayjs(),messageError:error,messageErrorServer:err})}return sync.setImportFunction(upsert),exports.upsert=upsert,exports.setLunarisError=setLunarisError,exports.setImportFunction=function(fn){imports[fn.name]=fn},exports}([_logger_js,_cache_js,_utils_js,_store_store_utils_js,_offline_js,_store_store_hook_js,_store_crud_crudUtils_js,_http_js,_store_store_url_js,_store_store_template_js,_store_store_synchronisation_js,_store_crud__lazyLoad_js],{}),_md5_js=function(imports,exports){var hexcase=0;function rstr2binl(input){for(var output=Array(input.length>>2),i=0;i<output.length;i++)output[i]=0;for(i=0;i<8*input.length;i+=8)output[i>>5]|=(255&input.charCodeAt(i/8))<<i%32;return output}function binl2rstr(input){for(var output="",i=0;i<32*input.length;i+=8)output+=String.fromCharCode(input[i>>5]>>>i%32&255);return output}function binl_md5(x,len){x[len>>5]|=128<<len%32,x[14+(len+64>>>9<<4)]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i<x.length;i+=16){var olda=a,oldb=b,oldc=c,oldd=d;a=md5_ff(a,b,c,d,x[i+0],7,-680876936),d=md5_ff(d,a,b,c,x[i+1],12,-389564586),c=md5_ff(c,d,a,b,x[i+2],17,606105819),b=md5_ff(b,c,d,a,x[i+3],22,-1044525330),a=md5_ff(a,b,c,d,x[i+4],7,-176418897),d=md5_ff(d,a,b,c,x[i+5],12,1200080426),c=md5_ff(c,d,a,b,x[i+6],17,-1473231341),b=md5_ff(b,c,d,a,x[i+7],22,-45705983),a=md5_ff(a,b,c,d,x[i+8],7,1770035416),d=md5_ff(d,a,b,c,x[i+9],12,-1958414417),c=md5_ff(c,d,a,b,x[i+10],17,-42063),b=md5_ff(b,c,d,a,x[i+11],22,-1990404162),a=md5_ff(a,b,c,d,x[i+12],7,1804603682),d=md5_ff(d,a,b,c,x[i+13],12,-40341101),c=md5_ff(c,d,a,b,x[i+14],17,-1502002290),a=md5_gg(a,b=md5_ff(b,c,d,a,x[i+15],22,1236535329),c,d,x[i+1],5,-165796510),d=md5_gg(d,a,b,c,x[i+6],9,-1069501632),c=md5_gg(c,d,a,b,x[i+11],14,643717713),b=md5_gg(b,c,d,a,x[i+0],20,-373897302),a=md5_gg(a,b,c,d,x[i+5],5,-701558691),d=md5_gg(d,a,b,c,x[i+10],9,38016083),c=md5_gg(c,d,a,b,x[i+15],14,-660478335),b=md5_gg(b,c,d,a,x[i+4],20,-405537848),a=md5_gg(a,b,c,d,x[i+9],5,568446438),d=md5_gg(d,a,b,c,x[i+14],9,-1019803690),c=md5_gg(c,d,a,b,x[i+3],14,-187363961),b=md5_gg(b,c,d,a,x[i+8],20,1163531501),a=md5_gg(a,b,c,d,x[i+13],5,-1444681467),d=md5_gg(d,a,b,c,x[i+2],9,-51403784),c=md5_gg(c,d,a,b,x[i+7],14,1735328473),a=md5_hh(a,b=md5_gg(b,c,d,a,x[i+12],20,-1926607734),c,d,x[i+5],4,-378558),d=md5_hh(d,a,b,c,x[i+8],11,-2022574463),c=md5_hh(c,d,a,b,x[i+11],16,1839030562),b=md5_hh(b,c,d,a,x[i+14],23,-35309556),a=md5_hh(a,b,c,d,x[i+1],4,-1530992060),d=md5_hh(d,a,b,c,x[i+4],11,1272893353),c=md5_hh(c,d,a,b,x[i+7],16,-155497632),b=md5_hh(b,c,d,a,x[i+10],23,-1094730640),a=md5_hh(a,b,c,d,x[i+13],4,681279174),d=md5_hh(d,a,b,c,x[i+0],11,-358537222),c=md5_hh(c,d,a,b,x[i+3],16,-722521979),b=md5_hh(b,c,d,a,x[i+6],23,76029189),a=md5_hh(a,b,c,d,x[i+9],4,-640364487),d=md5_hh(d,a,b,c,x[i+12],11,-421815835),c=md5_hh(c,d,a,b,x[i+15],16,530742520),a=md5_ii(a,b=md5_hh(b,c,d,a,x[i+2],23,-995338651),c,d,x[i+0],6,-198630844),d=md5_ii(d,a,b,c,x[i+7],10,1126891415),c=md5_ii(c,d,a,b,x[i+14],15,-1416354905),b=md5_ii(b,c,d,a,x[i+5],21,-57434055),a=md5_ii(a,b,c,d,x[i+12],6,1700485571),d=md5_ii(d,a,b,c,x[i+3],10,-1894986606),c=md5_ii(c,d,a,b,x[i+10],15,-1051523),b=md5_ii(b,c,d,a,x[i+1],21,-2054922799),a=md5_ii(a,b,c,d,x[i+8],6,1873313359),d=md5_ii(d,a,b,c,x[i+15],10,-30611744),c=md5_ii(c,d,a,b,x[i+6],15,-1560198380),b=md5_ii(b,c,d,a,x[i+13],21,1309151649),a=md5_ii(a,b,c,d,x[i+4],6,-145523070),d=md5_ii(d,a,b,c,x[i+11],10,-1120210379),c=md5_ii(c,d,a,b,x[i+2],15,718787259),b=md5_ii(b,c,d,a,x[i+9],21,-343485551),a=safe_add(a,olda),b=safe_add(b,oldb),c=safe_add(c,oldc),d=safe_add(d,oldd)}return Array(a,b,c,d)}function md5_cmn(q,a,b,x,s,t){return safe_add((num=safe_add(safe_add(a,q),safe_add(x,t)))<<(cnt=s)|num>>>32-cnt,b);var num,cnt}function md5_ff(a,b,c,d,x,s,t){return md5_cmn(b&c|~b&d,a,b,x,s,t)}function md5_gg(a,b,c,d,x,s,t){return md5_cmn(b&d|c&~d,a,b,x,s,t)}function md5_hh(a,b,c,d,x,s,t){return md5_cmn(b^c^d,a,b,x,s,t)}function md5_ii(a,b,c,d,x,s,t){return md5_cmn(c^(b|~d),a,b,x,s,t)}function safe_add(x,y){var lsw=(65535&x)+(65535&y);return(x>>16)+(y>>16)+(lsw>>16)<<16|65535&lsw}return function(s){return function(input){for(var x,hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef",output="",i=0;i<input.length;i++)x=input.charCodeAt(i),output+=hex_tab.charAt(x>>>4&15)+hex_tab.charAt(15&x);return output}(function(s){return binl2rstr(binl_md5(rstr2binl(s),8*s.length))}(function(input){var x,y,output="",i=-1;for(;++i<input.length;)x=input.charCodeAt(i),y=i+1<input.length?input.charCodeAt(i+1):0,55296<=x&&x<=56319&&56320<=y&&y<=57343&&(x=65536+((1023&x)<<10)+(1023&y),i++),x<=127?output+=String.fromCharCode(x):x<=2047?output+=String.fromCharCode(192|x>>>6&31,128|63&x):x<=65535?output+=String.fromCharCode(224|x>>>12&15,128|x>>>6&63,128|63&x):x<=2097151&&(output+=String.fromCharCode(240|x>>>18&7,128|x>>>12&63,128|x>>>6&63,128|63&x));return output}(s)))}}(),_store_store_offline_js=function(imports,exports){var utils=imports[0],OPERATORS=utils.OPERATORS,cache=imports[1],md5=imports[2],url=imports[3];function _transformCacheData(obj,cloneFn){var _clonedData=cloneFn(obj);return delete _clonedData._id,delete _clonedData._version,delete _clonedData._rowId,_clonedData}function ilike(filterValue,objValue){for(var _document=objValue.split(" "),j=0;j<filterValue.length;j++)for(var _nbSearchWordHasBeenFound=0,k=0;k<filterValue[j].length;k++)for(var i=0;i<_document.length;i++){if(-1!==utils.unaccent(_document[i]).toLowerCase().indexOf(filterValue[j][k])&&++_nbSearchWordHasBeenFound>=filterValue[j].length)return!0}return!1}function _reduce(filterFn,filter,data,isRequiredFilter){if(!filterFn&&filter[3]!==OPERATORS.ILIKE||!filter)return data;var _filterValue=filter[2];if("ILIKE"===filter[3]&&!isRequiredFilter){Array.isArray(_filterValue)||(_filterValue=[_filterValue]);for(var _searchWords=[],k=0;k<_filterValue.length;k++)_filterValue[k]=utils.unaccent(_filterValue[k]),_searchWords.push(_filterValue[k].toLowerCase().split(" "));_filterValue=_searchWords}for(var _res=[],i=0,len=data.length;i<len;i++)filterFn.call(null,_filterValue,data[i],ilike)&&_res.push(data[i]);return _res}return exports.filter=function(store,collection,filterValues){var _data=collection.getAll(null,!1,!1);if(!filterValues||!store.filterFns)return _data;store.isStoreObject&&(_data=[_data]);for(var _requiredFilters=Object.keys(filterValues.requiredOptions),i=0;i<_requiredFilters.length;i++)void 0!==store.filterFns[_requiredFilters[i]]&&(_data=_reduce(store.filterFns[_requiredFilters[i]],filterValues.requiredOptions[_requiredFilters[i]],_data,!0));var _optionalFilters=Object.keys(filterValues.optionalOptions);for(i=0;i<_optionalFilters.length;i++)void 0!==store.filterFns[_optionalFilters[i]]&&(_data=_reduce(store.filterFns[_optionalFilters[i]],filterValues.optionalOptions[_optionalFilters[i]],_data,!1));return store.isStoreObject?_data=_data[0]||null:function(store,filterValues,data){for(var _len=data.length,_cacheValues=[],j=0;j<_len&&j<store.paginationLimit;j++)_cacheValues.push(_transformCacheData(data[j],store.clone));if(filterValues.cache.offset=0,filterValues.cache.limit=store.paginationLimit,cache.add(store.name,md5(url.createForOffline(store,filterValues)),_cacheValues),_len<=store.paginationLimit)return data;var _dataToReturn=data.slice(0,store.paginationLimit);_cacheValues=[];for(var _n=0,i=store.paginationLimit;i<_len;i++)_n++,_cacheValues.push(_transformCacheData(data[i],store.clone)),_n%store.paginationLimit&&i+1!==_len||(filterValues.cache.offset+=store.paginationLimit,cache.add(store.name,md5(url.createForOffline(store,filterValues)),_cacheValues),_cacheValues=[]);return _dataToReturn}(store,filterValues,_data)},exports.ilike=ilike,exports}([_utils_js,_cache_js,_md5_js,_store_store_url_js],{}),_store_store_js=function(imports,exports){var lunarisExports=imports[0],utils=imports[1],storeUtils=imports[2],logger=imports[3],collection=imports[4],offline=imports[5],crudUtils=imports[6],upsertCRUD=imports[7],getCRUD=imports[8],clearCrud=imports[9],deleteCrud=imports[10],storeUrl=imports[11],emptyObject=(imports[12].indexedDB,{});function validate(store,value,isUpdate,callback,eventName){try{var _isUpdate=isUpdate;storeUtils.checkArgs(store,value,!0),callback||(callback=isUpdate,_isUpdate=!1,(Array.isArray(value)&&value[0]._id||value._id)&&(_isUpdate=!0));var _store=storeUtils.getStore(store);if(_store.validateFn){var _valueToValidate=value;if(_store.isStoreObject&&Array.isArray(value))throw new Error('The store "'+store.name+'" is a store object, you cannot add or update multiple elements!');_store.isStoreObject||Array.isArray(value)||(_valueToValidate=[value]);var _isValidatingPK=!!offline.isOnline&&_isUpdate;return _store.validateFn(_valueToValidate,_store.onValidate,_isValidatingPK,(function(err){if(err.length){for(var i=0;i<err.length;i++)logger.warn(["lunaris."+(_isUpdate?"update":"insert")+store+" Error when validating data"],err[i]);return callback(!1,err)}callback(!0)}))}throw new Error("The store does not have a map! You cannot validate a store without a map.")}catch(e){logger.warn([eventName||"lunaris.validate"+store],e)}}return lunarisExports._stores.lunarisErrors={name:"lunarisErrors",data:collection.collection(null,!1,null,null,null,"lunarisErrors",null,utils.clone),filters:[],paginationLimit:50,paginationOffset:0,paginationCurrentPage:1,hooks:{},nameTranslated:"${store.lunarisErrors}",isLocal:!0,storesToPropagate:[],isStoreObject:!1,massOperations:{},clone:utils.clone},upsertCRUD.setImportFunction(validate),exports.get=getCRUD.get,exports.load=getCRUD.load,exports.getOne=function(store,id,isPrimaryKey){try{var _item,_options=crudUtils.beforeAction(store,null,!0);if(!(_item=id?_options.collection.get(id,isPrimaryKey):_options.collection.getFirst()))return;return utils.cloneAndFreeze(_item)}catch(e){logger.warn(["lunaris.getOne"+store],e)}},exports.insert=upsertCRUD.upsert,exports.update=upsertCRUD.upsert,exports.upsert=upsertCRUD.upsert,exports.delete=deleteCrud.delete,exports.clear=clearCrud.clear,exports.rollback=function(store,version){try{crudUtils.beforeAction(store,null,!0).collection.rollback(version)}catch(e){logger.warn(["lunaris.rollback"+store],e)}},exports.getDefaultValue=function(store){try{var _options=crudUtils.beforeAction(store,null,!0);return _options.store.defaultValue?utils.clone(_options.store.defaultValue):emptyObject}catch(e){logger.warn(["lunaris.getDefaultValue"+store],e)}},exports.validate=validate,exports.setPagination=function(store,page,limit){try{var _options=crudUtils.beforeAction(store,null,!0);_options.store.paginationLimit=limit||_options.store.paginationLimit,_options.store.paginationCurrentPage=page||1,_options.store.paginationOffset=_options.store.paginationLimit*_options.store.paginationCurrentPage-_options.store.paginationLimit,storeUtils.saveState(_options.store,_options.collection)}catch(e){logger.warn(["lunaris.setPagination"+store],e)}},exports.createUrl=function(store,method,primaryKey){try{var _options=crudUtils.beforeAction(store,null,!0);if(!method)throw new Error("Must provide a method, ex: GET, POST, etc.");var _request=storeUrl.create(_options.store,method,primaryKey);return _request?_request.request:void 0}catch(e){logger.warn(["lunaris.createUrl"],e)}},exports}([_exports_js,_utils_js,_store_store_utils_js,_logger_js,_store_store_collection_js,_offline_js,_store_crud_crudUtils_js,_store_crud_upsert_js,function(imports,exports){var storeOffline=imports[0],md5=imports[1],http=imports[2],logger=imports[3],cache=imports[4],url=imports[5],utils=imports[6],storeUtils=imports[7],crudUtils=imports[8],offline=imports[9],hook=imports[10],template=imports[11],upsertCRUD=imports[12],indexedDB=imports[13].indexedDB,lazyLoad=imports[14],getRequestQueue={};utils.OPERATIONS;function _processNextGetRequest(store){var _getRequest=getRequestQueue[store].shift();_getRequest&&(_getRequest=_getRequest.concat([_processNextGetRequest]),_get.apply(null,_getRequest))}function _returnCacheValues(store,collection,request,cacheValues,options,nextGet){var _values=[];return"object"==typeof cacheValues&&(storeUtils.saveState(store,collection),_values=function(collection,values){var _version=collection.begin();if(Array.isArray(values))for(var i=0;i<values.length;i++)collection.add(values[i],_version);else collection.add(values,_version);return collection.commit(_version)}(collection,store.clone(cacheValues))),crudUtils.afterAction(store,"get",_values,null,(function(){if(store.isFilter)return hook.pushToHandlers(store,"filterUpdated",null,(function(){options.callback(null,_values),nextGet("@"+store.name)}));options.callback(null,_values),nextGet("@"+store.name)}))}function _returnLocalValues(store,collection,request,options,nextGet){var _res=storeOffline.filter(store,collection,request);crudUtils.afterAction(store,"get",_res,null,(function(){if(store.isFilter&&(store.isStoreObject&&_res||!store.isStoreObject&&_res.length))return hook.pushToHandlers(store,"filterUpdated",null,(function(){storeUtils.saveState(store,collection,(function(){options.callback(null,_res),nextGet("@"+store.name)}))}));storeUtils.saveState(store,collection,(function(){options.callback(null,_res),nextGet("@"+store.name)}))}))}function _getHTTP(store,collection,request,primaryKeyValue,options,nextGet){http.request("GET",request,null,(function(err,data){if(err){var _error=template.getError(err,store,"GET",!0);return upsertCRUD.setLunarisError(store.name,"GET",request,null,null,err,_error),logger.warn(["lunaris.get@"+store.name],err),hook.pushToHandlers(store,"errorHttp",{error:_error},(function(){options.callback(err),nextGet("@"+store.name)}))}var _version=collection.begin();if(Array.isArray(data)){if(store.isStoreObject)return err='The store "'+store.name+'" is an object store. The GET method cannot return multiple elements!',logger.warn(["lunaris.get@"+store.name],new Error(err)),options.callback(err),nextGet("@"+store.name);cache.add(store.name,md5(request),store.clone(data));for(var i=0;i<data.length;i++)collection.upsert(data[i],_version);primaryKeyValue&&data.length&&(data=data[0])}else{if(store.isStoreObject){var _value=collection.getAll(),_id=_value?_value._id:null;data._id=_id}cache.add(store.name,md5(request),store.clone(data)),collection.upsert(data,_version)}data=collection.commit(_version),crudUtils.propagate(store,data,utils.OPERATIONS.INSERT,(function(){crudUtils.afterAction(store,"get",data,null,(function(){if(store.isFilter)return hook.pushToHandlers(store,"filterUpdated",null,(function(){storeUtils.saveState(store,collection,(function(){options.callback(null,data),nextGet("@"+store.name)}))}));storeUtils.saveState(store,collection,(function(){options.callback(null,data),nextGet("@"+store.name)}))}))}))}),{store:store.name})}function _get(store,primaryKeyValue,options,next){try{var _options=crudUtils.beforeAction(store,null,!0);if(!_options.store.isInitialized)return lazyLoad.load(_options.store,[_get,arguments]);var _request="/";let isPaginated=!0;if(!1===_options.store.isPaginated&&(isPaginated=!1),null!=options.isPaginated&&(isPaginated=options.isPaginated),_request=url.create(_options.store,"GET",primaryKeyValue,isPaginated),isPaginated&&(_options.store.paginationOffset=_options.store.paginationLimit*_options.store.paginationCurrentPage,_options.store.paginationCurrentPage++),!_request)return options.callback("No url. Maybe the required filters are not set"),next(store);var _cacheValues=cache.get(store.name,md5(_request.request));if(_cacheValues)return _returnCacheValues(_options.store,_options.collection,_request.request,_cacheValues,options,next);if(!offline.isOnline||_options.store.isLocal)return _returnLocalValues(_options.store,_options.collection,_request,options,next);_getHTTP(_options.store,_options.collection,_request.request,primaryKeyValue,options,next)}catch(e){logger.warn(["lunaris.get"+store],e)}}return exports.get=function(store,primaryKeyValue,options,callback){getRequestQueue[store]||(getRequestQueue[store]=[]),"function"==typeof primaryKeyValue&&(callback=primaryKeyValue,primaryKeyValue=null),"function"==typeof options&&(callback=options,options=null),"object"==typeof primaryKeyValue&&(options=primaryKeyValue,primaryKeyValue=null),options||(options={}),options.callback=callback||function(){},getRequestQueue[store].push([store,primaryKeyValue,options]),1===getRequestQueue[store].length&&_processNextGetRequest(store)},exports.load=function(store,options,callback){"function"==typeof options&&(callback=options,options=null),callback||(callback=function(){}),options||(options={});try{if(!offline.isRealOnline)throw new Error("You are offline!");if(!offline.isOfflineMode)throw new Error("Offline mode is not enabled!");var _options=crudUtils.beforeAction(store,null,!0);if(_options.store.isLocal)throw new Error("The store is local!");null==options&&(options={}),_options.store.paginationCurrentPage=1,_options.store.paginationOffset=0,_options.store.paginationLimit=50,_options.store.massOperations={},cache.invalidate(_options.store.name),_options.collection.clear(),indexedDB.clear(_options.store.name),storeUtils.saveState(_options.store,_options.collection,(function(){options.limit&&(_options.store.paginationLimit=options.limit);var _request=url.create(_options.store,"GET",null,!!options.limit).request;http.request("GET",_request,null,(function(err,data){if(err){var _error=template.getError(err,_options.store,"GET",!0);return upsertCRUD.setLunarisError(_options.store.name,"GET",_request,null,null,err,_error),logger.warn(["lunaris.load@"+_options.store.name],err),hook.pushToHandlers(_options.store,"errorHttp",{error:_error},(function(){callback&&callback()}))}Array.isArray(data)||(data=[data]);for(var _version=_options.collection.begin(),i=0,len=data.length;i<len;i++)_options.collection.add(data[i],_version);_options.collection.commit(_version),storeUtils.saveState(_options.store,_options.collection,(function(){hook.pushToHandlers(_options.store,"loaded",null,(function(){callback&&callback()}))}))}),{isOffline:!0,store:_options.store.name})}))}catch(e){logger.warn(["lunaris.load"+store],e)}},exports}([_store_store_offline_js,_md5_js,_http_js,_logger_js,_cache_js,_store_store_url_js,_utils_js,_store_store_utils_js,_store_crud_crudUtils_js,_offline_js,_store_store_hook_js,_store_store_template_js,_store_crud_upsert_js,_localStorageDriver_js,_store_crud__lazyLoad_js],{}),function(imports,exports){var logger=imports[0],cache=imports[1],utils=imports[2],storeUtils=imports[3],crudUtils=imports[4],offline=imports[5],hook=imports[6],lunarisExports=imports[7],sync=imports[8],indexedDB=imports[9].indexedDB,OPERATIONS=utils.OPERATIONS;function _clearPropagate(store,collection,callback){crudUtils.propagate(store,null,OPERATIONS.DELETE,(function(){storeUtils.saveState(store,collection,callback)}))}function _clearSendEvents(store,collection,isSilent,callback){if(!isSilent)return _clearPropagate(store,collection,(function(){hook.pushToHandlers(store,"clear",null,(function(){hook.pushToHandlers(store,"reset",null,callback)}))}));_clearPropagate(store,collection,callback)}function _clear(store,options,callback){try{var _options=crudUtils.beforeAction(store,null,!0);if(_options.store.paginationCurrentPage=1,_options.store.paginationOffset=0,_options.store.paginationLimit=50,_options.store.massOperations={},cache.invalidate(_options.store.name),offline.isOnline||_options.store.isLocal)return _options.collection.clear(),indexedDB.clear(_options.store.name,(function(){_clearSendEvents(_options.store,_options.collection,options.isSilent,callback)}));_clearSendEvents(_options.store,_options.collection,options.isSilent,callback)}catch(e){callback(e),logger.warn(["lunaris.clear"+store],e)}}return sync.setImportFunction(_clear),exports.clear=function(store,options,callback){if("function"==typeof options&&(callback=options,options=null),"boolean"==typeof options&&(options={isSilent:options}),options||(options={}),options.isSilent=options.isSilent||!1,/\*$/.test(store)){if(!/^@/.test(store))return logger.warn(["lunaris.clear"],new Error("The store key must begin by '@'"));var _keyLength=store.length-2,_key=store.slice(1,_keyLength+1);return utils.queue(Object.keys(lunarisExports._stores),(function(store,next){if(store.slice(0,_keyLength)!==_key)return next();_clear("@"+store,options,next)}),(function(){callback&&callback()}))}_clear(store,options,(function(err){callback&&callback(err)}))},exports}([_logger_js,_cache_js,_utils_js,_store_store_utils_js,_store_crud_crudUtils_js,_offline_js,_store_store_hook_js,_exports_js,_store_store_synchronisation_js,_localStorageDriver_js],{}),function(imports,exports){var logger=imports[0],cache=imports[1],utils=imports[2],storeUtils=imports[3],offline=imports[4],hook=imports[5],crudUtils=imports[6],http=imports[7],url=imports[8],template=imports[9],sync=imports[10],upsertCrud=imports[11],lazyLoad=imports[12],queue=utils.queue,OPERATIONS=utils.OPERATIONS;function _deleteLocal(store,collection,value,isLocal,callback){var _version=collection.begin();!function(store,collection,value,callback){if(!store.storesToPropagateReferences.length)return callback();if(null==collection.getIndexDataCache()[value._id])return callback();var _pkValue=storeUtils.getPrimaryKeyValue(store,collection.get(value._id));queue(store.storesToPropagateReferences,(function(storeToPropagate,next){var _store=storeUtils.getStore("@"+storeToPropagate),_references=storeUtils.getCollection(_store).getIndexReferences();if(!_references[store.name])return next();if(!_references[store.name][_pkValue])return next();var error="${Cannot delete the value, it is still referenced in the store} "+_store.nameTranslated;hook.pushToHandlers(store,"error",{error:error,data:null},(function(){callback(!0)}))}),callback)}(store,collection,value,(function(isError){if(isError)return callback(isError);collection.remove(value,_version,!isLocal),value=collection.commit(_version);var _isArray=Array.isArray(value);if(isLocal&&(!_isArray&&!value||_isArray&&!value.length))return callback(new Error("You cannot delete a value not in the store!"));crudUtils.propagate(store,value,utils.OPERATIONS.DELETE,(function(){crudUtils.afterAction(store,"delete",value,null,(function(){store.isStoreObject||(value=value[0]),cache.invalidate(store.name),storeUtils.saveState(store,collection,(function(){callback(null,[_version,value])}))}))}))}))}function _deleteHttp(store,collection,value,version,options,callback){if(store.isLocal||options.isLocal)return callback(null,value);var _request="/";if(options.retryOptions)_request=options.retryOptions.url;else{if(!(_request=url.create(store,"DELETE",storeUtils.getPrimaryKeyValue(store,value))))return callback("No url. Maybe the required filters are not set");_request=_request.request}if(!offline.isOnline)return sync.setOfflineHttpTransaction(store.name,OPERATIONS.DELETE,_request,value),callback();http.request("DELETE",_request,null,(function(err,data){if(err){var _error=template.getError(err,store,"DELETE",!1);return upsertCrud.setLunarisError(store.name,"DELETE",_request,value,version,err,_error),logger.warn(["lunaris.delete@"+store.name],err),hook.pushToHandlers(store,"errorHttp",{error:_error,data:value},(function(){callback(err)}))}_deleteLocal(store,collection,data,!1,(function(err,dataCollection){if(err)return callback(err);dataCollection[1]&&(value=dataCollection[1]),crudUtils.afterAction(store,"deleted",utils.merge(value,data),template.getSuccess(null,store,"DELETE",!1),(function(){callback(null,utils.merge(value,data))}))}))}))}function deleteStore(store,value,options,callback){"function"==typeof options&&(callback=options,options={}),options||(options={}),callback=callback||function(){};try{options.retryOptions&&(value=options.retryOptions.data);var _version,_options=crudUtils.beforeAction(store,value);if(!_options.store.isInitialized)return lazyLoad.load(_options.store,[deleteStore,arguments]);if(!options.retryOptions)return _deleteLocal(_options.store,_options.collection,value,!0,(function(err,data){if(err)throw callback(err),err;_version=data[0],value=data[1],_deleteHttp(_options.store,_options.collection,value,_version,options,(function(err,data){if(err)throw callback(err),err;callback(null,data)}))}));_version=options.retryOptions.version,_deleteHttp(_options.store,_options.collection,value,_version,options,(function(err,data){if(err)throw callback(err),err;callback(null,data)}))}catch(e){logger.warn(["lunaris.delete"+store],e)}}return sync.setImportFunction(deleteStore),exports.delete=deleteStore,exports}([_logger_js,_cache_js,_utils_js,_store_store_utils_js,_offline_js,_store_store_hook_js,_store_crud_crudUtils_js,_http_js,_store_store_url_js,_store_store_template_js,_store_store_synchronisation_js,_store_crud_upsert_js,_store_crud__lazyLoad_js],{}),_store_store_url_js,_localStorageDriver_js],{}),_websocket_js=function(imports,exports){var logger=imports[0],offline=imports[2],ws=null,lastInterval=200,timeout=null,isReload=!1,handlers={};function connect(host){ws||((ws=new WebSocket(host)).onopen=function(){lastInterval=200,logger.info("[Websocket]","Connected!"),_send("invalidations")},ws.onerror=function(evt){},ws.onclose=function(evt){isReload||function(host){ws=null,(lastInterval*=1.2)>2e4&&(lastInterval=2e4),logger.info("[Websocket]","Reconnect to websocket server in "+lastInterval.toFixed(2)+"ms"),timeout=setTimeout((function(){offline.isOnline||clearTimeout(timeout),connect(host)}),lastInterval)}(host)},ws.onmessage=function(msg){if(msg.data)try{var message=JSON.parse(msg.data);handlers[message.channel]&&handlers[message.channel].call(null,message)}catch(e){logger.warn("[Websocket] Cannot parse incomming message",e)}})}function _send(channel,data){ws.send(JSON.stringify({channel:channel,data:data,ts:Date.now()}))}return imports[1].isBrowser&&(window.onbeforeunload=function(){isReload=!0}),{_handlers:handlers,connect:connect,send:function(channel,data){ws.readyState===WebSocket.OPEN&&_send(channel,data)},stop:function(callback){ws?(isReload=!0,ws.onclose=function(){callback&&callback(),isReload=!1},ws.close()):callback&&callback()},subscribe:(channel,handler)=>"function"!=typeof handler?logger.warn("[lunaris.websocket.subscribe] Handler is not a function"):"invalidated"!==channel&&"invalidations"!==channel||!handlers[channel]?void(handlers[channel]=handler):logger.warn("[lunaris.websocket.subscribe] Given channel is reserved"),unsubscribe(channel){delete handlers[channel]}}}([_logger_js,_exports_js,_offline_js]),_invalidate_js=function(imports,exports){var indexedDB=imports[0].indexedDB,lunarisExports=imports[1],cache=imports[2],store=imports[3],logger=imports[4],offline=imports[5],storeUtils=imports[6],clientLightUrlInvalidations={},events={},INVALIDATE_EVENTS_INVALIDATE="invalidate";return{invalidations:clientLightUrlInvalidations,init:function(callback){indexedDB.getAll("_invalidations",(function(err,res){if(err)return callback();for(var i=0;i<res.length;i++)clientLightUrlInvalidations[res[i].url]=res[i].date;callback()}))},invalidate:function(storeOrUrl){if(null!=storeOrUrl&&"string"==typeof storeOrUrl)if(/^GET\s/.test(storeOrUrl)){if(!lunarisExports.urlsGraph[storeOrUrl])return;if(offline.isOfflineMode&&!offline.isSynchronizing)return void(events[INVALIDATE_EVENTS_INVALIDATE]&&events[INVALIDATE_EVENTS_INVALIDATE](storeOrUrl));url=storeOrUrl,dateInvalidations=Date.now(),clientLightUrlInvalidations[url]=dateInvalidations,indexedDB.upsert("_invalidations",{url:url,date:dateInvalidations});for(var i=0,len=lunarisExports.urlsGraph[storeOrUrl].length;i<len;i++){var _store=lunarisExports.urlsGraph[storeOrUrl][i];logger.info("[Invalidate] "+storeOrUrl+" -> @"+_store);var _storeInstance=storeUtils.getStore(_store);_storeInstance&&!1===_storeInstance.isInvalidable||store.clear("@"+_store)}}else{var url,dateInvalidations;cache.invalidate(storeOrUrl)}},computeInvalidations:function(lightUrlInvalidations,stores){var _storesToDeleteStates=[],_invalidations=[];function searchAndRemove(url){if(lunarisExports.urlsGraph[url]){var dateInvalidations=Date.now();clientLightUrlInvalidations[url]=dateInvalidations,_invalidations.push({url:url,date:dateInvalidations});for(var i=0,len=lunarisExports.urlsGraph[url].length;i<len;i++){var index=stores.indexOf(lunarisExports.urlsGraph[url][i]);-1!==index&&(store.clear("@"+stores[index]),stores.splice(index,1))}}}for(var url in lunarisExports.urlsGraph)!lightUrlInvalidations[url]&&clientLightUrlInvalidations[url]||(!lightUrlInvalidations[url]||clientLightUrlInvalidations[url]?clientLightUrlInvalidations[url]<lightUrlInvalidations[url]&&searchAndRemove(url):searchAndRemove(url));_storesToDeleteStates.length&&indexedDB.del("_states",_storesToDeleteStates),_invalidations.length&&indexedDB.upsert("_invalidations",_invalidations)},on:function(event,handler){events[event]=handler}}}([_localStorageDriver_js,_exports_js,_cache_js,_store_store_js,_logger_js,_offline_js,_store_store_utils_js]),_store_dataQuery_queryResultSet_js=function(imports,exports){var ilike=imports[0].ilike,utils=imports[1];var queryOpertors={">":function(a,b){return a>b},">=":function(a,b){return a>=b},"<":function(a,b){return a<b},"<=":function(a,b){return a<=b},"=":function(a,b){return a===b},"!=":function(a,b){return a!==b},$text:function(a,b){return ilike.call(null,[b],a)},$where:function(a,b){return b.call(null,a)},$in:function(a,b){return b.indexOf(a)>-1},$nin:function(a,b){return-1===b.indexOf(a)},$and:function(a,b){for(var i=0,len=a.length;i<len;i++)if(!doQuery(a[i],b))return!1;return!0},$or:function(a,b){for(var i=0,len=a.length;i<len;i++)if(doQuery(a[i],b))return!0;return!1}};function doQuery(query,value){return queryOpertors[query.operator]?queryOpertors[query.operator].call(null,value[query.attribute],query.value):!!query.$and&&queryOpertors.$and.call(null,query.$and,value)}function _sort(sorts,data){return timsort.sort(data,function(sorts){for(var _fn="",i=0;i<sorts.length;i++){for(var _parts=sorts[i].split(" "),_atributePath=_parts[0].split("."),_sort="DESC"===_parts[1]?-1:1,_attribute="";_atributePath.length;)_fn+="if (itemA"+(_attribute+='["'+_atributePath.shift()+'"]')+" == null) { return 1; }",_fn+="if (itemB"+_attribute+" == null) { return -1; }";_fn+="\nif (itemA"+_attribute+" > itemB"+_attribute+") {",_fn+="\n  return "+_sort+";",_fn+="\n}",_fn+="\nif (itemA"+_attribute+" < itemB"+_attribute+") {",_fn+="\n  return -("+_sort+");",_fn+="\n}"}return _fn+="\nreturn 0;",new Function("itemA","itemB",_fn)}(sorts)),data}function parseExpression(expressions){for(var compilatedExpressions=[],attributes=[],i=0;i<expressions.length;i++){var expression=expressions[i],subCompilatedExpressions=[];for(var field in expression){attributes.push(field);var querySearch=expression[field];if("object"!=typeof querySearch)querySearch={attribute:field,operator:"=",value:querySearch},subCompilatedExpressions.push(querySearch);else for(var operator in querySearch)"$text"===operator&&(querySearch[operator]=utils.unaccent(querySearch[operator]).toLowerCase().split(" ")),subCompilatedExpressions.push({attribute:field,operator:operator,value:querySearch[operator]})}compilatedExpressions.push({$and:subCompilatedExpressions})}return{expressions:compilatedExpressions,attributes:attributes}}return(exports=function(data,options){var _query={},_hasBeenCloned=!(!options||!1!==options.shouldClone);function _cloneIfNotAlreadyIs(){_hasBeenCloned||(data=utils.clone(data),_hasBeenCloned=!0)}return _query.count=function(){return data.length},_query.data=function(options){return _cloneIfNotAlreadyIs(),options&&options.freeze&&(data=utils.cloneAndFreeze(data)),data},_query.sort=function(sorts){return sorts?(Array.isArray(sorts)||(sorts=[sorts]),_cloneIfNotAlreadyIs(),_sort(sorts,data),_query):_query},_query.map=function(mapFn){if("function"!=typeof mapFn)throw new Error("mapFn is not a function");_cloneIfNotAlreadyIs();for(var res=[],i=0;i<data.length;i++)res[i]=mapFn.call(null,data[i],i,res);return data=res,_query},_query.reduce=function(reduceFn,options){if("function"!=typeof reduceFn)throw new Error("reduceFn is not a function");_cloneIfNotAlreadyIs();for(var accumulator=options&&void 0!==options.initialValue?options.initialValue:null,i=0;i<data.length;i++)accumulator=reduceFn.call(null,accumulator,data[i]);return accumulator},_query.mapReduce=function(mapFn,reduceFn,options){if("function"!=typeof mapFn)throw new Error("mapFn is not a function");if("function"!=typeof reduceFn)throw new Error("reduceFn is not a function");_cloneIfNotAlreadyIs();for(var newArray=[],accumulator=options&&void 0!==options.initialValue?options.initialValue:null,i=0;i<data.length;i++)newArray[i]=mapFn.call(null,data[i],i,newArray),accumulator=reduceFn.call(null,accumulator,newArray[i]);return data=newArray,accumulator},_query.where=function(fn){if("function"!=typeof fn)throw new Error("fn is not a function");_cloneIfNotAlreadyIs();var dataFiltered=function(whereFn,data){for(var dataFiltered=[],i=0;i<data.length;i++){whereFn.call(null,data[i])&&dataFiltered.push(data[i])}return dataFiltered}(fn,data);return data=dataFiltered,_query},_query.find=function(query){return data=function(query,data){var dataFiltered=[],_and=[],_or=[];query.$or&&(_or=query.$or,Array.isArray(_or)||(_or=[_or]),delete query.$or),query.$and?(_and=query.$and,Array.isArray(_and)||(_and=[_and])):_and=[query];var compilatedAndExpressions=parseExpression(_and),compilatedOrExpressions=parseExpression(_or);_and=compilatedAndExpressions.expressions,_or=compilatedOrExpressions.expressions;for(var attributes=compilatedAndExpressions.attributes.concat(compilatedOrExpressions.attributes),i=0,len=data.length;i<len;i++){for(var item=data[i],itemValues={},j=0;j<attributes.length;j++){for(var itemValue=item,atributePath=attributes[j].split(".");atributePath.length;){var attribute=atributePath.shift();if(null==itemValue[attribute]){itemValues[attributes[j]]=void 0;break}itemValue=itemValue[attribute]}itemValues[attributes[j]]=itemValue}var conditionValue=!0;_and.length&&!(conditionValue=queryOpertors.$and(_and,itemValues))||(_or.length&&(conditionValue=queryOpertors.$or(_or,itemValues)),conditionValue&&dataFiltered.push(item))}return dataFiltered}(query,data),_query},_query}).operators=queryOpertors,exports}([_store_store_offline_js,_utils_js],{}),_store_dataQuery_store_collectionResultSet_js=function(imports,exports){var utils=imports[0],storeUtils=imports[1],queryResultSet=imports[2];return function(store){var _store=storeUtils.getStore(store);if(_store.isStoreObject)throw new Error("Cannot initialize a CollectionResultSet on a store object");var _collection=storeUtils.getCollection(_store),_data=utils.clone(_collection.getAll());return queryResultSet(_data)}}([_utils_js,_store_store_utils_js,_store_dataQuery_queryResultSet_js]),_index_js=function(imports,exports){var hook=imports[0],store=imports[1],storeSynchro=imports[2],storeUtils=imports[3],lunarisExports=imports[4],collection=imports[5],utils=imports[6],logger=imports[7],http=imports[8],offline=imports[9],cache=imports[10],transaction=imports[11],websocket=imports[12],localStorageDriver=imports[13],invalidate=imports[14],lazyLoad=imports[15],collectionResultSet=imports[16],dynamicView=imports[17],devtools=imports[18];return utils.getTranslatedStoreName=storeUtils.getTranslatedStoreName,offline.pushOfflineHttpTransactions=storeSynchro.pushOfflineHttpTransactions,offline.getLastSyncDate=storeSynchro.getLastSyncDate,offline.load=store.load,{_stores:lunarisExports._stores,_collection:collection.collection,_cache:cache,_resetVersionNumber:collection.resetVersionNumber,_indexedDB:localStorageDriver.indexedDB,_removeAllHooks:hook.removeAllHooks,_initStore:lazyLoad.load,_register:lazyLoad.register,collectionResultSet:collectionResultSet,dynamicView:dynamicView,devtools:devtools,utils:utils,logger:logger,hook:hook.hook,removeHook:hook.removeHook,pushToHandlers:hook.pushToHandlers,http:http,websocket:websocket,offline:offline,localStorage:localStorageDriver.localStorage,get:store.get,getOne:store.getOne,insert:store.insert,update:store.update,upsert:store.upsert,delete:store.delete,load:store.load,clear:store.clear,rollback:store.rollback,getDefaultValue:store.getDefaultValue,validate:store.validate,setPagination:store.setPagination,createUrl:store.createUrl,begin:transaction.begin,commit:transaction.commit,invalidate:invalidate.invalidate,invalidations:{init:invalidate.init,compute:invalidate.computeInvalidations,on:invalidate.on,_invalidations:invalidate.invalidations,getAndCompute:function(){lunaris.websocket.unsubscribe("invalidations"),websocket.subscribe("invalidations",(function(serverInvalidations){invalidate.computeInvalidations(serverInvalidations.data,Object.keys(lunarisExports._stores))})),websocket.send("invalidations")}},OPERATIONS:utils.OPERATIONS,exports:lunarisExports,get constants(){return lunarisExports.constants}}}([_store_store_hook_js,_store_store_js,_store_store_synchronisation_js,_store_store_utils_js,_exports_js,_store_store_collection_js,_utils_js,_logger_js,_http_js,_offline_js,_cache_js,_store_store_transaction_js,_websocket_js,_localStorageDriver_js,_invalidate_js,_store_crud__lazyLoad_js,_store_dataQuery_store_collectionResultSet_js,function(imports,exports){var storeUtils=imports[0],hooks=imports[1],collectionResultSet=imports[2],queryResultSet=imports[3];return function(store,options){var _store=storeUtils.getStore(store),_dynamicView={idIdx:{}},_data=[],_hasBeenMaterialized=!1,_pipeline=[];if(_dynamicView.shouldNotInitialize=!(!options||!options.shouldNotInitialize),_store.isStoreObject)throw new Error("Cannot initialize a DynamicView on a store object");function _isMaterialized(){_hasBeenMaterialized||_dynamicView.shouldNotInitialize||_dynamicView.materialize()}function update(items){Array.isArray(items)||(items=[items]);var _itemsFiltered=function(data){for(var _resultSet=queryResultSet(data,{shouldClone:!1}),i=0;i<_pipeline.length;i++){var _criteria=_pipeline[i];_resultSet[_criteria.type].call(null,_criteria.args)}return _resultSet.data()}(items),_diff=[];if(_pipeline.length){for(var i=0;i<items.length;i++){for(var _hasBeenFound=!1,j=0;j<_itemsFiltered.length;j++)if(items[i]._id===_itemsFiltered[j]._id){_hasBeenFound=!0;break}_hasBeenFound||_diff.push(items[i])}_diff.length&&remove(_diff)}for(var _index=_dynamicView.idIdx,len=(i=0,_itemsFiltered.length);i<len;i++){var _item=_itemsFiltered[i];null==_index[_item._id]?(_index[_item._id]=_data.length,_data.push(_item)):_data.splice(_index[_item._id],1,_item)}}function _moveIndex(index){for(var i=index,len=_data.length;i<len;i++)_dynamicView.idIdx[_data[i]._id]--}function remove(items){Array.isArray(items)||(items=[items]);for(var _index=_dynamicView.idIdx,i=0,len=items.length;i<len;i++)null!=_index[items[i]._id]&&(_data.splice(_index[items[i]._id],1),_moveIndex(_index[items[i]._id]),_index[items[i]._id]=null)}function reset(){_data.splice(0),_dynamicView.idIdx={},_hasBeenMaterialized=!1}return _dynamicView.count=function(){return _isMaterialized(),_data.length},_dynamicView.data=function(){return _isMaterialized(),_data},_dynamicView.materialize=function(){for(var _resultSet=collectionResultSet(store),i=0;i<_pipeline.length;i++){var _criteria=_pipeline[i];_resultSet[_criteria.type].call(null,_criteria.args)}_dynamicView.idIdx={};let materializedData=_resultSet.data();i=0;for(var len=materializedData.length;i<len;i++)_data.splice(i,1,materializedData[i]),_dynamicView.idIdx[materializedData[i]._id]=i;return _hasBeenMaterialized=!0,_dynamicView},_dynamicView.applyFindCriteria=function(queryResultSet,uid){return _pipeline.push({id:uid,args:queryResultSet,type:"find"}),_dynamicView},_dynamicView.applyWhereCriteria=function(whereFn,uid){return _pipeline.push({id:uid,args:whereFn,type:"where"}),_dynamicView},_dynamicView.applySortCriteria=function(sort,uid){return _pipeline.push({id:uid,args:sort,type:"sort"}),_dynamicView},_dynamicView.removeCriteria=function(uid){for(var i=0,len=_pipeline.length;i<len;i++)if(_pipeline[i].id===uid&&uid){_pipeline.splice(i,1);break}return _dynamicView},_dynamicView.removeCriterias=function(){return _pipeline=[],_dynamicView},_dynamicView.resultSet=function(){return queryResultSet(_data)},_dynamicView.destroy=function(){hooks.removeHook("get@"+_store.name,update),hooks.removeHook("insert@"+_store.name,update),hooks.removeHook("update@"+_store.name,update),hooks.removeHook("delete@"+_store.name,remove),hooks.removeHook("reset@"+_store.name,reset)},hooks.hook("get@"+_store.name,update),hooks.hook("insert@"+_store.name,update),hooks.hook("update@"+_store.name,update),hooks.hook("delete@"+_store.name,remove),hooks.hook("reset@"+_store.name,reset),_dynamicView._update=update,_dynamicView._remove=remove,_dynamicView}}([_store_store_utils_js,_store_store_hook_js,_store_dataQuery_store_collectionResultSet_js,_store_dataQuery_queryResultSet_js]),{send:function(data){var event=new CustomEvent("lunaris-devtools",{detail:data});window.dispatchEvent(event)}}]);global.lunaris=_index_js}("undefined"!=typeof module?global:this);