diff --git a/CHANGELOG.md b/CHANGELOG.md index d6712acdc..83bd016ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ *__note:__ the # at the end of lines are the pull request numbers on GitHub* +# 2.1.4 + +* Fix `onDone` callbacks being lost when subscribing in a `disconnected` state #121 + # 2.1.3 * https://github.com/kuzzleio/sdk-javascript/releases/tag/2.1.3 diff --git a/dist/kuzzle.js b/dist/kuzzle.js index ae1753334..4e86709ea 100644 --- a/dist/kuzzle.js +++ b/dist/kuzzle.js @@ -1,3 +1,3 @@ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){function r(){var e=this,t=Date.now(),n=-1;e.queueTTL>0&&(e.offlineQueue.forEach(function(r,i){r.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emitEvent("offlineQueuePop",t.query)})}function i(e){var t=Date.now();Object.keys(e).forEach(function(n){e[n]0?(o.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){r()},Math.max(0,t.replayInterval))):t.queuing=!1};if(t.offlineQueueLoader){if("function"!=typeof t.offlineQueueLoader)throw new Error("Invalid value for offlineQueueLoader property. Expected: function. Got: "+typeof t.offlineQueueLoader);if(e=t.offlineQueueLoader(),!Array.isArray(e))throw new Error("Invalid value returned by the offlineQueueLoader function. Expected: array. Got: "+typeof e);t.offlineQueue=e.concat(t.offlineQueue).filter(function(e){if(!e.query||void 0===e.query.requestId||!e.query.action||!e.query.controller)throw new Error("Invalid offline queue request. One or more missing properties: requestId, action, controller.");return!n.hasOwnProperty(e.query.requestId)&&(n[e.query.requestId]=!0)})}r()}function s(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(n){var r=e.subscriptions[t][n];r.renew(r.callback)})})}function l(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(n){var r=e.subscriptions[t][n];r.unsubscribe()})})}var c=n(3),a=n(4),f=n(15),d=n(7),h=n(2),p=n(10);e.exports=Kuzzle=function(e,t,n){var r=this;if(!(this instanceof Kuzzle))return new Kuzzle(e,t,n);if(n||"function"!=typeof t||(n=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:n},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]},queryError:{listeners:[]}}},eventTimeout:{value:200},queuing:{value:!1,writable:!0},requestHistory:{value:{},writable:!0},state:{value:"initializing",writable:!0},subscriptions:{value:{pending:{}},writable:!0},autoReconnect:{value:!t||"boolean"!=typeof t.autoReconnect||t.autoReconnect,enumerable:!0},defaultIndex:{value:t&&"string"==typeof t.defaultIndex?t.defaultIndex:void 0,writable:!0,enumerable:!0},reconnectionDelay:{value:t&&"number"==typeof t.reconnectionDelay?t.reconnectionDelay:1e3,enumerable:!0},host:{value:e,writable:!0,enumerable:!0},wsPort:{value:t&&"number"==typeof t.wsPort?t.wsPort:7513,enumerable:!0,writable:!0},ioPort:{value:t&&"number"==typeof t.ioPort?t.ioPort:7512,enumerable:!0,writable:!0},sslConnection:{value:!(!t||"boolean"!=typeof t.sslConnection)&&t.sslConnection,enumerable:!0},autoQueue:{value:!1,enumerable:!0,writable:!0},autoReplay:{value:!1,enumerable:!0,writable:!0},autoResubscribe:{value:!0,enumerable:!0,writable:!0},headers:{value:{},enumerable:!0,writable:!0},metadata:{value:{},enumerable:!0,writable:!0},offlineQueue:{value:[],enumerable:!0,writable:!0},queueFilter:{value:null,enumerable:!0,writable:!0},queueMaxSize:{value:500,enumerable:!0,writable:!0},queueTTL:{value:12e4,enumerable:!0,writable:!0},replayInterval:{value:10,enumerable:!0,writable:!0},jwtToken:{value:void 0,enumerable:!0,writable:!0},offlineQueueLoader:{value:null,enumerable:!0,writable:!0}}),t&&(Object.keys(t).forEach(function(e){r.hasOwnProperty(e)&&Object.getOwnPropertyDescriptor(r,e).writable&&(r[e]=t[e])}),"auto"===t.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===r.state)throw new Error("This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?")}}),Object.defineProperty(this,"addHeaders",{value:function(e,t){return Object.keys(t).forEach(function(n){e[n]||(e[n]=t[n])}),e}}),Object.defineProperty(this,"callbackRequired",{value:function(e,t){if(!t||"function"!=typeof t)throw new Error(e+": a callback argument is required for read queries")}}),Object.defineProperty(this,"security",{value:new f(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(e){var t=Date.now(),n=Array.prototype.slice.call(arguments,1),r=this.eventListeners[e];return!(r.lastEmitted&&r.lastEmitted>=t-this.eventTimeout)&&(r.listeners.forEach(function(e){process.nextTick(function(){e.fn.apply(void 0,n)})}),void(void 0!==r.lastEmitted&&(r.lastEmitted=t)))}}),Object.defineProperty(this,"memoryStorage",{value:new d(this),enumerable:!0}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),i(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return r&&i.indexOf(e)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var e=this;return e.network&&e.disconnect(),e.network=p(e.host,e.wsPort,e.ioPort,e.sslConnection),["initializing","ready","disconnected","error","offline"].indexOf(this.state)===-1?(e.connectCB&&e.connectCB(null,e),e):(e.state="connecting",e.network.connect(e.autoReconnect,e.reconnectionDelay),e.network.onConnect(function(){e.state="connected",s.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.onConnectError(function(t){var n=new Error('Unable to connect to kuzzle proxy server at "'+e.host+'"');n.internal=t,e.state="error",e.emitEvent("error",n),e.connectCB&&e.connectCB(n)}),e.network.onDisconnect(function(){e.state="offline",e.autoReconnect||e.disconnect(),e.autoQueue&&(e.queuing=!0),e.emitEvent("disconnected")}),e.network.onReconnect(function(){var t=function(){e.autoResubscribe&&s.call(e),e.autoReplay&&(r.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(n,r){!n&&r.valid||(e.jwtToken=void 0,e.emitEvent("jwtTokenExpired")),t()}):t()}),this)},Kuzzle.prototype.setJwtToken=function(e){if("string"==typeof e)this.jwtToken=e;else{if("object"!=typeof e)return this.emitEvent("loginAttempt",{success:!1,error:"Invalid token argument: "+e}),this;if(!e.result||!e.result.jwt||"string"!=typeof e.result.jwt)return this.emitEvent("loginAttempt",{success:!1,error:"Cannot find a valid JWT token in the following object: "+JSON.stringify(e)}),this;this.jwtToken=e.result.jwt}return s.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.unsetJwtToken=function(){return this.jwtToken=void 0,l.call(this),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(e){var t,n=this,r={strategy:e},i=null;arguments[1]&&("object"==typeof arguments[1]?t=arguments[1]:"number"==typeof arguments[1]||"string"==typeof arguments[1]?r.expiresIn=arguments[1]:"function"==typeof arguments[1]&&(i=arguments[1])),arguments[2]&&("number"==typeof arguments[2]||"string"==typeof arguments[2]?r.expiresIn=arguments[2]:"function"==typeof arguments[2]&&(i=arguments[2])),arguments[3]&&"function"==typeof arguments[3]&&(i=arguments[3]),"object"==typeof t&&Object.keys(t).forEach(function(e){r[e]=t[e]}),this.query({controller:"auth",action:"login"},{body:r},{queuable:!1},function(e,t){e?(i&&i(e),n.emitEvent("loginAttempt",{success:!1,error:e.message})):(t.result.jwt&&n.setJwtToken(t.result.jwt),i&&i(null,t.result))})},Kuzzle.prototype.logout=function(e){var t=this,n={action:"logout",controller:"auth",requestId:c.v4(),body:{}};return this.query({controller:"auth",action:"logout"},n,{queuable:!1},"function"!=typeof e?null:function(n){null===n?(t.unsetJwtToken(),e(null,t)):e(n)}),t},Kuzzle.prototype.checkToken=function(e,t){var n={body:{token:e}};this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},n,{queuable:!1},function(e,n){return e?t(e):void t(null,n.result)})},Kuzzle.prototype.whoAmI=function(e){var t=this;t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(n,r){return n?e(n):void e(null,new h(t.security,r.result._id,r.result._source))})},Kuzzle.prototype.getMyRights=function(e,t){var n=this;t||"function"!=typeof e||(t=e,e=null),n.callbackRequired("Kuzzle.getMyRights",t),n.query({controller:"auth",action:"getMyRights"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.updateSelf=function(e,t,n){var r=this,i={},o={controller:"auth",action:"updateSelf"};return n||"function"!=typeof t||(n=t,t=null),i.body=e,r.query(o,i,t,n&&function(e,t){n(e,e?void 0:t.result)}),this},Kuzzle.prototype.addListener=function(e,t){var n,r=Object.keys(this.eventListeners),i=typeof t;if(this.isValid(),r.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+r.toString());if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return n=c.v4(),this.eventListeners[e].listeners.push({id:n,fn:t}),n},Kuzzle.prototype.getAllStatistics=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"admin",action:"getAllStats"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.getStatistics=function(e,t,n){var r,i;n||(1===arguments.length?(n=arguments[0],t=null,e=null):(n=arguments[1],"object"==typeof arguments[0]?(t=arguments[0],e=null):(e=arguments[0],t=null))),r=function(t,r){return t?n(t):void n(null,e?r.result.hits:[r.result])},this.callbackRequired("Kuzzle.getStatistics",n),i=e?{body:{startTime:e}}:{},this.query({controller:"admin",action:e?"getStats":"getLastStats"},i,t,r)},Kuzzle.prototype.dataCollectionFactory=function(e,t){if(this.isValid(),!t){if(!this.defaultIndex)throw new Error("Unable to create a new data collection object: no index specified");t=this.defaultIndex}if("string"!=typeof t||"string"!=typeof e)throw new Error("Invalid index or collection argument: string expected");return this.collections[t]||(this.collections[t]={}),this.collections[t][e]||(this.collections[t][e]=new a(this,e,t)),this.collections[t][e]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var e,t,n,r="all",i=Array.prototype.slice.call(arguments);if(i.forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.listCollections",n),t&&t.type&&(r=t.type),this.query({index:e,controller:"read",action:"listCollections"},{body:{type:r}},t,function(e,t){return e?n(e):void n(null,t.result.collections)})},Kuzzle.prototype.listIndexes=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"read",action:"listIndexes"},{},e,function(e,n){t(e,e?void 0:n.result.indexes)})},Kuzzle.prototype.disconnect=function(){var e;this.logout(),this.state="disconnected",this.network.close(),this.network=null;for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},Kuzzle.prototype.getServerInfo=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"read",action:"serverInfo"},{},e,function(e,n){return e?t(e):void t(null,n.result.serverInfo)})},Kuzzle.prototype.refreshIndex=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"admin",action:"refreshIndex"},{},t,n),this},Kuzzle.prototype.getAutoRefresh=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.getAutoRefresh",n),this.query({index:e,controller:"admin",action:"getAutoRefresh"},{},t,n)},Kuzzle.prototype.setAutoRefresh=function(){var e,t,n,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"boolean":t=i;break;case"object":n=i;break;case"function":r=i}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.setAutoRefresh: index required");e=this.defaultIndex}if(void 0===t)throw new Error("Kuzzle.setAutoRefresh: autoRefresh value is required");return this.query({index:e,controller:"admin",action:"setAutoRefresh"},{body:{autoRefresh:t}},n,r),this},Kuzzle.prototype.now=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"read",action:"now"},{},e,function(e,n){t(e,n&&n.result.now)})},Kuzzle.prototype.query=function(e,t,n,i){var u,s={action:e.action,controller:e.controller,metadata:this.metadata},l=this;if(this.isValid(),i||"function"!=typeof n||(i=n,n=null),n&&(n.metadata&&Object.keys(n.metadata).forEach(function(e){s.metadata[e]=n.metadata[e]}),n.queuable===!1&&"offline"===l.state))return l;if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.metadata&&Object.keys(t.metadata).forEach(function(e){s.metadata[e]=t.metadata[e]});for(u in t)"metadata"!==u&&t.hasOwnProperty(u)&&(s[u]=t[u]);return s=l.addHeaders(s,this.headers),void 0===l.jwtToken||"auth"===s.controller&&"checkToken"===s.action||(s.headers=s.headers||{},s.headers.authorization="Bearer "+l.jwtToken),e.collection&&(s.collection=e.collection),e.index&&(s.index=e.index),s.requestId||(s.requestId=c.v4()),"connected"===l.state||n&&n.queuable===!1?"connected"===l.state?o.call(this,s,i):i&&i(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(s))):(l.queuing||["initializing","connecting"].indexOf(l.state)!==-1)&&(r.call(this,s,i),l.queueFilter&&!l.queueFilter(s)||(l.offlineQueue.push({ts:Date.now(),query:s,cb:i}),l.emitEvent("offlineQueuePush",{query:s,cb:i}))),l},Kuzzle.prototype.removeAllListeners=function(e){var t=Object.keys(this.eventListeners),n=this;if(e){if(t.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+t.toString());this.eventListeners[e].listeners=[]}else t.forEach(function(e){n.eventListeners[e].listeners=[]});return this},Kuzzle.prototype.removeListener=function(e,t){var n=Object.keys(this.eventListeners),r=this;if(n.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+n.toString());return this.eventListeners[e].listeners.forEach(function(n,i){n.id===t&&r.eventListeners[e].listeners.splice(i,1)}),this},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(r.call(this),u.call(this)),this},Kuzzle.prototype.setDefaultIndex=function(e){if("string"!=typeof e)throw new Error("Invalid default index: ["+e+"] (an index name is expected)");if(0===e.length)throw new Error("Cannot set an empty index as the default index");return this.defaultIndex=e,this},Kuzzle.prototype.setHeaders=function(e,t){var n=this;if("object"!=typeof e||Array.isArray(e))throw new Error("Expected a content object, received a "+typeof e);return t?n.headers=e:Object.keys(e).forEach(function(t){n.headers[t]=e[t]}),n},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}},function(e,t){function n(e,t,n){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},kuzzleSecurity:{value:e},id:{value:t,enumerable:!0},content:{value:{},writable:!0,enumerable:!0}}),n&&this.setContent(n,!0),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","update"];return r&&i.indexOf(e)!==-1}})}n.prototype.setContent=function(e){return this.content=e,this},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},n.prototype["delete"]=function(e,t){var n=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName),{_id:this.id},e,function(e,n){return e?!!t&&t(e):void(t&&t(null,n.result._id))})},n.prototype.update=function(e,t,n){var r={},i=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');return t&&void 0===n&&"function"==typeof t&&(n=t,t=null),r._id=i.id,r.body=e,i.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),r,t,function(e,t){return e?!!n&&n(e):(i.setContent(t.result._source),void(n&&n(null,i)))}),this},e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.setProfiles=function(e){if(!Array.isArray(e)||"string"!=typeof e[0])throw new Error('Parameter "profileIds" must be an array of strings');return this.content.profileIds=e,this},r.prototype.addProfile=function(e){if("string"!=typeof e)throw new Error('Parameter "profileId" must be a string');return this.content.profileIds||(this.content.profileIds=[]),this.content.profileIds.indexOf(e)===-1&&this.content.profileIds.push(e),this},r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.prototype.serialize=function(){return{_id:this.id,body:this.content}},r.prototype.getProfiles=function(){return this.content.profileIds},e.exports=r},function(e,t){!function(t){"use strict";function n(){var e=t.crypto||t.msCrypto;if(!l&&e&&e.getRandomValues)try{var n=new Uint8Array(16);f=l=function(){return e.getRandomValues(n),n},l()}catch(r){}if(!l){var i=new Array(16);c=l=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function r(){if("function"==typeof require)try{var e=require("crypto").randomBytes;a=l=e&&function(){return e(16)},l()}catch(t){}}function i(e,t,n){var r=t&&n||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[r+i++]=y[e])});i<16;)t[r+i++]=0;return t}function o(e,t){var n=t||0,r=p;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]}function u(e,t,n){var r=t&&n||0,i=t||[];e=e||{};var u=null!=e.clockseq?e.clockseq:m,s=null!=e.msecs?e.msecs:(new Date).getTime(),l=null!=e.nsecs?e.nsecs:k+1,c=s-w+(l-k)/1e4;if(c<0&&null==e.clockseq&&(u=u+1&16383),(c<0||s>w)&&null==e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=s,k=l,m=u,s+=122192928e5;var a=(1e4*(268435455&s)+l)%4294967296;i[r++]=a>>>24&255,i[r++]=a>>>16&255,i[r++]=a>>>8&255,i[r++]=255&a;var f=s/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=255&f,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=u>>>8|128,i[r++]=255&u;for(var d=e.node||v,h=0;h<6;h++)i[r+h]=d[h];return t?t:o(i)}function s(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new h(16):null,e=null),e=e||{};var i=e.random||(e.rng||l)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;u++)t[r+u]=i[u];return t||o(i)}var l,c,a,f,d;t?n():r();for(var h="function"==typeof Buffer?Buffer:Array,p=[],y={},b=0;b<256;b++)p[b]=(b+256).toString(16).substr(1),y[p[b]]=b;var z=l(),v=[1|z[0],z[1],z[2],z[3],z[4],z[5]],m=16383&(z[6]<<8|z[7]),w=0,k=0,g=s;g.v1=u,g.v4=s,g.parse=i,g.unparse=o,g.BufferClass=h,g._rng=l,g._mathRNG=c,g._nodeRNG=a,g._whatwgRNG=f,"undefined"!=typeof e&&e.exports?e.exports=g:"function"==typeof define&&define.amd?define(function(){return g}):(d=t.uuid,g.noConflict=function(){return t.uuid=d,g},t.uuid=g)}("undefined"!=typeof window?window:null)},function(e,t,n){function r(e,t,n){if(!n||!t)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:t,enumerable:!0},index:{value:n,enumerable:!0},kuzzle:{value:e,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0}}),Object.defineProperty(this,"buildQueryArgs",{value:function(e,t){return{controller:e,action:t,collection:this.collection,index:this.index}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["publishMessage","setHeaders","subscribe"];return r&&i.indexOf(e)===-1}}):this}var i=n(6),o=n(5),u=n(8),s=n(9);r.prototype.advancedSearch=function(e,t,n){var r,o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",n),r=o.kuzzle.addHeaders({body:e},this.headers),o.kuzzle.query(this.buildQueryArgs("read","search"),r,t,function(e,t){var r=[];return e?n(e):(t.result.hits.forEach(function(e){var t=new i(o,e._id,e._source);t.version=e._version,r.push(t)}),void n(null,{total:t.result.total,documents:r}))})},r.prototype.count=function(e,t,n){var r;n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",n),r=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),r,t,function(e,t){n(e,t&&t.result.count)})},r.prototype.create=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("write","createCollection"),n,e,t),this},r.prototype.createDocument=function(e,t,n,r){var o=this,u={},s="create";return e&&"string"!=typeof e&&(r=n,n=t,t=e,e=null),r||"function"!=typeof n||(r=n,n=null),t instanceof i?u=t.serialize():u.body=t,n&&(s=n.updateIfExist?"createOrReplace":"create"),e&&(u._id=e),u=o.kuzzle.addHeaders(u,o.headers),o.kuzzle.query(this.buildQueryArgs("write",s),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.deleteDocument=function(e,t,n){var r,i={};return"string"==typeof e?(i._id=e,r="delete"):(i.body=e,r="deleteByQuery"),n||"function"!=typeof t||(n=t,t=null),i=this.kuzzle.addHeaders(i,this.headers),this.kuzzle.query(this.buildQueryArgs("write",r),i,t,n&&function(e,t){e?n(e):n(null,"delete"===r?[t.result._id]:t.result.ids)}),this},r.prototype.fetchDocument=function(e,t,n){var r={_id:e},o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.fetch",n),r=o.kuzzle.addHeaders(r,this.headers),o.kuzzle.query(this.buildQueryArgs("read","get"),r,t,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))})},r.prototype.fetchAllDocuments=function(e,t){var n={};t||"function"!=typeof e||(t=e,e=null),e&&(e.from&&(n.from=e.from),e.size&&(n.size=e.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",t),this.advancedSearch(n,e,t)},r.prototype.getMapping=function(e,t){var n;t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",t),n=new o(this),n.refresh(e,t)},r.prototype.publishMessage=function(e,t,n){var r={};return e instanceof i?r=e.serialize():r.body=e,r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),r,t,n),this},r.prototype.replaceDocument=function(e,t,n,r){var o=this,u={_id:e,body:t};return r||"function"!=typeof n||(r=n,n=null),u=o.kuzzle.addHeaders(u,this.headers),o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.subscribe=function(e,t,n){var r,i;return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",n),i=new s,r=new u(this,t),r.renew(e,n,i.done.bind(i)),i},r.prototype.truncate=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("admin","truncateCollection"),n,e,t),this},r.prototype.updateDocument=function(e,t,n,r){var o={_id:e,body:t},u=this;return r||"function"!=typeof n||(r=n,n=null),o=u.kuzzle.addHeaders(o,this.headers),u.kuzzle.query(this.buildQueryArgs("write","update"),o,n,r&&function(e,t){return e?r(e):void new i(u,t.result._id).refresh(r)}),u},r.prototype.documentFactory=function(e,t){return new i(this,e,t)},r.prototype.roomFactory=function(e){return new u(this,e)},r.prototype.dataMappingFactory=function(e){return new o(this,e)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(e,t){return Object.defineProperties(this,{collection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},mapping:{value:t||{},enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["set","setHeaders"];return r&&i.indexOf(e)===-1}}):this}n.prototype.apply=function(e,t){var n=this,r=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),n.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),r,e,function(r){return r?t&&t(r):void n.refresh(e,t)}),this},n.prototype.refresh=function(e,t){var n=this,r=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),r,e,function(e,r){return e?!!t&&t(e):r.result[n.collection.index]?r.result[n.collection.index].mappings[n.collection.collection]?(n.mapping=r.result[n.collection.index].mappings[n.collection.collection].properties,void 0===n.mapping&&(n.mapping={}),void(t&&t(null,n))):t&&t(new Error("No mapping found for collection "+n.collection.collection)):t&&t(new Error("No mapping found for index "+n.collection.index))}),this},n.prototype.set=function(e,t){return this.mapping[e]=t,this},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(e,t,n){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},id:{value:void 0,enumerable:!0,writable:!0},content:{value:{},writable:!0,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},version:{value:void 0,enumerable:!0,writable:!0}}),!n&&t&&"object"==typeof t&&(n=t,t=null),n&&(n._version&&(this.version=n._version,delete n._version),this.setContent(n,!0)),t&&Object.defineProperty(this,"id",{value:t,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","refresh","save"];return r&&i.indexOf(e)!==-1}}):this}n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e._version=this.version,e=this.kuzzle.addHeaders(e,this.headers)},n.prototype.toString=function(){return JSON.stringify(this.serialize())},n.prototype["delete"]=function(e,t){var n=this;if(t||"function"!=typeof e||(t=e,e=null),!n.id)throw new Error("KuzzleDocument.delete: cannot delete a document without a document ID");this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e,t&&function(e){t(e,e?void 0:n.id)})},n.prototype.refresh=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",t),r.kuzzle.query(r.dataCollection.buildQueryArgs("read","get"),{_id:r.id},e,function(e,i){var o;return e?t(e):(o=new n(r.dataCollection,r.id,i.result._source),o.version=i.result._version,void t(null,o))})},n.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.dataCollection.buildQueryArgs("write","createOrReplace"),n,e,function(e,n){return e?t&&t(e):(r.id=n.result._id,r.version=n.result._version,void(t&&t(null,r)))}),r},n.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","publish"),t,e),this},n.prototype.setContent=function(e,t){var n=this;return t?this.content=e:Object.keys(e).forEach(function(t){n.content[t]=e[t]}),this},n.prototype.subscribe=function(e,t){var n;if(e&&!t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDocument.subscribe",t),!this.id)throw new Error("KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided");return n={ids:{values:[this.id]}},this.dataCollection.subscribe(n,e,t)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(e){return Object.defineProperties(this,{kuzzle:{value:e,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0}}),this.setHeaders=e.setHeaders.bind(this),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["setHeaders"];return r&&i.indexOf(e)===-1}}):this}!function(){var e=["id","value"],t=["id","keys"],r={append:e,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",t],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[t,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:e,del:[t],discard:[],exec:[],exists:[t],expire:["id","seconds"],expireat:["id","timestamp"],flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"], -hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"],publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"],sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",t],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",t],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",t],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",t,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};r.decr=r.get=r.dump=r.hgetall=r.hkeys=r.hlen=r.hstrlen=r.hvals=r.incr=r.llen=r.lpop=r.persist=r.pttl=r.rpop=r.scard=r.smembers=r.strlen=r.ttl=r.type=r.zcard=["id"],r.getset=r.lpushx=e,r.del=r.exists=r.mget=r.pfcount=r.sdiff=r.sinter=r.sunion=r.watch=[t],r.incrby=r.incrbyfloat=r.decrby,r.brpop=r.blpop,r.hget=r.hexists,r.hmget=r.hdel,r.hsetnx=r.hset,r.msetnx=r.mset,r.rpush=r.lpush,r.hincrbyfloat=r.hincrby,r.srandmember=r.spop,r.zrevrange=r.zrange,r.zscore=r.zrevrank,Object.keys(r).forEach(function(e){n.prototype[e]=function(){var t,n=Array.prototype.slice.call(arguments),i=null,o={controller:"ms",action:e},u={};return"function"==typeof n[n.length-1]&&(t=n.pop()),n.length&&"object"==typeof n[n.length-1]&&1===Object.keys(n[n.length-1]).length&&void 0!==n[n.length-1].queuable&&(i=n.pop()),r[e].forEach(function(e,t){void 0!==n[t]&&(Array.isArray(e)&&(e=Array.isArray(n[t])?e[1]:e[0]),"id"===e?u._id=n[t]:(u.body||(u.body={}),"object"==typeof e&&void 0!==e.__opts__?e.__opts__.forEach(function(e){void 0!==n[t][e]&&(u.body[e]=n[t][e])}):u.body[e]=n[t]))}),this.kuzzle.query(o,u,i,t),this}})}(),e.exports=n},function(e,t,n){function r(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:s.v4()},lastRenewal:{value:null,writable:!0},notifier:{value:null,writable:!0},queue:{value:[],writable:!0},renewalDelay:{value:500},scope:{value:t&&t.scope?t.scope:"all"},state:{value:t&&t.state?t.state:"done"},subscribing:{value:!1,writable:!0},users:{value:t&&t.users?t.users:"none"},collection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},filters:{value:null,enumerable:!0,writable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},metadata:{value:t&&t.metadata?t.metadata:{},enumerable:!0,writable:!0},roomId:{value:null,enumerable:!0,writable:!0},subscribeToSelf:{value:!t||"boolean"!=typeof t.subscribeToSelf||t.subscribeToSelf,enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["count"];return r&&i.indexOf(e)!==-1}}):this}function i(e){return e.error?this.callback(e.error):"jwtTokenExpired"===e.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):void(this.kuzzle.requestHistory[e.requestId]?(this.subscribeToSelf&&this.callback(null,e),delete this.kuzzle.requestHistory[e.requestId]):this.callback(null,e))}function o(){for(var e;this.queue.length>0;)e=this.queue.shift(),this[e.action].apply(this,e.args)}function u(){return"connected"===this.kuzzle.state&&!this.subscribing}var s=n(3);r.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("KuzzleRoom.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!u.call(this))return void this.queue.push({action:"count",args:[e]});if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),t,function(t,n){e(t,n&&n.result.count)})},r.prototype.renew=function(e,t,n){var r=Date.now(),u={scope:this.scope,state:this.state,users:this.users},s=this;if("function"==typeof e&&(n=t,t=e,e=null),s.kuzzle.callbackRequired("KuzzleRoom.renew",t),!(s.lastRenewal&&r-s.lastRenewal<=s.renewalDelay)){if(e&&(s.filters=e),"connected"!==s.kuzzle.state)return s.callback=t,void(s.kuzzle.subscriptions.pending[s.id]=s);if(s.subscribing)return void s.queue.push({action:"renew",args:[e,t,n]});s.unsubscribe(),s.roomId=null,s.subscribing=!0,s.callback=t,s.kuzzle.subscriptions.pending[s.id]=s,u.body=s.filters,u=s.kuzzle.addHeaders(u,this.headers),s.kuzzle.query(s.collection.buildQueryArgs("subscribe","on"),u,{metadata:s.metadata},function(e,t){return delete s.kuzzle.subscriptions.pending[s.id],s.subscribing=!1,e?(s.queue=[],n&&n(new Error("Error during Kuzzle subscription: "+e.message))):(s.lastRenewal=r,s.roomId=t.result.roomId,s.channel=t.result.channel,s.kuzzle.subscriptions[s.roomId]||(s.kuzzle.subscriptions[s.roomId]={}),s.kuzzle.subscriptions[s.roomId][s.id]=s,s.notifier=i.bind(s),s.kuzzle.network.on(s.channel,s.notifier),o.call(s),void(n&&n(null,s)))})}},r.prototype.unsubscribe=function(){var e,t=this,n=t.roomId;return u.call(this)?(n&&(t.kuzzle.network.off(t.channel,this.notifier),1===Object.keys(t.kuzzle.subscriptions[n]).length?(delete t.kuzzle.subscriptions[n],0===Object.keys(t.kuzzle.subscriptions.pending).length?t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[n]||t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[n][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(){this.cbs=[]}n.prototype.onDone=function(e){return this.cbs.push(e),this},n.prototype.done=function(e,t){this.cbs.forEach(function(n){n(e,t)})},e.exports=n},function(e,t,n){function r(e,t,r,i){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(n(12))(e,t,i);if(window.io)return new(n(11))(e,r,i);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(n(!function(){var e=new Error('Cannot find module "./wrappers/wsnode"');throw e.code="MODULE_NOT_FOUND",e}()))(e,t,i)}e.exports=r},function(e,t){function n(e,t,n){this.host=e,this.port=t,this.ssl=n,this.socket=null,this.connect=function(e,t){this.socket=window.io((this.ssl?"https://":"http://")+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0})},this.onConnect=function(e){this.socket.on("connect",e)},this.onConnectError=function(e){this.socket.on("connect_error",e)},this.onDisconnect=function(e){this.socket.on("disconnect",e)},this.onReconnect=function(e){this.socket.on("reconnect",e)},this.once=function(e,t){this.socket.once(e,t)},this.on=function(e,t){this.socket.on(e,t)},this.off=function(e,t){this.socket.off(e,t)},this.send=function(e){this.socket.emit("kuzzle",e)},this.close=function(){this.socket.close(),this.socket=null}}e.exports=n},function(e,t){function n(e,t,n){var o=this;this.host=e,this.port=t,this.ssl=n,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(e,t){this.client=new WebSocket((this.ssl?"wss://":"ws://")+this.host+":"+this.port),this.client.onopen=function(){o.retrying?r(o.listeners,"reconnect"):r(o.listeners,"connect")},this.client.onclose=function(n,u){1e3===n?r(o.listeners,"disconnect"):i.call(o,e,t,u)},this.client.onerror=function(n){i.call(o,e,t,n)},this.client.onmessage=function(e){var t=JSON.parse(e.data);t.room&&o.listeners[t.room]&&r(o.listeners,t.room,t)}},this.onConnect=function(e){this.listeners.connect.push({fn:e,keep:!0})},this.onConnectError=function(e){this.listeners.error.push({fn:e,keep:!0})},this.onDisconnect=function(e){this.listeners.disconnect.push({fn:e,keep:!0})},this.onReconnect=function(e){this.listeners.reconnect.push({fn:e,keep:!0})},this.once=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!1})},this.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!0})},this.off=function(e,t){var n;this.listeners[e]&&(n=this.listeners[e].findIndex(function(e){return e.fn===t}),n!==-1&&(1===this.listeners[e].length&&["error","connect","disconnect","reconnect"].indexOf(e)===-1?delete this.listeners[e]:this.listeners[e].splice(n,1)))},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function r(e,t,n){var r,i=e[t].length;for(r=0;r1?(e[t].splice(r,1),--r,--i):delete e[t])}function i(e,t,n){var i=this;e&&(i.retrying=!0,setTimeout(function(){i.connect(e,t)},t)),r(i.listeners,"error",n)}e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteProfile"},updateActionName:{value:"updateProfile"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["hydrate","save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n,r=this;if(!this.content.policies)throw new Error('Argument "policies" is mandatory in a profile. This argument contains an array of objects.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n=this.serialize(),r.kuzzle.query(r.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.prototype.addPolicy=function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an object containing at least a "roleId" member which must be a string.');return this.content.policies||(this.content.policies=[]),this.content.policies.push(e),this},r.prototype.setPolicies=function(e){if(!Array.isArray(e))throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string');return e.map(function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string')}),this.content.policies=e,this},r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},r.prototype.getPolicies=function(){return this.content.policies},e.exports=r},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteRole"},updateActionName:{value:"updateRole"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),n,e,t&&function(e){t(e,e?void 0:r)}),this},e.exports=r},function(e,t,n){function r(e){return Object.defineProperty(this,"kuzzle",{value:e}),Object.defineProperty(this,"buildQueryArgs",{value:function(e){return{controller:"security",action:e}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["roleFactory","profileFactory","userFactory","isActionAllowed"];return r&&i.indexOf(e)===-1}}):this}var i=n(14),o=n(13),u=n(2);r.prototype.getRole=function(e,t,n){var r,o=this;if(!e)throw new Error("Id parameter is mandatory for getRole function");n||"function"!=typeof t||(n=t,t=null),r={_id:e},o.kuzzle.callbackRequired("KuzzleSecurity.getRole",n),o.kuzzle.query(this.buildQueryArgs("getRole"),r,t,function(e,t){n(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.searchRoles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchRoles",n),r.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?n(e):(o=t.result.hits.map(function(e){return new i(r,e._id,e._source)}),void n(null,{total:t.result.total,roles:o}))})},r.prototype.createRole=function(e,t,n,r){var o=this,u={},s="createRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.updateRole=function(e,t,n,r){var o=this,u={_id:e,body:t},s="updateRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");return r||"function"!=typeof n||(r=n,n=null),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(n){r(n,n?void 0:new i(o,e,t))}),this},r.prototype.deleteRole=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.roleFactory=function(e,t){return new i(this,e,t)},r.prototype.getProfile=function(e,t,n){var r,i=this;if(n||"function"!=typeof t||(n=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getProfile function");r={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getProfile",n),i.kuzzle.query(this.buildQueryArgs("getProfile"),r,t,function(e,t){n(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.searchProfiles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",n),r.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new o(r,e._id,e._source)}),void n(null,{total:t.result.total,profiles:i}))})},r.prototype.createProfile=function(e,t,n,r){var i=this,u={},s="createProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceProfile":"createProfile"),i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.updateProfile=function(e,t,n,r){var i=this,u={},s="updateProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");return r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){var n={};return e?r(e):(Object.keys(t.result._source).forEach(function(e){n[e]=t.result._source[e]}),void r(null,new o(i,t.result._id,n)))}),this},r.prototype.deleteProfile=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.profileFactory=function(e,t){return new o(this,e,t)},r.prototype.getUser=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getUser function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("KuzzleSecurity.getUser",n),i.kuzzle.query(this.buildQueryArgs("getUser"),r,t,function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.searchUsers=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",n),r.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new u(r,e._id,e._source)}),void n(null,{total:t.result.total,users:i}))})},r.prototype.createUser=function(e,t,n,r){var i=this,o={_id:e,body:t},s="createUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");r||"function"!=typeof n||(r=n,n=null),n&&(s=n.replaceIfExist?"createOrReplaceUser":"createUser"),i.kuzzle.query(this.buildQueryArgs(s),o,null,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.updateUser=function(e,t,n,r){var i=this,o={},s="updateUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");return r||"function"!=typeof n||(r=n,n=null),o._id=e,o.body=t,i.kuzzle.query(this.buildQueryArgs(s),o,n,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))}),this},r.prototype.deleteUser=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.userFactory=function(e,t){return new u(this,e,t)},r.prototype.isActionAllowed=function(e,t,n,r,i){var o;if(!e||"object"!=typeof e)throw new Error("rights parameter is mandatory for isActionAllowed function");if(!t||"string"!=typeof t)throw new Error("controller parameter is mandatory for isActionAllowed function");if(!n||"string"!=typeof n)throw new Error("action parameter is mandatory for isActionAllowed function");return o=e.filter(function(e){return e.controller===t||"*"===e.controller}).filter(function(e){return e.action===n||"*"===e.action}).filter(function(e){return e.index===r||"*"===e.index}).filter(function(e){return e.collection===i||"*"===e.collection}),o.some(function(e){return"allowed"===e.value})?"allowed":o.some(function(e){return"conditional"===e.value})?"conditional":"denied"},r.prototype.getUserRights=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("Kuzzle.getUserRights",n),this.kuzzle.query(this.buildQueryArgs("getUserRights"),r,t,n&&function(e,t){n(e,e?void 0:t.result.hits)})},e.exports=r}])}); +hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"],publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"],sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",t],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",t],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",t],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",t,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};r.decr=r.get=r.dump=r.hgetall=r.hkeys=r.hlen=r.hstrlen=r.hvals=r.incr=r.llen=r.lpop=r.persist=r.pttl=r.rpop=r.scard=r.smembers=r.strlen=r.ttl=r.type=r.zcard=["id"],r.getset=r.lpushx=e,r.del=r.exists=r.mget=r.pfcount=r.sdiff=r.sinter=r.sunion=r.watch=[t],r.incrby=r.incrbyfloat=r.decrby,r.brpop=r.blpop,r.hget=r.hexists,r.hmget=r.hdel,r.hsetnx=r.hset,r.msetnx=r.mset,r.rpush=r.lpush,r.hincrbyfloat=r.hincrby,r.srandmember=r.spop,r.zrevrange=r.zrange,r.zscore=r.zrevrank,Object.keys(r).forEach(function(e){n.prototype[e]=function(){var t,n=Array.prototype.slice.call(arguments),i=null,o={controller:"ms",action:e},u={};return"function"==typeof n[n.length-1]&&(t=n.pop()),n.length&&"object"==typeof n[n.length-1]&&1===Object.keys(n[n.length-1]).length&&void 0!==n[n.length-1].queuable&&(i=n.pop()),r[e].forEach(function(e,t){void 0!==n[t]&&(Array.isArray(e)&&(e=Array.isArray(n[t])?e[1]:e[0]),"id"===e?u._id=n[t]:(u.body||(u.body={}),"object"==typeof e&&void 0!==e.__opts__?e.__opts__.forEach(function(e){void 0!==n[t][e]&&(u.body[e]=n[t][e])}):u.body[e]=n[t]))}),this.kuzzle.query(o,u,i,t),this}})}(),e.exports=n},function(e,t,n){function r(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:s.v4()},lastRenewal:{value:null,writable:!0},notifier:{value:null,writable:!0},onDoneCB:{value:null,writable:!0},queue:{value:[],writable:!0},renewalDelay:{value:500},scope:{value:t&&t.scope?t.scope:"all"},state:{value:t&&t.state?t.state:"done"},subscribing:{value:!1,writable:!0},users:{value:t&&t.users?t.users:"none"},collection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},filters:{value:null,enumerable:!0,writable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},metadata:{value:t&&t.metadata?t.metadata:{},enumerable:!0,writable:!0},roomId:{value:null,enumerable:!0,writable:!0},subscribeToSelf:{value:!t||"boolean"!=typeof t.subscribeToSelf||t.subscribeToSelf,enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["count"];return r&&i.indexOf(e)!==-1}}):this}function i(e){return e.error?this.callback(e.error):"jwtTokenExpired"===e.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):void(this.kuzzle.requestHistory[e.requestId]?(this.subscribeToSelf&&this.callback(null,e),delete this.kuzzle.requestHistory[e.requestId]):this.callback(null,e))}function o(){for(var e;this.queue.length>0;)e=this.queue.shift(),this[e.action].apply(this,e.args)}function u(){return"connected"===this.kuzzle.state&&!this.subscribing}var s=n(3);r.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("KuzzleRoom.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!u.call(this))return void this.queue.push({action:"count",args:[e]});if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),t,function(t,n){e(t,n&&n.result.count)})},r.prototype.renew=function(e,t,n){var r=Date.now(),u={scope:this.scope,state:this.state,users:this.users},s=this;return"function"==typeof e&&(n=t,t=e,e=null),n||(n=s.onDoneCB),s.kuzzle.callbackRequired("KuzzleRoom.renew",t),s.lastRenewal&&r-s.lastRenewal<=s.renewalDelay?n&&n(new Error("Subscription already renewed less than "+s.renewalDelay+"ms ago")):(e&&(s.filters=e),"connected"!==s.kuzzle.state?(s.callback=t,s.onDoneCB=n,void(s.kuzzle.subscriptions.pending[s.id]=s)):s.subscribing?void s.queue.push({action:"renew",args:[e,t,n]}):(s.unsubscribe(),s.roomId=null,s.subscribing=!0,s.callback=t,s.onDoneCB=n,s.kuzzle.subscriptions.pending[s.id]=s,u.body=s.filters,u=s.kuzzle.addHeaders(u,this.headers),void s.kuzzle.query(s.collection.buildQueryArgs("subscribe","on"),u,{metadata:s.metadata},function(e,t){return delete s.kuzzle.subscriptions.pending[s.id],s.subscribing=!1,e?(s.queue=[],n&&n(new Error("Error during Kuzzle subscription: "+e.message))):(s.lastRenewal=r,s.roomId=t.result.roomId,s.channel=t.result.channel,s.kuzzle.subscriptions[s.roomId]||(s.kuzzle.subscriptions[s.roomId]={}),s.kuzzle.subscriptions[s.roomId][s.id]=s,s.notifier=i.bind(s),s.kuzzle.network.on(s.channel,s.notifier),o.call(s),void(n&&n(null,s)))})))},r.prototype.unsubscribe=function(){var e,t=this,n=t.roomId;return u.call(this)?(n&&(t.kuzzle.network.off(t.channel,this.notifier),1===Object.keys(t.kuzzle.subscriptions[n]).length?(delete t.kuzzle.subscriptions[n],0===Object.keys(t.kuzzle.subscriptions.pending).length?t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[n]||t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[n][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(){this.cbs=[]}n.prototype.onDone=function(e){return this.cbs.push(e),this},n.prototype.done=function(e,t){this.cbs.forEach(function(n){n(e,t)})},e.exports=n},function(e,t,n){function r(e,t,r,i){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(n(12))(e,t,i);if(window.io)return new(n(11))(e,r,i);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(n(!function(){var e=new Error('Cannot find module "./wrappers/wsnode"');throw e.code="MODULE_NOT_FOUND",e}()))(e,t,i)}e.exports=r},function(e,t){function n(e,t,n){this.host=e,this.port=t,this.ssl=n,this.socket=null,this.connect=function(e,t){this.socket=window.io((this.ssl?"https://":"http://")+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0})},this.onConnect=function(e){this.socket.on("connect",e)},this.onConnectError=function(e){this.socket.on("connect_error",e)},this.onDisconnect=function(e){this.socket.on("disconnect",e)},this.onReconnect=function(e){this.socket.on("reconnect",e)},this.once=function(e,t){this.socket.once(e,t)},this.on=function(e,t){this.socket.on(e,t)},this.off=function(e,t){this.socket.off(e,t)},this.send=function(e){this.socket.emit("kuzzle",e)},this.close=function(){this.socket.close(),this.socket=null}}e.exports=n},function(e,t){function n(e,t,n){var o=this;this.host=e,this.port=t,this.ssl=n,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(e,t){this.client=new WebSocket((this.ssl?"wss://":"ws://")+this.host+":"+this.port),this.client.onopen=function(){o.retrying?r(o.listeners,"reconnect"):r(o.listeners,"connect")},this.client.onclose=function(n,u){1e3===n?r(o.listeners,"disconnect"):i.call(o,e,t,u)},this.client.onerror=function(n){i.call(o,e,t,n)},this.client.onmessage=function(e){var t=JSON.parse(e.data);t.room&&o.listeners[t.room]&&r(o.listeners,t.room,t)}},this.onConnect=function(e){this.listeners.connect.push({fn:e,keep:!0})},this.onConnectError=function(e){this.listeners.error.push({fn:e,keep:!0})},this.onDisconnect=function(e){this.listeners.disconnect.push({fn:e,keep:!0})},this.onReconnect=function(e){this.listeners.reconnect.push({fn:e,keep:!0})},this.once=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!1})},this.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!0})},this.off=function(e,t){var n;this.listeners[e]&&(n=this.listeners[e].findIndex(function(e){return e.fn===t}),n!==-1&&(1===this.listeners[e].length&&["error","connect","disconnect","reconnect"].indexOf(e)===-1?delete this.listeners[e]:this.listeners[e].splice(n,1)))},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function r(e,t,n){var r,i=e[t].length;for(r=0;r1?(e[t].splice(r,1),--r,--i):delete e[t])}function i(e,t,n){var i=this;e&&(i.retrying=!0,setTimeout(function(){i.connect(e,t)},t)),r(i.listeners,"error",n)}e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteProfile"},updateActionName:{value:"updateProfile"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["hydrate","save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n,r=this;if(!this.content.policies)throw new Error('Argument "policies" is mandatory in a profile. This argument contains an array of objects.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n=this.serialize(),r.kuzzle.query(r.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.prototype.addPolicy=function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an object containing at least a "roleId" member which must be a string.');return this.content.policies||(this.content.policies=[]),this.content.policies.push(e),this},r.prototype.setPolicies=function(e){if(!Array.isArray(e))throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string');return e.map(function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string')}),this.content.policies=e,this},r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},r.prototype.getPolicies=function(){return this.content.policies},e.exports=r},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteRole"},updateActionName:{value:"updateRole"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),n,e,t&&function(e){t(e,e?void 0:r)}),this},e.exports=r},function(e,t,n){function r(e){return Object.defineProperty(this,"kuzzle",{value:e}),Object.defineProperty(this,"buildQueryArgs",{value:function(e){return{controller:"security",action:e}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["roleFactory","profileFactory","userFactory","isActionAllowed"];return r&&i.indexOf(e)===-1}}):this}var i=n(14),o=n(13),u=n(2);r.prototype.getRole=function(e,t,n){var r,o=this;if(!e)throw new Error("Id parameter is mandatory for getRole function");n||"function"!=typeof t||(n=t,t=null),r={_id:e},o.kuzzle.callbackRequired("KuzzleSecurity.getRole",n),o.kuzzle.query(this.buildQueryArgs("getRole"),r,t,function(e,t){n(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.searchRoles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchRoles",n),r.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?n(e):(o=t.result.hits.map(function(e){return new i(r,e._id,e._source)}),void n(null,{total:t.result.total,roles:o}))})},r.prototype.createRole=function(e,t,n,r){var o=this,u={},s="createRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.updateRole=function(e,t,n,r){var o=this,u={_id:e,body:t},s="updateRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");return r||"function"!=typeof n||(r=n,n=null),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(n){r(n,n?void 0:new i(o,e,t))}),this},r.prototype.deleteRole=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.roleFactory=function(e,t){return new i(this,e,t)},r.prototype.getProfile=function(e,t,n){var r,i=this;if(n||"function"!=typeof t||(n=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getProfile function");r={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getProfile",n),i.kuzzle.query(this.buildQueryArgs("getProfile"),r,t,function(e,t){n(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.searchProfiles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",n),r.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new o(r,e._id,e._source)}),void n(null,{total:t.result.total,profiles:i}))})},r.prototype.createProfile=function(e,t,n,r){var i=this,u={},s="createProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceProfile":"createProfile"),i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.updateProfile=function(e,t,n,r){var i=this,u={},s="updateProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");return r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){var n={};return e?r(e):(Object.keys(t.result._source).forEach(function(e){n[e]=t.result._source[e]}),void r(null,new o(i,t.result._id,n)))}),this},r.prototype.deleteProfile=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.profileFactory=function(e,t){return new o(this,e,t)},r.prototype.getUser=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getUser function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("KuzzleSecurity.getUser",n),i.kuzzle.query(this.buildQueryArgs("getUser"),r,t,function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.searchUsers=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",n),r.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new u(r,e._id,e._source)}),void n(null,{total:t.result.total,users:i}))})},r.prototype.createUser=function(e,t,n,r){var i=this,o={_id:e,body:t},s="createUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");r||"function"!=typeof n||(r=n,n=null),n&&(s=n.replaceIfExist?"createOrReplaceUser":"createUser"),i.kuzzle.query(this.buildQueryArgs(s),o,null,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.updateUser=function(e,t,n,r){var i=this,o={},s="updateUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");return r||"function"!=typeof n||(r=n,n=null),o._id=e,o.body=t,i.kuzzle.query(this.buildQueryArgs(s),o,n,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))}),this},r.prototype.deleteUser=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.userFactory=function(e,t){return new u(this,e,t)},r.prototype.isActionAllowed=function(e,t,n,r,i){var o;if(!e||"object"!=typeof e)throw new Error("rights parameter is mandatory for isActionAllowed function");if(!t||"string"!=typeof t)throw new Error("controller parameter is mandatory for isActionAllowed function");if(!n||"string"!=typeof n)throw new Error("action parameter is mandatory for isActionAllowed function");return o=e.filter(function(e){return e.controller===t||"*"===e.controller}).filter(function(e){return e.action===n||"*"===e.action}).filter(function(e){return e.index===r||"*"===e.index}).filter(function(e){return e.collection===i||"*"===e.collection}),o.some(function(e){return"allowed"===e.value})?"allowed":o.some(function(e){return"conditional"===e.value})?"conditional":"denied"},r.prototype.getUserRights=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("Kuzzle.getUserRights",n),this.kuzzle.query(this.buildQueryArgs("getUserRights"),r,t,n&&function(e,t){n(e,e?void 0:t.result.hits)})},e.exports=r}])}); //# sourceMappingURL=kuzzle.js.map \ No newline at end of file diff --git a/dist/kuzzle.js.map b/dist/kuzzle.js.map index 4ac657593..50dc8ab34 100644 --- a/dist/kuzzle.js.map +++ b/dist/kuzzle.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap 227866ea638cf581dca7","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///../~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/kuzzleSubscribeResult.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","error","action","message","Error","assign","status","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","removeAllSubscriptions","unsubscribe","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","queryError","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","disconnect","onConnect","onConnectError","connectionError","internal","onDisconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","unsetJwtToken","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","KuzzleSubscribeResult","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","subscribeResult","done","bind","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","notificationCB","subscribeQuery","on","interval","off","setInterval","clearInterval","cbs","onDone","WebSocket","io","code","SocketIO","port","ssl","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onClientError","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId"],"mappings":"CAAA,SAAAA,EAAAC,GACA,mBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,QACA,sBAAAG,gBAAAC,IACAD,UAAAH,OACA,CACA,GAAAK,GAAAL,GACA,QAAAM,KAAAD,IAAA,gBAAAJ,iBAAAF,GAAAO,GAAAD,EAAAC,KAECC,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAT,OAGA,IAAAC,GAAAS,EAAAD,IACAT,WACAW,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAZ,EAAAD,QAAAC,IAAAD,QAAAQ,GAGAP,EAAAW,QAAA,EAGAX,EAAAD,QAvBA,GAAAU,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,GAGAR,EAAA,KDgBM,SAASP,EAAQD,EAASQ,GEolBhC,Q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AApB,EAAAvB,EAAA+K,GACA,GAAA8V,EAEA,KAAAD,GAAA,gBAAAA,GACA,SAAAnf,OAAA,6DAEA,KAAAkB,GAAA,gBAAAA,GACA,SAAAlB,OAAA,iEAEA,KAAAF,GAAA,gBAAAA,GACA,SAAAE,OAAA,6DAmBA,OAfAof,GAAAD,EACAle,OAAA,SAAAoe,GACA,MAAAA,GAAAne,gBAAA,MAAAme,EAAAne,aAEAD,OAAA,SAAAoe,GACA,MAAAA,GAAAvf,YAAA,MAAAuf,EAAAvf,SAEAmB,OAAA,SAAAoe,GACA,MAAAA,GAAA9gB,WAAA,MAAA8gB,EAAA9gB,QAEA0C,OAAA,SAAAoe,GACA,MAAAA,GAAA/V,gBAAA,MAAA+V,EAAA/V,aAIA8V,EAAAE,KAAA,SAAAC,GAA2C,kBAAAA,EAAA/c,QAC3C,UAGA4c,EAAAE,KAAA,SAAAC,GAA2C,sBAAAA,EAAA/c,QAC3C,cAGA,UAWAT,EAAA+C,UAAA0a,cAAA,SAAAC,EAAApd,EAAA/C,GACA,GACAiJ,IAAYN,IAAAwX,GACZ1hB,EAAAZ,IAEA,KAAAsiB,GAAA,gBAAAA,GACA,SAAAzf,OAAA,2DAGAV,IAAA,kBAAA+C,KACA/C,EAAA+C,EACAA,EAAA,MAGAtE,EAAAsN,OAAAvD,iBAAA,uBAAAxI,GAEAnC,KAAAkO,OAAA/M,MAAAnB,KAAAqO,eAAA,iBAAAjD,EAAAlG,EAAA/C,GAAA,SAAAoH,EAAAC,GACArH,EAAAoH,IAAAnH,OAAAoH,EAAAK,OAAAoB,SAIAtL,EAAAD,QAAAkF","file":"kuzzle.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\n **/","(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(15),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(10);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle object constructor.\n\t *\n\t * @constructor\n\t * @param host - Server name or IP Address to the Kuzzle instance\n\t * @param [options] - Connection options\n\t * @param {responseCallback} [cb] - Handles connection response\n\t * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (host, options, cb) {\n\t var self = this;\n\t\n\t if (!(this instanceof Kuzzle)) {\n\t return new Kuzzle(host, options, cb);\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!host || host === '') {\n\t throw new Error('host argument missing');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // 'private' properties\n\t collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []},\n\t queryError: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\n\t },\n\t queuing: {\n\t value: false,\n\t writable: true\n\t },\n\t requestHistory: {\n\t value: {},\n\t writable: true\n\t },\n\t state: {\n\t value: 'initializing',\n\t writable: true\n\t },\n\t subscriptions: {\n\t /*\n\t Contains the centralized subscription list in the following format:\n\t pending: \n\t 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: kuzzleRoomInstance_...\n\t }\n\t\n\t This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n\t This structure also allows renewing subscriptions after a connection loss\n\t */\n\t value: {\n\t pending: {}\n\t },\n\t writable: true\n\t },\n\t // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n\t enumerable: true\n\t },\n\t defaultIndex: {\n\t value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n\t writable: true,\n\t enumerable: true\n\t },\n\t reconnectionDelay: {\n\t value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n\t enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t writable: true,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true,\n\t writable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n\t enumerable: true,\n\t writable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n\t enumerable: true\n\t },\n\t autoQueue: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoReplay: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoResubscribe: {\n\t value: true,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t /*\n\t Offline queue use the following format:\n\t [\n\t {\n\t ts: ,\n\t query: 'query',\n\t cb: callbackFunction\n\t }\n\t ]\n\t */\n\t offlineQueue: {\n\t value: [],\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueFilter: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueMaxSize: {\n\t value: 500,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueTTL: {\n\t value: 120000,\n\t enumerable: true,\n\t writable: true\n\t },\n\t replayInterval: {\n\t value: 10,\n\t enumerable: true,\n\t writable: true\n\t },\n\t jwtToken: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t offlineQueueLoader: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (options) {\n\t Object.keys(options).forEach(function (opt) {\n\t if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n\t self[opt] = options[opt];\n\t }\n\t });\n\t\n\t if (options.offlineMode === 'auto' && this.autoReconnect) {\n\t this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n\t }\n\t }\n\t\n\t // Helper function ensuring that this Kuzzle object is still valid before performing a query\n\t Object.defineProperty(this, 'isValid', {\n\t value: function () {\n\t if (self.state === 'disconnected') {\n\t throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n\t }\n\t }\n\t });\n\t\n\t // Helper function copying headers to the query data\n\t Object.defineProperty(this, 'addHeaders', {\n\t value: function (query, headers) {\n\t Object.keys(headers).forEach(function (header) {\n\t if (!query[header]) {\n\t query[header] = headers[header];\n\t }\n\t });\n\t\n\t return query;\n\t }\n\t });\n\t\n\t /**\n\t * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n\t * and is called by these methods\n\t */\n\t Object.defineProperty(this, 'callbackRequired', {\n\t value: function (errorMessagePrefix, callback) {\n\t if (!callback || typeof callback !== 'function') {\n\t throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * Create an attribute security that embed all methods to manage Role, Profile and User\n\t */\n\t Object.defineProperty(this, 'security', {\n\t value: new KuzzleSecurity(this),\n\t enumerable: true\n\t });\n\t\n\t /**\n\t * Emit an event to all registered listeners\n\t * An event cannot be emitted multiple times before a timeout has been reached.\n\t */\n\t Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\n\t\n\t\n\t if (!options || !options.connect || options.connect === 'auto') {\n\t this.connect();\n\t } else {\n\t this.state = 'ready';\n\t }\n\t\n\t cleanHistory(this.requestHistory);\n\t\n\t if (this.bluebird) {\n\t return this.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n\t 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n\t 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n\t ];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t};\n\t\n\t/**\n\t * Connects to a Kuzzle instance using the provided host name.\n\t * @returns {Object} this\n\t */\n\tKuzzle.prototype.connect = function () {\n\t var self = this;\n\t\n\t if (self.network) {\n\t self.disconnect();\n\t }\n\t\n\t self.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\t\n\t if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t return self;\n\t }\n\t\n\t self.state = 'connecting';\n\t self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\t\n\t self.network.onConnect(function () {\n\t self.state = 'connected';\n\t renewAllSubscriptions.call(self);\n\t dequeue.call(self);\n\t self.emitEvent('connected');\n\t\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t });\n\t\n\t self.network.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\n\t\n\t if (self.connectCB) {\n\t self.connectCB(connectionError);\n\t }\n\t });\n\t\n\t self.network.onDisconnect(function () {\n\t self.state = 'offline';\n\t\n\t if (!self.autoReconnect) {\n\t self.disconnect();\n\t }\n\t\n\t if (self.autoQueue) {\n\t self.queuing = true;\n\t }\n\t\n\t self.emitEvent('disconnected');\n\t });\n\t\n\t self.network.onReconnect(function () {\n\t var reconnect = function () {\n\t // renew subscriptions\n\t if (self.autoResubscribe) {\n\t renewAllSubscriptions.call(self);\n\t }\n\t\n\t // replay queued requests\n\t if (self.autoReplay) {\n\t cleanQueue.call(self);\n\t dequeue.call(self);\n\t }\n\t\n\t // alert listeners\n\t self.emitEvent('reconnected');\n\t };\n\t\n\t self.state = 'connected';\n\t\n\t if (self.jwtToken) {\n\t self.checkToken(self.jwtToken, function (err, res) {\n\t // shouldn't obtain an error but let's invalidate the token anyway\n\t if (err || !res.valid) {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired');\n\t }\n\t\n\t reconnect();\n\t });\n\t } else {\n\t reconnect();\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the jwtToken used to query kuzzle\n\t * @param token\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.setJwtToken = function(token) {\n\t if (typeof token === 'string') {\n\t this.jwtToken = token;\n\t } else if (typeof token === 'object') {\n\t if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n\t this.jwtToken = token.result.jwt;\n\t } else {\n\t this.emitEvent('loginAttempt', {\n\t success: false,\n\t error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n\t });\n\t\n\t return this;\n\t }\n\t } else {\n\t this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n\t return this;\n\t }\n\t\n\t renewAllSubscriptions.call(this);\n\t this.emitEvent('loginAttempt', {success: true});\n\t return this;\n\t};\n\t\n\t/**\n\t * Unset the jwtToken used to query kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.unsetJwtToken = function() {\n\t this.jwtToken = undefined;\n\t\n\t removeAllSubscriptions.call(this);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Get the jwtToken used by kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.getJwtToken = function() {\n\t return this.jwtToken;\n\t};\n\t\n\t/**\n\t * Send login request to kuzzle with credentials\n\t * If login success, store the jwtToken into kuzzle object\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param expiresIn\n\t * @param cb\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = arguments[1];\n\t } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n\t request.expiresIn = arguments[1];\n\t } else if (typeof arguments[1] === 'function') {\n\t cb = arguments[1];\n\t }\n\t }\n\t if (arguments[2]) {\n\t if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n\t request.expiresIn = arguments[2];\n\t } else if (typeof arguments[2] === 'function') {\n\t cb = arguments[2];\n\t }\n\t }\n\t if (arguments[3] && typeof arguments[3] === 'function') {\n\t cb = arguments[3];\n\t }\n\t\n\t if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, function(error, response) {\n\t if (!error) {\n\t if (response.result.jwt) {\n\t self.setJwtToken(response.result.jwt);\n\t }\n\t\n\t cb && cb(null, response.result);\n\t }\n\t else {\n\t cb && cb(error);\n\t self.emitEvent('loginAttempt', {success: false, error: error.message});\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Send logout request to kuzzle with jwtToken.\n\t *\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.logout = function (cb) {\n\t var\n\t self = this,\n\t request = {\n\t action: 'logout',\n\t controller: 'auth',\n\t requestId: uuid.v4(),\n\t body: {}\n\t };\n\t\n\t this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n\t if (error === null) {\n\t self.unsetJwtToken();\n\t cb(null, self);\n\t }\n\t else {\n\t cb(error);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Checks whether a given jwt token still represents a valid session in Kuzzle.\n\t *\n\t * @param {string} token The jwt token to check\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\n\t var\n\t request = {\n\t body: {\n\t token: token\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.checkToken', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Gets the rights array of the currently logged user.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzle.prototype.getMyRights = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.callbackRequired('Kuzzle.getMyRights', cb);\n\t\n\t self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Update current user in Kuzzle.\n\t *\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.updateSelf = function (content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t queryArgs = {controller: 'auth', action: 'updateSelf'};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data.body = content;\n\t\n\t self.query(queryArgs, data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n\t */\n\tfunction cleanQueue () {\n\t var\n\t self = this,\n\t now = Date.now(),\n\t lastDocumentIndex = -1;\n\t\n\t if (self.queueTTL > 0) {\n\t self.offlineQueue.forEach(function (query, index) {\n\t if (query.ts < now - self.queueTTL) {\n\t lastDocumentIndex = index;\n\t }\n\t });\n\t\n\t if (lastDocumentIndex !== -1) {\n\t self.offlineQueue\n\t .splice(0, lastDocumentIndex + 1)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t }\n\t\n\t if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n\t self.offlineQueue\n\t .splice(0, self.offlineQueue.length - self.queueMaxSize)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Clean history from requests made more than 10s ago\n\t */\n\tfunction cleanHistory (requestHistory) {\n\t var\n\t now = Date.now();\n\t\n\t Object.keys(requestHistory).forEach(function (key) {\n\t if (requestHistory[key] < now - 10000) {\n\t delete requestHistory[key];\n\t }\n\t });\n\t\n\t setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\n\t}\n\t\n\t/**\n\t * Emit a request to Kuzzle\n\t *\n\t * @param {object} request\n\t * @param {responseCallback} [cb]\n\t */\n\tfunction emitRequest (request, cb) {\n\t var\n\t self = this;\n\t\n\t if (self.jwtToken !== undefined || cb) {\n\t self.network.once(request.requestId, function (response) {\n\t var error = null;\n\t\n\t if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t if (response.error) {\n\t error = new Error(response.error.message);\n\t Object.assign(error, response.error);\n\t error.status = response.status;\n\t self.emitEvent('queryError', error, request, cb);\n\t }\n\t\n\t if (cb) {\n\t cb(error, response);\n\t }\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow KuzzleRoom.subscribeToSelf to work\n\t self.requestHistory[request.requestId] = Date.now();\n\t}\n\t\n\t/**\n\t * Play all queued requests, in order.\n\t */\n\tfunction dequeue () {\n\t var\n\t self = this,\n\t additionalQueue,\n\t uniqueQueue = {},\n\t dequeuingProcess = function () {\n\t if (self.offlineQueue.length > 0) {\n\t emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n\t self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\t\n\t setTimeout(function () {\n\t dequeuingProcess();\n\t }, Math.max(0, self.replayInterval));\n\t } else {\n\t self.queuing = false;\n\t }\n\t };\n\t\n\t if (self.offlineQueueLoader) {\n\t if (typeof self.offlineQueueLoader !== 'function') {\n\t throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n\t }\n\t\n\t additionalQueue = self.offlineQueueLoader();\n\t if (Array.isArray(additionalQueue)) {\n\t self.offlineQueue = additionalQueue\n\t .concat(self.offlineQueue)\n\t .filter(function (request) {\n\t // throws if the query object does not contain required attributes\n\t if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n\t throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n\t }\n\t\n\t return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n\t });\n\t } else {\n\t throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n\t }\n\t }\n\t\n\t dequeuingProcess();\n\t}\n\t\n\t/**\n\t * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n\t * successful login attempt\n\t */\n\tfunction renewAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.renew(subscription.callback);\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n\t */\n\tfunction removeAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.unsubscribe();\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n\t * insertion.\n\t *\n\t * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t if (listenerType !== 'function') {\n\t throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n\t }\n\t\n\t listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\n\t\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method returns all available statistics from Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAllStatistics = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\t\n\t this.query({controller:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n\t *\n\t * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n\t var\n\t queryCB,\n\t body;\n\t\n\t if (!cb) {\n\t if (arguments.length === 1) {\n\t cb = arguments[0];\n\t options = null;\n\t timestamp = null;\n\t } else {\n\t cb = arguments[1];\n\t if (typeof arguments[0] === 'object') {\n\t options = arguments[0];\n\t timestamp = null;\n\t } else {\n\t timestamp = arguments[0];\n\t options = null;\n\t }\n\t }\n\t }\n\t\n\t queryCB = function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, timestamp ? res.result.hits : [res.result]);\n\t };\n\t\n\t this.callbackRequired('Kuzzle.getStatistics', cb);\n\t\n\t body = timestamp ? {body: {startTime: timestamp}} : {};\n\t this.query({controller: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection object.\n\t * If no index is specified, takes the default index.\n\t *\n\t * @param {string} collection - The name of the data collection you want to manipulate\n\t * @param {string} [index] - The name of the data index containing the data collection\n\t * @returns {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = function(collection, index) {\n\t this.isValid();\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Unable to create a new data collection object: no index specified');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (typeof index !== 'string' || typeof collection !== 'string') {\n\t throw new Error('Invalid index or collection argument: string expected');\n\t }\n\t\n\t if (!this.collections[index]) {\n\t this.collections[index] = {};\n\t }\n\t\n\t if (!this.collections[index][collection]) {\n\t this.collections[index][collection] = new KuzzleDataCollection(this, collection, index);\n\t }\n\t\n\t return this.collections[index][collection];\n\t};\n\t\n\t/**\n\t * Empties the offline queue without replaying it.\n\t *\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.flushQueue = function () {\n\t this.offlineQueue = [];\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns the list of known persisted data collections.\n\t *\n\t * @param {string} [index] - Index containing collections to be listed\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\n\t\n\t args.forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.listCollections: index required');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listCollections', cb);\n\t\n\t if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.collections);\n\t });\n\t};\n\t\n\t/**\n\t * Returns the list of existing indexes in Kuzzle\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listIndexes = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listIndexes', cb);\n\t\n\t this.query({controller: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.indexes);\n\t });\n\t};\n\t\n\t/**\n\t * Disconnects from Kuzzle and invalidate this instance.\n\t */\n\tKuzzle.prototype.disconnect = function () {\n\t var collection;\n\t\n\t this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\n\t this.network = null;\n\t\n\t for (collection in this.collections) {\n\t if (this.collections.hasOwnProperty(collection)) {\n\t delete this.collections[collection];\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Returns the server informations\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getServerInfo = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getServerInfo', cb);\n\t\n\t this.query({controller: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.serverInfo);\n\t });\n\t};\n\t\n\t/**\n\t * Forces an index refresh\n\t *\n\t * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.refreshIndex = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.refreshIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.query({ index: index, controller: 'admin', action: 'refreshIndex'}, {}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns de current autoRefresh status for the given index\n\t *\n\t * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optinal arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAutoRefresh = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.getAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n\t this.query({ index: index, controller: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n\t};\n\t\n\t/**\n\t * (Un)Sets the autoRefresh flag on the given index\n\t *\n\t * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n\t * @param {boolean} autoRefresh - The autoRefresh value to set\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query result\n\t * @returns {object} this\n\t */\n\tKuzzle.prototype.setAutoRefresh = function () {\n\t var\n\t index,\n\t autoRefresh,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'boolean':\n\t autoRefresh = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.setAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (autoRefresh === undefined) {\n\t throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n\t }\n\t\n\t this.query({ index: index, controller: 'admin', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Return the current Kuzzle's UTC Epoch time, in milliseconds\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.now = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.now', cb);\n\t\n\t this.query({controller: 'read', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, res && res.result.now);\n\t });\n\t};\n\t\n\t/**\n\t * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n\t * Base method used to send read queries to Kuzzle\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} queryArgs - Query configuration\n\t * @param {object} query - The query data\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n\t var\n\t attr,\n\t object = {\n\t action: queryArgs.action,\n\t controller: queryArgs.controller,\n\t metadata: this.metadata\n\t },\n\t self = this;\n\t\n\t this.isValid();\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t if (options.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\n\t }\n\t }\n\t\n\t if (!query || typeof query !== 'object' || Array.isArray(query)) {\n\t throw new Error('Invalid query parameter: ' + query);\n\t }\n\t\n\t if (query.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && query.hasOwnProperty(attr)) {\n\t object[attr] = query[attr];\n\t }\n\t }\n\t\n\t object = self.addHeaders(object, this.headers);\n\t\n\t /*\n\t * Do not add the token for the checkToken route, to avoid getting a token error when\n\t * a developer simply wish to verify his token\n\t */\n\t if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n\t object.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + self.jwtToken;\n\t }\n\t\n\t if (queryArgs.collection) {\n\t object.collection = queryArgs.collection;\n\t }\n\t\n\t if (queryArgs.index) {\n\t object.index = queryArgs.index;\n\t }\n\t\n\t if (!object.requestId) {\n\t object.requestId = uuid.v4();\n\t }\n\t\n\t if (self.state === 'connected' || (options && options.queuable === false)) {\n\t if (self.state === 'connected') {\n\t emitRequest.call(this, object, cb);\n\t } else if (cb) {\n\t cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n\t }\n\t } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\n\t if (!self.queueFilter || self.queueFilter(object)) {\n\t self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n\t self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n\t }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replays the requests queued during offline mode.\n\t * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n\t */\n\tKuzzle.prototype.replayQueue = function () {\n\t if (this.state !== 'offline' && !this.autoReplay) {\n\t cleanQueue.call(this);\n\t dequeue.call(this);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Sets the default Kuzzle index\n\t *\n\t * @param index\n\t * @returns this\n\t */\n\tKuzzle.prototype.setDefaultIndex = function (index) {\n\t if (typeof index !== 'string') {\n\t throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n\t }\n\t\n\t if (index.length === 0) {\n\t throw new Error('Cannot set an empty index as the default index');\n\t }\n\t\n\t this.defaultIndex = index;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzle.prototype.setHeaders = function (content, replace) {\n\t var self = this;\n\t\n\t if (typeof content !== 'object' || Array.isArray(content)) {\n\t throw new Error('Expected a content object, received a ' + typeof content);\n\t }\n\t\n\t if (replace) {\n\t self.headers = content;\n\t } else {\n\t Object.keys(content).forEach(function (key) {\n\t self.headers[key] = content[key];\n\t });\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.startQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = true;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.stopQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = false;\n\t }\n\t\n\t return this;\n\t};\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\n\t\n\t if (!id) {\n\t throw new Error('A security document must have an id');\n\t }\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t kuzzle: {\n\t value: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\n\t },\n\t // read-only properties\n\t // writable properties\n\t id: {\n\t value: id,\n\t enumerable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'update'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {Object} data - New securityDocument content\n\t * @return {KuzzleSecurityDocument} this\n\t */\n\tKuzzleSecurityDocument.prototype.setContent = function (data) {\n\t this.content = data;\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a pojo\n\t *\n\t * @return {object} pojo representing this securityDocument\n\t */\n\tKuzzleSecurityDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Delete the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurityDocument.prototype.delete = function (options, cb) {\n\t var\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t if (cb) {\n\t cb(null, res.result._id);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Update the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} content - Content to add to KuzzleSecurityDocument\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurityDocument} this\n\t */\n\tKuzzleSecurityDocument.prototype.update = function (content, options, cb) {\n\t var\n\t data = {},\n\t self = this;\n\t\n\t if (typeof content !== 'object') {\n\t throw new Error('Parameter \"content\" must be a object');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = self.id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t self.setContent(response.result._source);\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteUser'\n\t },\n\t updateActionName: {\n\t value: 'updateUser'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.setProfiles = function (profileIds) {\n\t if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n\t throw new Error('Parameter \"profileIds\" must be an array of strings');\n\t }\n\t\n\t this.content.profileIds = profileIds;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.addProfile = function (profileId) {\n\t if (typeof profileId !== 'string') {\n\t throw new Error('Parameter \"profileId\" must be a string');\n\t }\n\t\n\t if (!this.content.profileIds) {\n\t this.content.profileIds = [];\n\t }\n\t\n\t if (this.content.profileIds.indexOf(profileId) === -1) {\n\t this.content.profileIds.push(profileId);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tKuzzleUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content};\n\t};\n\t\n\t/**\n\t * Return the associated profiles IDs\n\t *\n\t * @return {array} the associated profiles IDs\n\t */\n\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_rng) {\n\t // Math.random()-based (RNG)\n\t //\n\t // If all else fails, use Math.random(). It's fast, but is of unspecified\n\t // quality.\n\t var _rnds = new Array(16);\n\t _mathRNG = _rng = function() {\n\t for (var i = 0, r; i < 16; i++) {\n\t if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }\n\t _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n\t }\n\t\n\t return _rnds;\n\t };\n\t if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, bth = _byteToHex;\n\t return bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]];\n\t }\n\t\n\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(16) : null;\n\t options = null;\n\t }\n\t options = options || {};\n\t\n\t var rnds = options.random || (options.rng || _rng)();\n\t\n\t // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\t rnds[6] = (rnds[6] & 0x0f) | 0x40;\n\t rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\t\n\t // Copy bytes to buffer, if provided\n\t if (buf) {\n\t for (var ii = 0; ii < 16; ii++) {\n\t buf[i + ii] = rnds[ii];\n\t }\n\t }\n\t\n\t return buf || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8),\n\t KuzzleSubscribeResult = __webpack_require__(9);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n\t * or like a room for pub/sub messages.\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} collection - name of the data collection to handle\n\t * @param {string} index - Index containing the data collection\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, collection, index) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t index: {\n\t value: index,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (controller, action) {\n\t return {\n\t controller: controller,\n\t action: action,\n\t collection: this.collection,\n\t index: this.index\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Executes an advanced search on the data collection.\n\t *\n\t * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function.\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n\t var\n\t query,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', 'search'), query, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Returns the number of documents matching the provided set of filters.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.count = function (filters, options, cb) {\n\t var\n\t query;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t cb(error, result && result.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Create a new empty data collection, with no associated mapping.\n\t * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n\t * want to create and prepare data collections before storing documents in it.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.create = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('write', 'createCollection'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Create a new document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument object, or a document\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.createDocument = function (id, document, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'create';\n\t\n\t if (id && typeof id !== 'string') {\n\t cb = options;\n\t options = document;\n\t document = id;\n\t id = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (document instanceof KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\n\t }\n\t\n\t if (id) {\n\t data._id = id;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, self.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n\t var doc;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t doc = new KuzzleDocument(self, res.result._id, res.result._source);\n\t doc.version = res.result._version;\n\t cb(null, doc);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete persistent documents.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleDataCollection} this\n\t */\n\tKuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) {\n\t var\n\t action,\n\t data = {};\n\t\n\t if (typeof arg === 'string') {\n\t data._id = arg;\n\t action = 'delete';\n\t } else {\n\t data.body = arg;\n\t action = 'deleteByQuery';\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieve a single stored document using its unique document ID.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n\t */\n\tKuzzleDataCollection.prototype.getMapping = function (options, cb) {\n\t var kuzzleMapping;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\n\t};\n\t\n\t/**\n\t * Publish a realtime message\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument instance or a JSON object\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('write', 'publish'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replace an existing document with a new one.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to replace\n\t * @param {object} content - JSON object representing the new document version\n\t * @param {object} [options] - additional arguments\n\t * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n\t var\n\t self = this,\n\t data = {\n\t _id: documentId,\n\t body: content\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, cb && function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Subscribes to this data collection with a set of filters.\n\t * To subscribe to the entire data collection, simply provide an empty filter.\n\t *\n\t * @param {object} filters - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscriptions options\n\t * @param {responseCallback} cb - called for each new notification\n\t * @returns {*} KuzzleSubscribeResult object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var\n\t room,\n\t subscribeResult;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\t\n\t subscribeResult = new KuzzleSubscribeResult();\n\t room = new KuzzleRoom(this, options);\n\t\n\t room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\t\n\t return subscribeResult;\n\t};\n\t\n\t/**\n\t * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n\t * This method is a lot faster than removing all documents using a query.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.truncate = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('admin', 'truncateCollection'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Update parts of a document\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to update\n\t * @param {object} content - JSON object containing changes to perform on the document\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t data = {\n\t _id: documentId,\n\t body: content\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new KuzzleDocument(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - document id\n\t * @param {object} content - document content\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [options] - subscription configuration\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [mapping] - mapping to instantiate the KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(this, mapping);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n\t * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n\t * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n\t * the amount of data you stored in a collection and the complexity of your database.\n\t *\n\t * The KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t mapping: {\n\t value: mapping || {},\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['set', 'setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Applies the new mapping to the data collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleDataMapping.prototype.apply = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.collection.buildQueryArgs('admin', 'updateMapping'), data, options, function (err) {\n\t if (err) {\n\t return cb && cb(err);\n\t }\n\t\n\t self.refresh(options, cb);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with the mapping stored in Kuzzle\n\t *\n\t * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDataMapping.prototype.refresh = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('admin', 'getMapping'), data, options, function (err, res) {\n\t if (err) {\n\t return cb ? cb(err) : false;\n\t }\n\t\n\t if (res.result[self.collection.index]) {\n\t if (res.result[self.collection.index].mappings[self.collection.collection]) {\n\t self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\t\n\t // Mappings can be empty. The mapping property should never be \"undefined\"\n\t if (self.mapping === undefined) {\n\t self.mapping = {};\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n\t }\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Adds or updates a field mapping.\n\t *\n\t * Changes made by this function won’t be applied until you call the apply method\n\t *\n\t * @param {string} field - Name of the field from which the mapping is to be added or updated\n\t * @param {object} mapping - corresponding field mapping\n\t * @returns {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.prototype.set = function (field, mapping) {\n\t this.mapping[field] = mapping;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle handles documents either as realtime messages or as stored documents.\n\t * KuzzleDocument is the object representation of one of these documents.\n\t *\n\t * Notes:\n\t * - this constructor may be called either with a documentId, a content, neither or both.\n\t * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n\t *\n\t *\n\t * @param {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n\t * @param {string} [documentId] - ID of an existing document\n\t * @param {object} [content] - Initializes this document with the provided content\n\t * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t id: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t version: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t // handling provided arguments\n\t if (!content && documentId && typeof documentId === 'object') {\n\t content = documentId;\n\t documentId = null;\n\t }\n\t\n\t if (content) {\n\t if (content._version) {\n\t this.version = content._version;\n\t delete content._version;\n\t }\n\t this.setContent(content, true);\n\t }\n\t\n\t if (documentId) {\n\t Object.defineProperty(this, 'id', {\n\t value: documentId,\n\t enumerable: true\n\t });\n\t }\n\t\n\t // promisifying\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'refresh', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this document\n\t */\n\tKuzzleDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data._version = this.version;\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Overrides the toString() method in order to return a serialized version of the document\n\t *\n\t * @return {string} serialized version of this object\n\t */\n\tKuzzleDocument.prototype.toString = function () {\n\t return JSON.stringify(this.serialize());\n\t};\n\t\n\t/**\n\t * Deletes this document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.delete = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n\t cb(err, err ? undefined : self.id);\n\t });\n\t};\n\t\n\t/**\n\t * Replaces the current content with the last version of this document stored in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.refresh = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n\t var newDocument;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\n\t newDocument.version = res.result._version;\n\t\n\t cb(null, newDocument);\n\t });\n\t};\n\t\n\t/**\n\t * Saves this document into Kuzzle.\n\t *\n\t * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n\t * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'createOrReplace'), data, options, function (error, res) {\n\t if (error) {\n\t return cb && cb(error);\n\t }\n\t\n\t self.id = res.result._id;\n\t self.version = res.result._version;\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Sends the content of this document as a realtime message.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'publish'), data, options);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {object} data - New content\n\t * @param {boolean} replace - if true: replace this document content with the provided data\n\t */\n\tKuzzleDocument.prototype.setContent = function (data, replace) {\n\t var self = this;\n\t\n\t if (replace) {\n\t this.content = data;\n\t }\n\t else {\n\t Object.keys(data).forEach(function (key) {\n\t self.content[key] = data[key];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Listens to events concerning this document. Has no effect if the document does not have an ID\n\t * (i.e. if the document has not yet been created as a persisted document).\n\t *\n\t * @param {object} [options] - subscription options\n\t * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n\t */\n\tKuzzleDocument.prototype.subscribe = function (options, cb) {\n\t var filters;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided');\n\t }\n\t\n\t filters = { ids: { values: [this.id] } };\n\t\n\t return this.dataCollection.subscribe(filters, options, cb);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDocument.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t\n\tmodule.exports = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * Kuzzle's memory storage is a separate data store from the database layer.\n\t * It is internaly based on Redis. You can access most of Redis functions (all\n\t * lowercased), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(kuzzle) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t this.setHeaders = kuzzle.setHeaders.bind(this);\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.prototype[command] = function () {\n\t var\n\t args = Array.prototype.slice.call(arguments),\n\t options = null,\n\t cb,\n\t query = {\n\t controller: 'ms',\n\t action: command\n\t },\n\t data = {};\n\t\n\t if (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n\t *\n\t * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n\t *\n\t * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n\t * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n\t * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n\t *\n\t * @param {object} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, options) {\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t callback: {\n\t value: null,\n\t writable: true\n\t },\n\t channel: {\n\t value: null,\n\t writable: true\n\t },\n\t id: {\n\t value: uuid.v4()\n\t },\n\t lastRenewal: {\n\t value: null,\n\t writable: true\n\t },\n\t notifier: {\n\t value: null,\n\t writable: true\n\t },\n\t queue: {\n\t value: [],\n\t writable: true\n\t },\n\t // Delay before allowing a subscription renewal\n\t renewalDelay: {\n\t value: 500\n\t },\n\t scope: {\n\t value: options && options.scope ? options.scope : 'all'\n\t },\n\t state: {\n\t value: options && options.state ? options.state : 'done'\n\t },\n\t subscribing: {\n\t value: false,\n\t writable: true\n\t },\n\t users: {\n\t value: options && options.users ? options.users : 'none'\n\t },\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t filters: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t roomId: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t subscribeToSelf: {\n\t value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['count'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Returns the number of other subscriptions on that room.\n\t *\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.count', cb);\n\t\n\t data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\t\n\t if (!isReady.call(this)) {\n\t this.queue.push({action: 'count', args: [cb]});\n\t return;\n\t }\n\t\n\t if (!this.roomId) {\n\t throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n\t cb(err, res && res.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Renew the subscription using new filters\n\t *\n\t * @param {object} [filters] - Filters in Kuzzle DSL format\n\t * @param {responseCallback} notificationCB - called for each new notification\n\t * @param {responseCallback} [cb] - handles the query response\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, notificationCB, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (typeof filters === 'function') {\n\t cb = notificationCB;\n\t notificationCB = filters;\n\t filters = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', notificationCB);\n\t\n\t /*\n\t Skip subscription renewal if another one was performed a moment before\n\t */\n\t if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n\t return;\n\t }\n\t\n\t if (filters) {\n\t self.filters = filters;\n\t }\n\t\n\t /*\n\t if not yet connected, register itself to the subscriptions list and wait for the\n\t main Kuzzle object to renew once online\n\t */\n\t if (self.kuzzle.state !== 'connected') {\n\t self.callback = notificationCB;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t return;\n\t }\n\t\n\t if (self.subscribing) {\n\t self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n\t return;\n\t }\n\t\n\t self.unsubscribe();\n\t self.roomId = null;\n\t self.subscribing = true;\n\t self.callback = notificationCB;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t\n\t subscribeQuery.body = self.filters;\n\t subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n\t delete self.kuzzle.subscriptions.pending[self.id];\n\t self.subscribing = false;\n\t\n\t if (error) {\n\t self.queue = [];\n\t return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n\t }\n\t\n\t self.lastRenewal = now;\n\t self.roomId = response.result.roomId;\n\t self.channel = response.result.channel;\n\t\n\t if (!self.kuzzle.subscriptions[self.roomId]) {\n\t self.kuzzle.subscriptions[self.roomId] = {};\n\t }\n\t\n\t self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\t\n\t self.notifier = notificationCallback.bind(self);\n\t self.kuzzle.network.on(self.channel, self.notifier);\n\t\n\t dequeue.call(self);\n\t cb && cb(null, self);\n\t });\n\t};\n\t\n\t/**\n\t * Unsubscribes from Kuzzle.\n\t *\n\t * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n\t * pending subscriptions reaches 0, and only if there is still no listener on that room.\n\t * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n\t *\n\t * @return {*} this\n\t */\n\tKuzzleRoom.prototype.unsubscribe = function () {\n\t var\n\t self = this,\n\t room = self.roomId,\n\t interval;\n\t\n\t if (!isReady.call(this)) {\n\t self.queue.push({action: 'unsubscribe', args: []});\n\t return self;\n\t }\n\t\n\t if (room) {\n\t self.kuzzle.network.off(self.channel, this.notifier);\n\t\n\t if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n\t delete self.kuzzle.subscriptions[room];\n\t\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n\t } else {\n\t interval = setInterval(function () {\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t if (!self.kuzzle.subscriptions[room]) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n\t }\n\t clearInterval(interval);\n\t }\n\t }, 100);\n\t }\n\t } else {\n\t delete self.kuzzle.subscriptions[room][self.id];\n\t }\n\t\n\t self.roomId = null;\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleRoom.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t/**\n\t * Callback called by the network handler when a message is sent to the subscribed room ID\n\t * Calls the registered callback if the notification passes the subscription filters\n\t *\n\t * @param {object} data - data\n\t * @returns {*}\n\t */\n\tfunction notificationCallback (data) {\n\t if (data.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\n\t }\n\t\n\t if (this.kuzzle.requestHistory[data.requestId]) {\n\t if (this.subscribeToSelf) {\n\t this.callback(null, data);\n\t }\n\t delete this.kuzzle.requestHistory[data.requestId];\n\t } else {\n\t this.callback(null, data);\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Dequeue actions performed while subscription was being renewed\n\t */\n\tfunction dequeue () {\n\t var element;\n\t\n\t while (this.queue.length > 0) {\n\t element = this.queue.shift();\n\t\n\t this[element.action].apply(this, element.args);\n\t }\n\t}\n\t\n\tfunction isReady() {\n\t return this.kuzzle.state === 'connected' && !this.subscribing;\n\t}\n\t\n\tmodule.exports = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports) {\n\n\t/**\n\t * Sugar-code handling the result of a KuzzleRoom.renew call\n\t * @constructor\n\t */\n\tfunction KuzzleSubscribeResult() {\n\t this.cbs = [];\n\t}\n\t\n\t/**\n\t * Registers a callback to be called with a subscription result\n\t * @param {Function} cb\n\t */\n\tKuzzleSubscribeResult.prototype.onDone = function (cb) {\n\t this.cbs.push(cb);\n\t return this;\n\t};\n\t\n\t/**\n\t * Calls all registered callbacks\n\t *\n\t * @param {Object} error object\n\t * @param {KuzzleRoom} room\n\t */\n\tKuzzleSubscribeResult.prototype.done = function (error, room) {\n\t this.cbs.forEach(function (cb) {\n\t cb(error, room);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSubscribeResult;\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort, sslConnection) {\n\t // Web browser / NodeJS websocket handling\n\t if (typeof window !== 'undefined') {\n\t // use native websockets if the browser supports it\n\t if (typeof WebSocket !== 'undefined') {\n\t return new (__webpack_require__(12))(host, wsPort, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(11))(host, ioPort, sslConnection);\n\t }\n\t\n\t throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n\t }\n\t\n\t return new (__webpack_require__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction SocketIO(host, port, ssl) {\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.socket = null;\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n\t reconnection: autoReconnect,\n\t reconnectionDelay: reconnectionDelay,\n\t forceNew: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t this.socket.on('connect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t this.socket.on('connect_error', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t this.socket.on('disconnect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t this.socket.on('reconnect', callback);\n\t };\n\t\n\t /**\n\t * Registers a callback on a room. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.once = function (roomId, callback) {\n\t this.socket.once(roomId, callback);\n\t };\n\t\n\t /**\n\t * Registers a callback on a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.on = function (roomId, callback) {\n\t this.socket.on(roomId, callback);\n\t };\n\t\n\t /**\n\t * Unregisters a callback from a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.off = function (roomId, callback) {\n\t this.socket.off(roomId, callback);\n\t };\n\t\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t this.socket.emit('kuzzle', payload);\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port, ssl) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t * @returns {Object} Socket\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function (code, message) {\n\t if (code === 1000) {\n\t poke(self.listeners, 'disconnect');\n\t }\n\t else {\n\t onClientError.call(self, autoReconnect, reconnectionDelay, message);\n\t }\n\t };\n\t\n\t this.client.onerror = function (error) {\n\t onClientError.call(self, autoReconnect, reconnectionDelay, error);\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, data);\n\t }\n\t };\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t this.listeners.connect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t this.listeners.error.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Registers a callback on a room. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.once = function (roomId, callback) {\n\t if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\n\t };\n\t\n\t /**\n\t * Registers a callback on a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.on = function (roomId, callback) {\n\t if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Unregisters a callback from a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.off = function (roomId, callback) {\n\t var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\n\t }\n\t };\n\t\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t if (this.client && this.client.readyState === this.client.OPEN) {\n\t this.client.send(JSON.stringify(payload));\n\t }\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * Called when the connection closes with an error state\n\t *\n\t * @param {boolean} autoReconnect\n\t * @param {number} reconnectionDelay\n\t * @param {string|Object} message\n\t */\n\tfunction onClientError(autoReconnect, reconnectionDelay, message) {\n\t var self = this;\n\t\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error', message);\n\t}\n\t\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteProfile'\n\t },\n\t updateActionName: {\n\t value: 'updateProfile'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['hydrate', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\n\t }\n\t});\n\t\n\t/**\n\t * Persist to the persistent layer the current profile\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.save = function (options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!this.content.policies) {\n\t throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.serialize();\n\t\n\t self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Add a policy in the policies list\n\t * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n\t *\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.addPolicy = function (policy) {\n\t\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n\t }\n\t\n\t if (!this.content.policies) {\n\t this.content.policies = [];\n\t }\n\t\n\t this.content.policies.push(policy);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set policies list\n\t * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.setPolicies = function (policies) {\n\t\n\t if (!Array.isArray(policies)) {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t\n\t policies.map(function (policy) {\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t });\n\t\n\t this.content.policies = policies;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this securityDocument\n\t */\n\tKuzzleProfile.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Returns the list of policies associated to this profile.\n\t * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @return {object} an array of policies\n\t */\n\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteRole'\n\t },\n\t updateActionName: {\n\t value: 'updateRole'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\n\t }\n\t});\n\t\n\t/**\n\t * Saves this role into Kuzzle.\n\t *\n\t * If this is a new role, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleRole} this object\n\t */\n\tKuzzleRole.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleRole;\n\n/***/ },\n/* 15 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(14),\n\t KuzzleProfile = __webpack_require__(13),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(kuzzle) {\n\t\n\t Object.defineProperty(this, 'kuzzle', {\n\t value: kuzzle\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (action) {\n\t return {\n\t controller: 'security',\n\t action: action\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['roleFactory', 'profileFactory', 'userFactory', 'isActionAllowed'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * Retrieve a single Role using its unique role ID.\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!id) {\n\t throw new Error('Id parameter is mandatory for getRole function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on roles according to a filter\n\t *\n\t * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.prototype.searchRoles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchRoles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = result.result.hits.map(function (doc) {\n\t return new KuzzleRole(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: result.result.total, roles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new role in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same role already exists: throw an error if sets to false.\n\t * Replace the existing role otherwise\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createRole: cannot create a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleRole(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a role in Kuzzle.\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateRole: cannot update a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err) {\n\t cb(err, err ? undefined : new KuzzleRole(self, id, content));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete role.\n\t *\n\t * There is a small delay between role deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Role id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteRole = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRole object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - role id\n\t * @param {object} content - role content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\n\t};\n\t\n\t\n\t/**\n\t * Get a specific profile from kuzzle\n\t *\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on profiles according to a filter\n\t *\n\t *\n\t * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.searchProfiles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new profile in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same profile already exists: throw an error if sets to false.\n\t * Replace the existing profile otherwise\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createProfile: cannot create a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleProfile(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a profile in Kuzzle.\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateProfile: cannot update a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t var updatedContent = {};\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t Object.keys(res.result._source).forEach(function (property) {\n\t updatedContent[property] = res.result._source[property];\n\t });\n\t\n\t cb(null, new KuzzleProfile(self, res.result._id, updatedContent));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete profile.\n\t *\n\t * There is a small delay between profile deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteProfile = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleProfile object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - profile id\n\t * @param {object} content - profile content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\n\t};\n\t\n\t/**\n\t * Get a specific user from kuzzle using its unique ID\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n\t var\n\t data = {_id: id},\n\t self = this;\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for getUser function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on user according to a filter\n\t *\n\t * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - same filters as documents filters\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.searchUsers = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profile` in `content` must only contains the profile id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateUser: cannot update an user without an user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete user.\n\t *\n\t * There is a small delay between user deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteUser = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleUser object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - user id\n\t * @param {object} content - user content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\n\t};\n\t\n\t/**\n\t * Tells whether an action is allowed, denied or conditional based on the rights\n\t * rights provided as the first argument. An action is defined as a couple of\n\t * action and controller (mandatory), plus an index and a collection(optional).\n\t *\n\t * @param {object} rights - The rights rights associated to a user\n\t * (see getMyrights and getUserrights).\n\t * @param {string} controller - The controller to check the action onto.\n\t * @param {string} action - The action to perform.\n\t * @param {string} index - (optional) The name of index to perform the action onto.\n\t * @param {string} collection - (optional) The name of the collection to perform the action onto.\n\t *\n\t * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n\t * correspond to rights containing closures.\n\t * See also http://kuzzle.io/guide/#roles-definition\n\t */\n\tKuzzleSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n\t var filteredRights;\n\t\n\t if (!rights || typeof rights !== 'object') {\n\t throw new Error('rights parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!controller || typeof controller !== 'string') {\n\t throw new Error('controller parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!action || typeof action !== 'string') {\n\t throw new Error('action parameter is mandatory for isActionAllowed function');\n\t }\n\t\n\t // We filter in all the rights that match the request (including wildcards).\n\t filteredRights = rights\n\t .filter(function (right) {\n\t return right.controller === controller || right.controller === '*';\n\t })\n\t .filter(function (right) {\n\t return right.action === action || right.action === '*';\n\t })\n\t .filter(function (right) {\n\t return right.index === index || right.index === '*';\n\t })\n\t .filter(function (right) {\n\t return right.collection === collection || right.collection === '*';\n\t });\n\t\n\t // Then, if at least one right allows the action, we return 'allowed'\n\t if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n\t return 'allowed';\n\t }\n\t // If no right allows the action, we check for conditionals.\n\t if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n\t return 'conditional';\n\t }\n\t // Otherwise we return 'denied'.\n\t return 'denied';\n\t};\n\t\n\t\n\t/**\n\t * Gets the rights array of a given user.\n\t *\n\t * @param {string} userId The id of the user.\n\t * @param {object} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.prototype.getUserRights = function (userId, options, cb) {\n\t var\n\t data = {_id: userId},\n\t self = this;\n\t\n\t if (!userId || typeof userId !== 'string') {\n\t throw new Error('userId parameter is mandatory for getUserRights function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap 227866ea638cf581dca7\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\n networkWrapper = require('./networkWrapper');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle object constructor.\n *\n * @constructor\n * @param host - Server name or IP Address to the Kuzzle instance\n * @param [options] - Connection options\n * @param {responseCallback} [cb] - Handles connection response\n * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!host || host === '') {\n throw new Error('host argument missing');\n }\n\n Object.defineProperties(this, {\n // 'private' properties\n collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []},\n queryError: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\n },\n queuing: {\n value: false,\n writable: true\n },\n requestHistory: {\n value: {},\n writable: true\n },\n state: {\n value: 'initializing',\n writable: true\n },\n subscriptions: {\n /*\n Contains the centralized subscription list in the following format:\n pending: \n 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: kuzzleRoomInstance_...\n }\n\n This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n This structure also allows renewing subscriptions after a connection loss\n */\n value: {\n pending: {}\n },\n writable: true\n },\n // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n enumerable: true\n },\n defaultIndex: {\n value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n writable: true,\n enumerable: true\n },\n reconnectionDelay: {\n value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n enumerable: true\n },\n host: {\n value: host,\n writable: true,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true,\n writable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n enumerable: true,\n writable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n enumerable: true\n },\n autoQueue: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoReplay: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoResubscribe: {\n value: true,\n enumerable: true,\n writable: true\n },\n headers: {\n value: {},\n enumerable: true,\n writable: true\n },\n metadata: {\n value: {},\n enumerable: true,\n writable: true\n },\n /*\n Offline queue use the following format:\n [\n {\n ts: ,\n query: 'query',\n cb: callbackFunction\n }\n ]\n */\n offlineQueue: {\n value: [],\n enumerable: true,\n writable: true\n },\n queueFilter: {\n value: null,\n enumerable: true,\n writable: true\n },\n queueMaxSize: {\n value: 500,\n enumerable: true,\n writable: true\n },\n queueTTL: {\n value: 120000,\n enumerable: true,\n writable: true\n },\n replayInterval: {\n value: 10,\n enumerable: true,\n writable: true\n },\n jwtToken: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n offlineQueueLoader: {\n value: null,\n enumerable: true,\n writable: true\n }\n });\n\n if (options) {\n Object.keys(options).forEach(function (opt) {\n if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n self[opt] = options[opt];\n }\n });\n\n if (options.offlineMode === 'auto' && this.autoReconnect) {\n this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n }\n }\n\n // Helper function ensuring that this Kuzzle object is still valid before performing a query\n Object.defineProperty(this, 'isValid', {\n value: function () {\n if (self.state === 'disconnected') {\n throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n }\n }\n });\n\n // Helper function copying headers to the query data\n Object.defineProperty(this, 'addHeaders', {\n value: function (query, headers) {\n Object.keys(headers).forEach(function (header) {\n if (!query[header]) {\n query[header] = headers[header];\n }\n });\n\n return query;\n }\n });\n\n /**\n * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n * and is called by these methods\n */\n Object.defineProperty(this, 'callbackRequired', {\n value: function (errorMessagePrefix, callback) {\n if (!callback || typeof callback !== 'function') {\n throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n }\n }\n });\n\n /**\n * Create an attribute security that embed all methods to manage Role, Profile and User\n */\n Object.defineProperty(this, 'security', {\n value: new KuzzleSecurity(this),\n enumerable: true\n });\n\n /**\n * Emit an event to all registered listeners\n * An event cannot be emitted multiple times before a timeout has been reached.\n */\n Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\n\n if (this.bluebird) {\n return this.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\n\n/**\n * Connects to a Kuzzle instance using the provided host name.\n * @returns {Object} this\n */\nKuzzle.prototype.connect = function () {\n var self = this;\n\n if (self.network) {\n self.disconnect();\n }\n\n self.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\n if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n return self;\n }\n\n self.state = 'connecting';\n self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\n self.network.onConnect(function () {\n self.state = 'connected';\n renewAllSubscriptions.call(self);\n dequeue.call(self);\n self.emitEvent('connected');\n\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n });\n\n self.network.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\n\n if (self.connectCB) {\n self.connectCB(connectionError);\n }\n });\n\n self.network.onDisconnect(function () {\n self.state = 'offline';\n\n if (!self.autoReconnect) {\n self.disconnect();\n }\n\n if (self.autoQueue) {\n self.queuing = true;\n }\n\n self.emitEvent('disconnected');\n });\n\n self.network.onReconnect(function () {\n var reconnect = function () {\n // renew subscriptions\n if (self.autoResubscribe) {\n renewAllSubscriptions.call(self);\n }\n\n // replay queued requests\n if (self.autoReplay) {\n cleanQueue.call(self);\n dequeue.call(self);\n }\n\n // alert listeners\n self.emitEvent('reconnected');\n };\n\n self.state = 'connected';\n\n if (self.jwtToken) {\n self.checkToken(self.jwtToken, function (err, res) {\n // shouldn't obtain an error but let's invalidate the token anyway\n if (err || !res.valid) {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired');\n }\n\n reconnect();\n });\n } else {\n reconnect();\n }\n });\n\n return this;\n};\n\n/**\n * Set the jwtToken used to query kuzzle\n * @param token\n * @returns {Kuzzle}\n */\nKuzzle.prototype.setJwtToken = function(token) {\n if (typeof token === 'string') {\n this.jwtToken = token;\n } else if (typeof token === 'object') {\n if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n this.jwtToken = token.result.jwt;\n } else {\n this.emitEvent('loginAttempt', {\n success: false,\n error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n });\n\n return this;\n }\n } else {\n this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n return this;\n }\n\n renewAllSubscriptions.call(this);\n this.emitEvent('loginAttempt', {success: true});\n return this;\n};\n\n/**\n * Unset the jwtToken used to query kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.unsetJwtToken = function() {\n this.jwtToken = undefined;\n\n removeAllSubscriptions.call(this);\n\n return this;\n};\n\n/**\n * Get the jwtToken used by kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.getJwtToken = function() {\n return this.jwtToken;\n};\n\n/**\n * Send login request to kuzzle with credentials\n * If login success, store the jwtToken into kuzzle object\n *\n * @param strategy\n * @param credentials\n * @param expiresIn\n * @param cb\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = arguments[1];\n } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n request.expiresIn = arguments[1];\n } else if (typeof arguments[1] === 'function') {\n cb = arguments[1];\n }\n }\n if (arguments[2]) {\n if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n request.expiresIn = arguments[2];\n } else if (typeof arguments[2] === 'function') {\n cb = arguments[2];\n }\n }\n if (arguments[3] && typeof arguments[3] === 'function') {\n cb = arguments[3];\n }\n\n if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, function(error, response) {\n if (!error) {\n if (response.result.jwt) {\n self.setJwtToken(response.result.jwt);\n }\n\n cb && cb(null, response.result);\n }\n else {\n cb && cb(error);\n self.emitEvent('loginAttempt', {success: false, error: error.message});\n }\n });\n};\n\n/**\n * Send logout request to kuzzle with jwtToken.\n *\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.logout = function (cb) {\n var\n self = this,\n request = {\n action: 'logout',\n controller: 'auth',\n requestId: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n if (error === null) {\n self.unsetJwtToken();\n cb(null, self);\n }\n else {\n cb(error);\n }\n });\n\n return self;\n};\n\n/**\n * Checks whether a given jwt token still represents a valid session in Kuzzle.\n *\n * @param {string} token The jwt token to check\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n });\n};\n\n/**\n * Gets the rights array of the currently logged user.\n *\n * @param {object} [options] - Optional parameters\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzle.prototype.getMyRights = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.callbackRequired('Kuzzle.getMyRights', cb);\n\n self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n};\n\n/**\n * Update current user in Kuzzle.\n *\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.updateSelf = function (content, options, cb) {\n var\n self = this,\n data = {},\n queryArgs = {controller: 'auth', action: 'updateSelf'};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data.body = content;\n\n self.query(queryArgs, data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return this;\n};\n\n/**\n * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n */\nfunction cleanQueue () {\n var\n self = this,\n now = Date.now(),\n lastDocumentIndex = -1;\n\n if (self.queueTTL > 0) {\n self.offlineQueue.forEach(function (query, index) {\n if (query.ts < now - self.queueTTL) {\n lastDocumentIndex = index;\n }\n });\n\n if (lastDocumentIndex !== -1) {\n self.offlineQueue\n .splice(0, lastDocumentIndex + 1)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n }\n\n if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n self.offlineQueue\n .splice(0, self.offlineQueue.length - self.queueMaxSize)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n}\n\n\n/**\n * Clean history from requests made more than 10s ago\n */\nfunction cleanHistory (requestHistory) {\n var\n now = Date.now();\n\n Object.keys(requestHistory).forEach(function (key) {\n if (requestHistory[key] < now - 10000) {\n delete requestHistory[key];\n }\n });\n\n setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\n}\n\n/**\n * Emit a request to Kuzzle\n *\n * @param {object} request\n * @param {responseCallback} [cb]\n */\nfunction emitRequest (request, cb) {\n var\n self = this;\n\n if (self.jwtToken !== undefined || cb) {\n self.network.once(request.requestId, function (response) {\n var error = null;\n\n if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n if (response.error) {\n error = new Error(response.error.message);\n Object.assign(error, response.error);\n error.status = response.status;\n self.emitEvent('queryError', error, request, cb);\n }\n\n if (cb) {\n cb(error, response);\n }\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.subscribeToSelf to work\n self.requestHistory[request.requestId] = Date.now();\n}\n\n/**\n * Play all queued requests, in order.\n */\nfunction dequeue () {\n var\n self = this,\n additionalQueue,\n uniqueQueue = {},\n dequeuingProcess = function () {\n if (self.offlineQueue.length > 0) {\n emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\n setTimeout(function () {\n dequeuingProcess();\n }, Math.max(0, self.replayInterval));\n } else {\n self.queuing = false;\n }\n };\n\n if (self.offlineQueueLoader) {\n if (typeof self.offlineQueueLoader !== 'function') {\n throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n }\n\n additionalQueue = self.offlineQueueLoader();\n if (Array.isArray(additionalQueue)) {\n self.offlineQueue = additionalQueue\n .concat(self.offlineQueue)\n .filter(function (request) {\n // throws if the query object does not contain required attributes\n if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n }\n\n return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n });\n } else {\n throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n }\n }\n\n dequeuingProcess();\n}\n\n/**\n * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n * successful login attempt\n */\nfunction renewAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.renew(subscription.callback);\n });\n });\n}\n\n/**\n * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n */\nfunction removeAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.unsubscribe();\n });\n });\n}\n\n/**\n * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n * insertion.\n *\n * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\n\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method returns all available statistics from Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAllStatistics = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\n this.query({controller:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n};\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n *\n * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n var\n queryCB,\n body;\n\n if (!cb) {\n if (arguments.length === 1) {\n cb = arguments[0];\n options = null;\n timestamp = null;\n } else {\n cb = arguments[1];\n if (typeof arguments[0] === 'object') {\n options = arguments[0];\n timestamp = null;\n } else {\n timestamp = arguments[0];\n options = null;\n }\n }\n }\n\n queryCB = function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, timestamp ? res.result.hits : [res.result]);\n };\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n body = timestamp ? {body: {startTime: timestamp}} : {};\n this.query({controller: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection object.\n * If no index is specified, takes the default index.\n *\n * @param {string} collection - The name of the data collection you want to manipulate\n * @param {string} [index] - The name of the data index containing the data collection\n * @returns {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = function(collection, index) {\n this.isValid();\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Unable to create a new data collection object: no index specified');\n }\n\n index = this.defaultIndex;\n }\n\n if (typeof index !== 'string' || typeof collection !== 'string') {\n throw new Error('Invalid index or collection argument: string expected');\n }\n\n if (!this.collections[index]) {\n this.collections[index] = {};\n }\n\n if (!this.collections[index][collection]) {\n this.collections[index][collection] = new KuzzleDataCollection(this, collection, index);\n }\n\n return this.collections[index][collection];\n};\n\n/**\n * Empties the offline queue without replaying it.\n *\n * @returns {Kuzzle}\n */\nKuzzle.prototype.flushQueue = function () {\n this.offlineQueue = [];\n return this;\n};\n\n/**\n * Returns the list of known persisted data collections.\n *\n * @param {string} [index] - Index containing collections to be listed\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\n\n args.forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.listCollections: index required');\n }\n\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.listCollections', cb);\n\n if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.collections);\n });\n};\n\n/**\n * Returns the list of existing indexes in Kuzzle\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listIndexes = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.listIndexes', cb);\n\n this.query({controller: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.indexes);\n });\n};\n\n/**\n * Disconnects from Kuzzle and invalidate this instance.\n */\nKuzzle.prototype.disconnect = function () {\n var collection;\n\n this.logout();\n\n this.state = 'disconnected';\n this.network.close();\n this.network = null;\n\n for (collection in this.collections) {\n if (this.collections.hasOwnProperty(collection)) {\n delete this.collections[collection];\n }\n }\n};\n\n/**\n * Returns the server informations\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getServerInfo = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getServerInfo', cb);\n\n this.query({controller: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.serverInfo);\n });\n};\n\n/**\n * Forces an index refresh\n *\n * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n * @returns {Kuzzle}\n */\nKuzzle.prototype.refreshIndex = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.refreshIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n this.query({ index: index, controller: 'admin', action: 'refreshIndex'}, {}, options, cb);\n\n return this;\n};\n\n/**\n * Returns de current autoRefresh status for the given index\n *\n * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optinal arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAutoRefresh = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.getAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n this.query({ index: index, controller: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n};\n\n/**\n * (Un)Sets the autoRefresh flag on the given index\n *\n * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n * @param {boolean} autoRefresh - The autoRefresh value to set\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query result\n * @returns {object} this\n */\nKuzzle.prototype.setAutoRefresh = function () {\n var\n index,\n autoRefresh,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'boolean':\n autoRefresh = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.setAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n if (autoRefresh === undefined) {\n throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n }\n\n this.query({ index: index, controller: 'admin', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\n return this;\n};\n\n/**\n * Return the current Kuzzle's UTC Epoch time, in milliseconds\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.now = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.now', cb);\n\n this.query({controller: 'read', action: 'now'}, {}, options, function (err, res) {\n cb(err, res && res.result.now);\n });\n};\n\n/**\n * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n * Base method used to send read queries to Kuzzle\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} queryArgs - Query configuration\n * @param {object} query - The query data\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n var\n attr,\n object = {\n action: queryArgs.action,\n controller: queryArgs.controller,\n metadata: this.metadata\n },\n self = this;\n\n this.isValid();\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n if (options.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\n }\n }\n\n if (!query || typeof query !== 'object' || Array.isArray(query)) {\n throw new Error('Invalid query parameter: ' + query);\n }\n\n if (query.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && query.hasOwnProperty(attr)) {\n object[attr] = query[attr];\n }\n }\n\n object = self.addHeaders(object, this.headers);\n\n /*\n * Do not add the token for the checkToken route, to avoid getting a token error when\n * a developer simply wish to verify his token\n */\n if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n object.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + self.jwtToken;\n }\n\n if (queryArgs.collection) {\n object.collection = queryArgs.collection;\n }\n\n if (queryArgs.index) {\n object.index = queryArgs.index;\n }\n\n if (!object.requestId) {\n object.requestId = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\n if (!self.queueFilter || self.queueFilter(object)) {\n self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n\n return this;\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\n\n return this;\n};\n\n/**\n * Replays the requests queued during offline mode.\n * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n */\nKuzzle.prototype.replayQueue = function () {\n if (this.state !== 'offline' && !this.autoReplay) {\n cleanQueue.call(this);\n dequeue.call(this);\n }\n\n return this;\n};\n\n/**\n * Sets the default Kuzzle index\n *\n * @param index\n * @returns this\n */\nKuzzle.prototype.setDefaultIndex = function (index) {\n if (typeof index !== 'string') {\n throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n }\n\n if (index.length === 0) {\n throw new Error('Cannot set an empty index as the default index');\n }\n\n this.defaultIndex = index;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzle.prototype.setHeaders = function (content, replace) {\n var self = this;\n\n if (typeof content !== 'object' || Array.isArray(content)) {\n throw new Error('Expected a content object, received a ' + typeof content);\n }\n\n if (replace) {\n self.headers = content;\n } else {\n Object.keys(content).forEach(function (key) {\n self.headers[key] = content[key];\n });\n }\n\n return self;\n};\n\n/**\n * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.startQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = true;\n }\n return this;\n};\n\n/**\n * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.stopQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = false;\n }\n\n return this;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\n\n if (!id) {\n throw new Error('A security document must have an id');\n }\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n kuzzle: {\n value: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\n },\n // read-only properties\n // writable properties\n id: {\n value: id,\n enumerable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n }\n });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'update'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {Object} data - New securityDocument content\n * @return {KuzzleSecurityDocument} this\n */\nKuzzleSecurityDocument.prototype.setContent = function (data) {\n this.content = data;\n return this;\n};\n\n/**\n * Serialize this object into a pojo\n *\n * @return {object} pojo representing this securityDocument\n */\nKuzzleSecurityDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n\n return data;\n};\n\n/**\n * Delete the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurityDocument.prototype.delete = function (options, cb) {\n var\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, res.result._id);\n }\n });\n};\n\n/**\n * Update the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} content - Content to add to KuzzleSecurityDocument\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurityDocument} this\n */\nKuzzleSecurityDocument.prototype.update = function (content, options, cb) {\n var\n data = {},\n self = this;\n\n if (typeof content !== 'object') {\n throw new Error('Parameter \"content\" must be a object');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = self.id;\n data.body = content;\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n self.setContent(response.result._source);\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\nmodule.exports = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.setProfiles = function (profileIds) {\n if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n throw new Error('Parameter \"profileIds\" must be an array of strings');\n }\n\n this.content.profileIds = profileIds;\n\n return this;\n};\n\n/**\n * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.addProfile = function (profileId) {\n if (typeof profileId !== 'string') {\n throw new Error('Parameter \"profileId\" must be a string');\n }\n\n if (!this.content.profileIds) {\n this.content.profileIds = [];\n }\n\n if (this.content.profileIds.indexOf(profileId) === -1) {\n this.content.profileIds.push(profileId);\n }\n\n return this;\n};\n\n/**\n * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nKuzzleUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_rng) {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var _rnds = new Array(16);\n _mathRNG = _rng = function() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }\n _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return _rnds;\n };\n if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, bth = _byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n }\n\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || _rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ii++) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ../~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom'),\n KuzzleSubscribeResult = require('./kuzzleSubscribeResult');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n * or like a room for pub/sub messages.\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} collection - name of the data collection to handle\n * @param {string} index - Index containing the data collection\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, collection, index) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\n\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n index: {\n value: index,\n enumerable: true\n },\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (controller, action) {\n return {\n controller: controller,\n action: action,\n collection: this.collection,\n index: this.index\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Executes an advanced search on the data collection.\n *\n * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function.\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'search'), query, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\n });\n};\n\n/**\n * Returns the number of documents matching the provided set of filters.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.count = function (filters, options, cb) {\n var\n query;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n cb(error, result && result.result.count);\n });\n};\n\n/**\n * Create a new empty data collection, with no associated mapping.\n * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n * want to create and prepare data collections before storing documents in it.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.create = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('write', 'createCollection'), data, options, cb);\n\n return this;\n};\n\n/**\n * Create a new document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.createDocument = function (id, document, options, cb) {\n var\n self = this,\n data = {},\n action = 'create';\n\n if (id && typeof id !== 'string') {\n cb = options;\n options = document;\n document = id;\n id = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (document instanceof KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\n }\n\n if (id) {\n data._id = id;\n }\n\n data = self.kuzzle.addHeaders(data, self.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\n doc.version = res.result._version;\n cb(null, doc);\n });\n\n return this;\n};\n\n/**\n * Delete persistent documents.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleDataCollection} this\n */\nKuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) {\n var\n action,\n data = {};\n\n if (typeof arg === 'string') {\n data._id = arg;\n action = 'delete';\n } else {\n data.body = arg;\n action = 'deleteByQuery';\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n if (err) {\n cb(err);\n }\n else {\n cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n }\n });\n\n return this;\n};\n\n/**\n * Retrieve a single stored document using its unique document ID.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n */\nKuzzleDataCollection.prototype.getMapping = function (options, cb) {\n var kuzzleMapping;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('write', 'publish'), data, options, cb);\n\n return this;\n};\n\n/**\n * Replace an existing document with a new one.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to replace\n * @param {object} content - JSON object representing the new document version\n * @param {object} [options] - additional arguments\n * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n var\n self = this,\n data = {\n _id: documentId,\n body: content\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\n};\n\n/**\n * Subscribes to this data collection with a set of filters.\n * To subscribe to the entire data collection, simply provide an empty filter.\n *\n * @param {object} filters - Filters in Kuzzle DSL format\n * @param {object} [options] - subscriptions options\n * @param {responseCallback} cb - called for each new notification\n * @returns {*} KuzzleSubscribeResult object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var\n room,\n subscribeResult;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n subscribeResult = new KuzzleSubscribeResult();\n room = new KuzzleRoom(this, options);\n\n room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\n return subscribeResult;\n};\n\n/**\n * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n * This method is a lot faster than removing all documents using a query.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.truncate = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('admin', 'truncateCollection'), data, options, cb);\n\n return this;\n};\n\n\n/**\n * Update parts of a document\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to update\n * @param {object} content - JSON object containing changes to perform on the document\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n data = {\n _id: documentId,\n body: content\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new KuzzleDocument(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - document id\n * @param {object} content - document content\n * @constructor\n */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [options] - subscription configuration\n * @constructor\n */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [mapping] - mapping to instantiate the KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(this, mapping);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n * the amount of data you stored in a collection and the complexity of your database.\n *\n * The KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n mapping: {\n value: mapping || {},\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['set', 'setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Applies the new mapping to the data collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleDataMapping.prototype.apply = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.collection.buildQueryArgs('admin', 'updateMapping'), data, options, function (err) {\n if (err) {\n return cb && cb(err);\n }\n\n self.refresh(options, cb);\n });\n\n return this;\n};\n\n/**\n * Replaces the current content with the mapping stored in Kuzzle\n *\n * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDataMapping.prototype.refresh = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('admin', 'getMapping'), data, options, function (err, res) {\n if (err) {\n return cb ? cb(err) : false;\n }\n\n if (res.result[self.collection.index]) {\n if (res.result[self.collection.index].mappings[self.collection.collection]) {\n self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\n // Mappings can be empty. The mapping property should never be \"undefined\"\n if (self.mapping === undefined) {\n self.mapping = {};\n }\n } else {\n return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n }\n } else {\n return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n }\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\n\n/**\n * Adds or updates a field mapping.\n *\n * Changes made by this function won’t be applied until you call the apply method\n *\n * @param {string} field - Name of the field from which the mapping is to be added or updated\n * @param {object} mapping - corresponding field mapping\n * @returns {KuzzleDataMapping}\n */\nKuzzleDataMapping.prototype.set = function (field, mapping) {\n this.mapping[field] = mapping;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle handles documents either as realtime messages or as stored documents.\n * KuzzleDocument is the object representation of one of these documents.\n *\n * Notes:\n * - this constructor may be called either with a documentId, a content, neither or both.\n * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n *\n *\n * @param {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n id: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\n }\n });\n\n // handling provided arguments\n if (!content && documentId && typeof documentId === 'object') {\n content = documentId;\n documentId = null;\n }\n\n if (content) {\n if (content._version) {\n this.version = content._version;\n delete content._version;\n }\n this.setContent(content, true);\n }\n\n if (documentId) {\n Object.defineProperty(this, 'id', {\n value: documentId,\n enumerable: true\n });\n }\n\n // promisifying\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'refresh', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this document\n */\nKuzzleDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data._version = this.version;\n data = this.kuzzle.addHeaders(data, this.headers);\n\n return data;\n};\n\n/**\n * Overrides the toString() method in order to return a serialized version of the document\n *\n * @return {string} serialized version of this object\n */\nKuzzleDocument.prototype.toString = function () {\n return JSON.stringify(this.serialize());\n};\n\n/**\n * Deletes this document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.delete = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\n });\n};\n\n/**\n * Replaces the current content with the last version of this document stored in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.refresh = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\n newDocument.version = res.result._version;\n\n cb(null, newDocument);\n });\n};\n\n/**\n * Saves this document into Kuzzle.\n *\n * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n * of this object.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'createOrReplace'), data, options, function (error, res) {\n if (error) {\n return cb && cb(error);\n }\n\n self.id = res.result._id;\n self.version = res.result._version;\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return self;\n};\n\n/**\n * Sends the content of this document as a realtime message.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'publish'), data, options);\n\n return this;\n};\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {object} data - New content\n * @param {boolean} replace - if true: replace this document content with the provided data\n */\nKuzzleDocument.prototype.setContent = function (data, replace) {\n var self = this;\n\n if (replace) {\n this.content = data;\n }\n else {\n Object.keys(data).forEach(function (key) {\n self.content[key] = data[key];\n });\n }\n\n return this;\n};\n\n/**\n * Listens to events concerning this document. Has no effect if the document does not have an ID\n * (i.e. if the document has not yet been created as a persisted document).\n *\n * @param {object} [options] - subscription options\n * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n */\nKuzzleDocument.prototype.subscribe = function (options, cb) {\n var filters;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided');\n }\n\n filters = { ids: { values: [this.id] } };\n\n return this.dataCollection.subscribe(filters, options, cb);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * Kuzzle's memory storage is a separate data store from the database layer.\n * It is internaly based on Redis. You can access most of Redis functions (all\n * lowercased), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(kuzzle) {\n Object.defineProperties(this, {\n // read-only properties\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n this.setHeaders = kuzzle.setHeaders.bind(this);\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.prototype[command] = function () {\n var\n args = Array.prototype.slice.call(arguments),\n options = null,\n cb,\n query = {\n controller: 'ms',\n action: command\n },\n data = {};\n\n if (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n *\n * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n *\n * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n *\n * @param {object} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, options) {\n // Define properties\n Object.defineProperties(this, {\n // private properties\n callback: {\n value: null,\n writable: true\n },\n channel: {\n value: null,\n writable: true\n },\n id: {\n value: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\n value: null,\n writable: true\n },\n queue: {\n value: [],\n writable: true\n },\n // Delay before allowing a subscription renewal\n renewalDelay: {\n value: 500\n },\n scope: {\n value: options && options.scope ? options.scope : 'all'\n },\n state: {\n value: options && options.state ? options.state : 'done'\n },\n subscribing: {\n value: false,\n writable: true\n },\n users: {\n value: options && options.users ? options.users : 'none'\n },\n // read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n filters: {\n value: null,\n enumerable: true,\n writable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\n enumerable: true,\n writable: true\n },\n roomId: {\n value: null,\n enumerable: true,\n writable: true\n },\n subscribeToSelf: {\n value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['count'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Returns the number of other subscriptions on that room.\n *\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.count', cb);\n\n data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\n if (!isReady.call(this)) {\n this.queue.push({action: 'count', args: [cb]});\n return;\n }\n\n if (!this.roomId) {\n throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n cb(err, res && res.result.count);\n });\n};\n\n/**\n * Renew the subscription using new filters\n *\n * @param {object} [filters] - Filters in Kuzzle DSL format\n * @param {responseCallback} notificationCB - called for each new notification\n * @param {responseCallback} [cb] - handles the query response\n */\nKuzzleRoom.prototype.renew = function (filters, notificationCB, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (typeof filters === 'function') {\n cb = notificationCB;\n notificationCB = filters;\n filters = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', notificationCB);\n\n /*\n Skip subscription renewal if another one was performed a moment before\n */\n if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n return;\n }\n\n if (filters) {\n self.filters = filters;\n }\n\n /*\n if not yet connected, register itself to the subscriptions list and wait for the\n main Kuzzle object to renew once online\n */\n if (self.kuzzle.state !== 'connected') {\n self.callback = notificationCB;\n self.kuzzle.subscriptions.pending[self.id] = self;\n return;\n }\n\n if (self.subscribing) {\n self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = notificationCB;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n }\n\n self.lastRenewal = now;\n self.roomId = response.result.roomId;\n self.channel = response.result.channel;\n\n if (!self.kuzzle.subscriptions[self.roomId]) {\n self.kuzzle.subscriptions[self.roomId] = {};\n }\n\n self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\n self.notifier = notificationCallback.bind(self);\n self.kuzzle.network.on(self.channel, self.notifier);\n\n dequeue.call(self);\n cb && cb(null, self);\n });\n};\n\n/**\n * Unsubscribes from Kuzzle.\n *\n * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n * pending subscriptions reaches 0, and only if there is still no listener on that room.\n * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n *\n * @return {*} this\n */\nKuzzleRoom.prototype.unsubscribe = function () {\n var\n self = this,\n room = self.roomId,\n interval;\n\n if (!isReady.call(this)) {\n self.queue.push({action: 'unsubscribe', args: []});\n return self;\n }\n\n if (room) {\n self.kuzzle.network.off(self.channel, this.notifier);\n\n if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n delete self.kuzzle.subscriptions[room];\n\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n } else {\n interval = setInterval(function () {\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n if (!self.kuzzle.subscriptions[room]) {\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n }\n clearInterval(interval);\n }\n }, 100);\n }\n } else {\n delete self.kuzzle.subscriptions[room][self.id];\n }\n\n self.roomId = null;\n }\n\n return self;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleRoom.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n/**\n * Callback called by the network handler when a message is sent to the subscribed room ID\n * Calls the registered callback if the notification passes the subscription filters\n *\n * @param {object} data - data\n * @returns {*}\n */\nfunction notificationCallback (data) {\n if (data.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\n }\n\n if (this.kuzzle.requestHistory[data.requestId]) {\n if (this.subscribeToSelf) {\n this.callback(null, data);\n }\n delete this.kuzzle.requestHistory[data.requestId];\n } else {\n this.callback(null, data);\n }\n}\n\n\n/**\n * Dequeue actions performed while subscription was being renewed\n */\nfunction dequeue () {\n var element;\n\n while (this.queue.length > 0) {\n element = this.queue.shift();\n\n this[element.action].apply(this, element.args);\n }\n}\n\nfunction isReady() {\n return this.kuzzle.state === 'connected' && !this.subscribing;\n}\n\nmodule.exports = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n * Sugar-code handling the result of a KuzzleRoom.renew call\n * @constructor\n */\nfunction KuzzleSubscribeResult() {\n this.cbs = [];\n}\n\n/**\n * Registers a callback to be called with a subscription result\n * @param {Function} cb\n */\nKuzzleSubscribeResult.prototype.onDone = function (cb) {\n this.cbs.push(cb);\n return this;\n};\n\n/**\n * Calls all registered callbacks\n *\n * @param {Object} error object\n * @param {KuzzleRoom} room\n */\nKuzzleSubscribeResult.prototype.done = function (error, room) {\n this.cbs.forEach(function (cb) {\n cb(error, room);\n });\n};\n\nmodule.exports = KuzzleSubscribeResult;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleSubscribeResult.js\n ** module id = 9\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort, sslConnection) {\n // Web browser / NodeJS websocket handling\n if (typeof window !== 'undefined') {\n // use native websockets if the browser supports it\n if (typeof WebSocket !== 'undefined') {\n return new (require('./wrappers/wsbrowsers'))(host, wsPort, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort, sslConnection);\n }\n\n throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n }\n\n return new (require('./wrappers/wsnode'))(host, wsPort, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 10\n ** module chunks = 0\n **/","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\n });\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n this.socket.on('connect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n this.socket.on('connect_error', callback);\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.socket.on('disconnect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n this.socket.on('reconnect', callback);\n };\n\n /**\n * Registers a callback on a room. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.once = function (roomId, callback) {\n this.socket.once(roomId, callback);\n };\n\n /**\n * Registers a callback on a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.on = function (roomId, callback) {\n this.socket.on(roomId, callback);\n };\n\n /**\n * Unregisters a callback from a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.off = function (roomId, callback) {\n this.socket.off(roomId, callback);\n };\n\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n this.socket.emit('kuzzle', payload);\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 11\n ** module chunks = 0\n **/","function WSBrowsers(host, port, ssl) {\n var self = this;\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n * @returns {Object} Socket\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function (code, message) {\n if (code === 1000) {\n poke(self.listeners, 'disconnect');\n }\n else {\n onClientError.call(self, autoReconnect, reconnectionDelay, message);\n }\n };\n\n this.client.onerror = function (error) {\n onClientError.call(self, autoReconnect, reconnectionDelay, error);\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, data);\n }\n };\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n this.listeners.connect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n this.listeners.reconnect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Registers a callback on a room. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.once = function (roomId, callback) {\n if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\n };\n\n /**\n * Registers a callback on a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.on = function (roomId, callback) {\n if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Unregisters a callback from a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.off = function (roomId, callback) {\n var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\n\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n if (this.client && this.client.readyState === this.client.OPEN) {\n this.client.send(JSON.stringify(payload));\n }\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\n/**\n * Called when the connection closes with an error state\n *\n * @param {boolean} autoReconnect\n * @param {number} reconnectionDelay\n * @param {string|Object} message\n */\nfunction onClientError(autoReconnect, reconnectionDelay, message) {\n var self = this;\n\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error', message);\n}\n\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 12\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteProfile'\n },\n updateActionName: {\n value: 'updateProfile'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['hydrate', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\n }\n});\n\n/**\n * Persist to the persistent layer the current profile\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.save = function (options, cb) {\n var\n data,\n self = this;\n\n if (!this.content.policies) {\n throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.serialize();\n\n self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n\n/**\n * Add a policy in the policies list\n * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n *\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.addPolicy = function (policy) {\n\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n }\n\n if (!this.content.policies) {\n this.content.policies = [];\n }\n\n this.content.policies.push(policy);\n\n return this;\n};\n\n/**\n * Set policies list\n * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.setPolicies = function (policies) {\n\n if (!Array.isArray(policies)) {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n\n policies.map(function (policy) {\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n });\n\n this.content.policies = policies;\n\n return this;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this securityDocument\n */\nKuzzleProfile.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n\n return data;\n};\n\n/**\n * Returns the list of policies associated to this profile.\n * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @return {object} an array of policies\n */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 13\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteRole'\n },\n updateActionName: {\n value: 'updateRole'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\n }\n});\n\n/**\n * Saves this role into Kuzzle.\n *\n * If this is a new role, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n * of this object.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleRole} this object\n */\nKuzzleRole.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 14\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(kuzzle) {\n\n Object.defineProperty(this, 'kuzzle', {\n value: kuzzle\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (action) {\n return {\n controller: 'security',\n action: action\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['roleFactory', 'profileFactory', 'userFactory', 'isActionAllowed'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * Retrieve a single Role using its unique role ID.\n *\n * @param {string} id\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on roles according to a filter\n *\n * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a role that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.prototype.searchRoles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchRoles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = result.result.hits.map(function (doc) {\n return new KuzzleRole(self, doc._id, doc._source);\n });\n\n cb(null, { total: result.result.total, roles: documents });\n });\n};\n\n/**\n * Create a new role in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same role already exists: throw an error if sets to false.\n * Replace the existing role otherwise\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createRole = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createRole: cannot create a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleRole(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a role in Kuzzle.\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateRole: cannot update a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err) {\n cb(err, err ? undefined : new KuzzleRole(self, id, content));\n });\n\n return this;\n};\n\n/**\n * Delete role.\n *\n * There is a small delay between role deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a role that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Role id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteRole = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleRole object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - role id\n * @param {object} content - role content\n * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on profiles according to a filter\n *\n *\n * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.searchProfiles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\n });\n};\n\n/**\n * Create a new profile in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same profile already exists: throw an error if sets to false.\n * Replace the existing profile otherwise\n *\n * @param {string} id - profile identifier\n * @param {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createProfile: cannot create a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleProfile(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateProfile: cannot update a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n var updatedContent = {};\n\n if (err) {\n return cb(err);\n }\n\n Object.keys(res.result._source).forEach(function (property) {\n updatedContent[property] = res.result._source[property];\n });\n\n cb(null, new KuzzleProfile(self, res.result._id, updatedContent));\n });\n\n return this;\n};\n\n/**\n * Delete profile.\n *\n * There is a small delay between profile deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteProfile = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleProfile object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - profile id\n * @param {object} content - profile content\n * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n var\n data = {_id: id},\n self = this;\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for getUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on user according to a filter\n *\n * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a user that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - same filters as documents filters\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.searchUsers = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateUser: cannot update an user without an user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n });\n\n return this;\n};\n\n/**\n * Delete user.\n *\n * There is a small delay between user deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a user that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteUser = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleUser object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - user id\n * @param {object} content - user content\n * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\n};\n\n/**\n * Tells whether an action is allowed, denied or conditional based on the rights\n * rights provided as the first argument. An action is defined as a couple of\n * action and controller (mandatory), plus an index and a collection(optional).\n *\n * @param {object} rights - The rights rights associated to a user\n * (see getMyrights and getUserrights).\n * @param {string} controller - The controller to check the action onto.\n * @param {string} action - The action to perform.\n * @param {string} index - (optional) The name of index to perform the action onto.\n * @param {string} collection - (optional) The name of the collection to perform the action onto.\n *\n * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n * correspond to rights containing closures.\n * See also http://kuzzle.io/guide/#roles-definition\n */\nKuzzleSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n var filteredRights;\n\n if (!rights || typeof rights !== 'object') {\n throw new Error('rights parameter is mandatory for isActionAllowed function');\n }\n if (!controller || typeof controller !== 'string') {\n throw new Error('controller parameter is mandatory for isActionAllowed function');\n }\n if (!action || typeof action !== 'string') {\n throw new Error('action parameter is mandatory for isActionAllowed function');\n }\n\n // We filter in all the rights that match the request (including wildcards).\n filteredRights = rights\n .filter(function (right) {\n return right.controller === controller || right.controller === '*';\n })\n .filter(function (right) {\n return right.action === action || right.action === '*';\n })\n .filter(function (right) {\n return right.index === index || right.index === '*';\n })\n .filter(function (right) {\n return right.collection === collection || right.collection === '*';\n });\n\n // Then, if at least one right allows the action, we return 'allowed'\n if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n return 'allowed';\n }\n // If no right allows the action, we check for conditionals.\n if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n return 'conditional';\n }\n // Otherwise we return 'denied'.\n return 'denied';\n};\n\n\n/**\n * Gets the rights array of a given user.\n *\n * @param {string} userId The id of the user.\n * @param {object} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.prototype.getUserRights = function (userId, options, cb) {\n var\n data = {_id: userId},\n self = this;\n\n if (!userId || typeof userId !== 'string') {\n throw new Error('userId parameter is mandatory for getUserRights function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\n this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 15\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap 479b7a96b704e843870d","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///./~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/kuzzleSubscribeResult.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","error","action","message","Error","assign","status","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","removeAllSubscriptions","unsubscribe","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","queryError","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","disconnect","onConnect","onConnectError","connectionError","internal","onDisconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","unsetJwtToken","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","KuzzleSubscribeResult","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","subscribeResult","done","bind","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","onDoneCB","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","notificationCB","subscribeQuery","on","interval","off","setInterval","clearInterval","cbs","onDone","WebSocket","io","code","SocketIO","port","ssl","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onClientError","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId"],"mappings":"CAAA,SAAAA,EAAAC,GACA,mBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,QACA,sBAAAG,gBAAAC,IACAD,UAAAH,OACA,CACA,GAAAK,GAAAL,GACA,QAAAM,KAAAD,IAAA,gBAAAJ,iBAAAF,GAAAO,GAAAD,EAAAC,KAECC,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAT,OAGA,IAAAC,GAAAS,EAAAD,IACAT,WACAW,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAZ,EAAAD,QAAAC,IAAAD,QAAAQ,GAGAP,EAAAW,QAAA,EAGAX,EAAAD,QAvBA,GAAAU,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,GAGAR,EAAA,KDgBM,SAASP,EAAQD,EAASQ,GEolBhC,QAAAS,KACA,GACAC,GAAAZ,KACAa,EAAAC,KAAAD,MACAE,IAEAH,GAAAI,SAAA,IACAJ,EAAAK,aAAAC,QAAA,SAAAC,EAAAC,GACAD,EAAAE,GAAAR,EAAAD,EAAAI,WACAD,EAAAK,KAIAL,QACAH,EAAAK,aACAK,OAAA,EAAAP,EAAA,GACAG,QAAA,SAAAK,GACAX,EAAAY,UAAA,kBAAAD,EA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A,GACA,SAAAE,OAAA,6DAmBA,OAfAqf,GAAAD,EACAne,OAAA,SAAAqe,GACA,MAAAA,GAAApe,gBAAA,MAAAoe,EAAApe,aAEAD,OAAA,SAAAqe,GACA,MAAAA,GAAAxf,YAAA,MAAAwf,EAAAxf,SAEAmB,OAAA,SAAAqe,GACA,MAAAA,GAAA/gB,WAAA,MAAA+gB,EAAA/gB,QAEA0C,OAAA,SAAAqe,GACA,MAAAA,GAAAhW,gBAAA,MAAAgW,EAAAhW,aAIA+V,EAAAE,KAAA,SAAAC,GAA2C,kBAAAA,EAAAhd,QAC3C,UAGA6c,EAAAE,KAAA,SAAAC,GAA2C,sBAAAA,EAAAhd,QAC3C,cAGA,UAWAT,EAAA+C,UAAA2a,cAAA,SAAAC,EAAArd,EAAA/C,GACA,GACAiJ,IAAYN,IAAAyX,GACZ3hB,EAAAZ,IAEA,KAAAuiB,GAAA,gBAAAA,GACA,SAAA1f,OAAA,2DAGAV,IAAA,kBAAA+C,KACA/C,EAAA+C,EACAA,EAAA,MAGAtE,EAAAsN,OAAAvD,iBAAA,uBAAAxI,GAEAnC,KAAAkO,OAAA/M,MAAAnB,KAAAqO,eAAA,iBAAAjD,EAAAlG,EAAA/C,GAAA,SAAAoH,EAAAC,GACArH,EAAAoH,IAAAnH,OAAAoH,EAAAK,OAAAoB,SAIAtL,EAAAD,QAAAkF","file":"kuzzle.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\n **/","(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(15),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(10);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle object constructor.\n\t *\n\t * @constructor\n\t * @param host - Server name or IP Address to the Kuzzle instance\n\t * @param [options] - Connection options\n\t * @param {responseCallback} [cb] - Handles connection response\n\t * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (host, options, cb) {\n\t var self = this;\n\t\n\t if (!(this instanceof Kuzzle)) {\n\t return new Kuzzle(host, options, cb);\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!host || host === '') {\n\t throw new Error('host argument missing');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // 'private' properties\n\t collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []},\n\t queryError: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\n\t },\n\t queuing: {\n\t value: false,\n\t writable: true\n\t },\n\t requestHistory: {\n\t value: {},\n\t writable: true\n\t },\n\t state: {\n\t value: 'initializing',\n\t writable: true\n\t },\n\t subscriptions: {\n\t /*\n\t Contains the centralized subscription list in the following format:\n\t pending: \n\t 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: kuzzleRoomInstance_...\n\t }\n\t\n\t This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n\t This structure also allows renewing subscriptions after a connection loss\n\t */\n\t value: {\n\t pending: {}\n\t },\n\t writable: true\n\t },\n\t // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n\t enumerable: true\n\t },\n\t defaultIndex: {\n\t value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n\t writable: true,\n\t enumerable: true\n\t },\n\t reconnectionDelay: {\n\t value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n\t enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t writable: true,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true,\n\t writable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n\t enumerable: true,\n\t writable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n\t enumerable: true\n\t },\n\t autoQueue: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoReplay: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoResubscribe: {\n\t value: true,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t /*\n\t Offline queue use the following format:\n\t [\n\t {\n\t ts: ,\n\t query: 'query',\n\t cb: callbackFunction\n\t }\n\t ]\n\t */\n\t offlineQueue: {\n\t value: [],\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueFilter: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueMaxSize: {\n\t value: 500,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueTTL: {\n\t value: 120000,\n\t enumerable: true,\n\t writable: true\n\t },\n\t replayInterval: {\n\t value: 10,\n\t enumerable: true,\n\t writable: true\n\t },\n\t jwtToken: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t offlineQueueLoader: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (options) {\n\t Object.keys(options).forEach(function (opt) {\n\t if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n\t self[opt] = options[opt];\n\t }\n\t });\n\t\n\t if (options.offlineMode === 'auto' && this.autoReconnect) {\n\t this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n\t }\n\t }\n\t\n\t // Helper function ensuring that this Kuzzle object is still valid before performing a query\n\t Object.defineProperty(this, 'isValid', {\n\t value: function () {\n\t if (self.state === 'disconnected') {\n\t throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n\t }\n\t }\n\t });\n\t\n\t // Helper function copying headers to the query data\n\t Object.defineProperty(this, 'addHeaders', {\n\t value: function (query, headers) {\n\t Object.keys(headers).forEach(function (header) {\n\t if (!query[header]) {\n\t query[header] = headers[header];\n\t }\n\t });\n\t\n\t return query;\n\t }\n\t });\n\t\n\t /**\n\t * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n\t * and is called by these methods\n\t */\n\t Object.defineProperty(this, 'callbackRequired', {\n\t value: function (errorMessagePrefix, callback) {\n\t if (!callback || typeof callback !== 'function') {\n\t throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * Create an attribute security that embed all methods to manage Role, Profile and User\n\t */\n\t Object.defineProperty(this, 'security', {\n\t value: new KuzzleSecurity(this),\n\t enumerable: true\n\t });\n\t\n\t /**\n\t * Emit an event to all registered listeners\n\t * An event cannot be emitted multiple times before a timeout has been reached.\n\t */\n\t Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\n\t\n\t\n\t if (!options || !options.connect || options.connect === 'auto') {\n\t this.connect();\n\t } else {\n\t this.state = 'ready';\n\t }\n\t\n\t cleanHistory(this.requestHistory);\n\t\n\t if (this.bluebird) {\n\t return this.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n\t 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n\t 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n\t ];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t};\n\t\n\t/**\n\t * Connects to a Kuzzle instance using the provided host name.\n\t * @returns {Object} this\n\t */\n\tKuzzle.prototype.connect = function () {\n\t var self = this;\n\t\n\t if (self.network) {\n\t self.disconnect();\n\t }\n\t\n\t self.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\t\n\t if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t return self;\n\t }\n\t\n\t self.state = 'connecting';\n\t self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\t\n\t self.network.onConnect(function () {\n\t self.state = 'connected';\n\t renewAllSubscriptions.call(self);\n\t dequeue.call(self);\n\t self.emitEvent('connected');\n\t\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t });\n\t\n\t self.network.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\n\t\n\t if (self.connectCB) {\n\t self.connectCB(connectionError);\n\t }\n\t });\n\t\n\t self.network.onDisconnect(function () {\n\t self.state = 'offline';\n\t\n\t if (!self.autoReconnect) {\n\t self.disconnect();\n\t }\n\t\n\t if (self.autoQueue) {\n\t self.queuing = true;\n\t }\n\t\n\t self.emitEvent('disconnected');\n\t });\n\t\n\t self.network.onReconnect(function () {\n\t var reconnect = function () {\n\t // renew subscriptions\n\t if (self.autoResubscribe) {\n\t renewAllSubscriptions.call(self);\n\t }\n\t\n\t // replay queued requests\n\t if (self.autoReplay) {\n\t cleanQueue.call(self);\n\t dequeue.call(self);\n\t }\n\t\n\t // alert listeners\n\t self.emitEvent('reconnected');\n\t };\n\t\n\t self.state = 'connected';\n\t\n\t if (self.jwtToken) {\n\t self.checkToken(self.jwtToken, function (err, res) {\n\t // shouldn't obtain an error but let's invalidate the token anyway\n\t if (err || !res.valid) {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired');\n\t }\n\t\n\t reconnect();\n\t });\n\t } else {\n\t reconnect();\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the jwtToken used to query kuzzle\n\t * @param token\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.setJwtToken = function(token) {\n\t if (typeof token === 'string') {\n\t this.jwtToken = token;\n\t } else if (typeof token === 'object') {\n\t if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n\t this.jwtToken = token.result.jwt;\n\t } else {\n\t this.emitEvent('loginAttempt', {\n\t success: false,\n\t error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n\t });\n\t\n\t return this;\n\t }\n\t } else {\n\t this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n\t return this;\n\t }\n\t\n\t renewAllSubscriptions.call(this);\n\t this.emitEvent('loginAttempt', {success: true});\n\t return this;\n\t};\n\t\n\t/**\n\t * Unset the jwtToken used to query kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.unsetJwtToken = function() {\n\t this.jwtToken = undefined;\n\t\n\t removeAllSubscriptions.call(this);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Get the jwtToken used by kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.getJwtToken = function() {\n\t return this.jwtToken;\n\t};\n\t\n\t/**\n\t * Send login request to kuzzle with credentials\n\t * If login success, store the jwtToken into kuzzle object\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param expiresIn\n\t * @param cb\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = arguments[1];\n\t } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n\t request.expiresIn = arguments[1];\n\t } else if (typeof arguments[1] === 'function') {\n\t cb = arguments[1];\n\t }\n\t }\n\t if (arguments[2]) {\n\t if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n\t request.expiresIn = arguments[2];\n\t } else if (typeof arguments[2] === 'function') {\n\t cb = arguments[2];\n\t }\n\t }\n\t if (arguments[3] && typeof arguments[3] === 'function') {\n\t cb = arguments[3];\n\t }\n\t\n\t if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, function(error, response) {\n\t if (!error) {\n\t if (response.result.jwt) {\n\t self.setJwtToken(response.result.jwt);\n\t }\n\t\n\t cb && cb(null, response.result);\n\t }\n\t else {\n\t cb && cb(error);\n\t self.emitEvent('loginAttempt', {success: false, error: error.message});\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Send logout request to kuzzle with jwtToken.\n\t *\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.logout = function (cb) {\n\t var\n\t self = this,\n\t request = {\n\t action: 'logout',\n\t controller: 'auth',\n\t requestId: uuid.v4(),\n\t body: {}\n\t };\n\t\n\t this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n\t if (error === null) {\n\t self.unsetJwtToken();\n\t cb(null, self);\n\t }\n\t else {\n\t cb(error);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Checks whether a given jwt token still represents a valid session in Kuzzle.\n\t *\n\t * @param {string} token The jwt token to check\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\n\t var\n\t request = {\n\t body: {\n\t token: token\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.checkToken', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Gets the rights array of the currently logged user.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzle.prototype.getMyRights = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.callbackRequired('Kuzzle.getMyRights', cb);\n\t\n\t self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Update current user in Kuzzle.\n\t *\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.updateSelf = function (content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t queryArgs = {controller: 'auth', action: 'updateSelf'};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data.body = content;\n\t\n\t self.query(queryArgs, data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n\t */\n\tfunction cleanQueue () {\n\t var\n\t self = this,\n\t now = Date.now(),\n\t lastDocumentIndex = -1;\n\t\n\t if (self.queueTTL > 0) {\n\t self.offlineQueue.forEach(function (query, index) {\n\t if (query.ts < now - self.queueTTL) {\n\t lastDocumentIndex = index;\n\t }\n\t });\n\t\n\t if (lastDocumentIndex !== -1) {\n\t self.offlineQueue\n\t .splice(0, lastDocumentIndex + 1)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t }\n\t\n\t if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n\t self.offlineQueue\n\t .splice(0, self.offlineQueue.length - self.queueMaxSize)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Clean history from requests made more than 10s ago\n\t */\n\tfunction cleanHistory (requestHistory) {\n\t var\n\t now = Date.now();\n\t\n\t Object.keys(requestHistory).forEach(function (key) {\n\t if (requestHistory[key] < now - 10000) {\n\t delete requestHistory[key];\n\t }\n\t });\n\t\n\t setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\n\t}\n\t\n\t/**\n\t * Emit a request to Kuzzle\n\t *\n\t * @param {object} request\n\t * @param {responseCallback} [cb]\n\t */\n\tfunction emitRequest (request, cb) {\n\t var\n\t self = this;\n\t\n\t if (self.jwtToken !== undefined || cb) {\n\t self.network.once(request.requestId, function (response) {\n\t var error = null;\n\t\n\t if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t if (response.error) {\n\t error = new Error(response.error.message);\n\t Object.assign(error, response.error);\n\t error.status = response.status;\n\t self.emitEvent('queryError', error, request, cb);\n\t }\n\t\n\t if (cb) {\n\t cb(error, response);\n\t }\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow KuzzleRoom.subscribeToSelf to work\n\t self.requestHistory[request.requestId] = Date.now();\n\t}\n\t\n\t/**\n\t * Play all queued requests, in order.\n\t */\n\tfunction dequeue () {\n\t var\n\t self = this,\n\t additionalQueue,\n\t uniqueQueue = {},\n\t dequeuingProcess = function () {\n\t if (self.offlineQueue.length > 0) {\n\t emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n\t self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\t\n\t setTimeout(function () {\n\t dequeuingProcess();\n\t }, Math.max(0, self.replayInterval));\n\t } else {\n\t self.queuing = false;\n\t }\n\t };\n\t\n\t if (self.offlineQueueLoader) {\n\t if (typeof self.offlineQueueLoader !== 'function') {\n\t throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n\t }\n\t\n\t additionalQueue = self.offlineQueueLoader();\n\t if (Array.isArray(additionalQueue)) {\n\t self.offlineQueue = additionalQueue\n\t .concat(self.offlineQueue)\n\t .filter(function (request) {\n\t // throws if the query object does not contain required attributes\n\t if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n\t throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n\t }\n\t\n\t return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n\t });\n\t } else {\n\t throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n\t }\n\t }\n\t\n\t dequeuingProcess();\n\t}\n\t\n\t/**\n\t * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n\t * successful login attempt\n\t */\n\tfunction renewAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.renew(subscription.callback);\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n\t */\n\tfunction removeAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.unsubscribe();\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n\t * insertion.\n\t *\n\t * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t if (listenerType !== 'function') {\n\t throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n\t }\n\t\n\t listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\n\t\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method returns all available statistics from Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAllStatistics = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\t\n\t this.query({controller:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n\t *\n\t * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n\t var\n\t queryCB,\n\t body;\n\t\n\t if (!cb) {\n\t if (arguments.length === 1) {\n\t cb = arguments[0];\n\t options = null;\n\t timestamp = null;\n\t } else {\n\t cb = arguments[1];\n\t if (typeof arguments[0] === 'object') {\n\t options = arguments[0];\n\t timestamp = null;\n\t } else {\n\t timestamp = arguments[0];\n\t options = null;\n\t }\n\t }\n\t }\n\t\n\t queryCB = function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, timestamp ? res.result.hits : [res.result]);\n\t };\n\t\n\t this.callbackRequired('Kuzzle.getStatistics', cb);\n\t\n\t body = timestamp ? {body: {startTime: timestamp}} : {};\n\t this.query({controller: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection object.\n\t * If no index is specified, takes the default index.\n\t *\n\t * @param {string} collection - The name of the data collection you want to manipulate\n\t * @param {string} [index] - The name of the data index containing the data collection\n\t * @returns {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = function(collection, index) {\n\t this.isValid();\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Unable to create a new data collection object: no index specified');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (typeof index !== 'string' || typeof collection !== 'string') {\n\t throw new Error('Invalid index or collection argument: string expected');\n\t }\n\t\n\t if (!this.collections[index]) {\n\t this.collections[index] = {};\n\t }\n\t\n\t if (!this.collections[index][collection]) {\n\t this.collections[index][collection] = new KuzzleDataCollection(this, collection, index);\n\t }\n\t\n\t return this.collections[index][collection];\n\t};\n\t\n\t/**\n\t * Empties the offline queue without replaying it.\n\t *\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.flushQueue = function () {\n\t this.offlineQueue = [];\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns the list of known persisted data collections.\n\t *\n\t * @param {string} [index] - Index containing collections to be listed\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\n\t\n\t args.forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.listCollections: index required');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listCollections', cb);\n\t\n\t if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.collections);\n\t });\n\t};\n\t\n\t/**\n\t * Returns the list of existing indexes in Kuzzle\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listIndexes = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listIndexes', cb);\n\t\n\t this.query({controller: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.indexes);\n\t });\n\t};\n\t\n\t/**\n\t * Disconnects from Kuzzle and invalidate this instance.\n\t */\n\tKuzzle.prototype.disconnect = function () {\n\t var collection;\n\t\n\t this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\n\t this.network = null;\n\t\n\t for (collection in this.collections) {\n\t if (this.collections.hasOwnProperty(collection)) {\n\t delete this.collections[collection];\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Returns the server informations\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getServerInfo = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getServerInfo', cb);\n\t\n\t this.query({controller: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.serverInfo);\n\t });\n\t};\n\t\n\t/**\n\t * Forces an index refresh\n\t *\n\t * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.refreshIndex = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.refreshIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.query({ index: index, controller: 'admin', action: 'refreshIndex'}, {}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns de current autoRefresh status for the given index\n\t *\n\t * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optinal arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAutoRefresh = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.getAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n\t this.query({ index: index, controller: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n\t};\n\t\n\t/**\n\t * (Un)Sets the autoRefresh flag on the given index\n\t *\n\t * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n\t * @param {boolean} autoRefresh - The autoRefresh value to set\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query result\n\t * @returns {object} this\n\t */\n\tKuzzle.prototype.setAutoRefresh = function () {\n\t var\n\t index,\n\t autoRefresh,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'boolean':\n\t autoRefresh = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.setAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (autoRefresh === undefined) {\n\t throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n\t }\n\t\n\t this.query({ index: index, controller: 'admin', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Return the current Kuzzle's UTC Epoch time, in milliseconds\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.now = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.now', cb);\n\t\n\t this.query({controller: 'read', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, res && res.result.now);\n\t });\n\t};\n\t\n\t/**\n\t * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n\t * Base method used to send read queries to Kuzzle\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} queryArgs - Query configuration\n\t * @param {object} query - The query data\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n\t var\n\t attr,\n\t object = {\n\t action: queryArgs.action,\n\t controller: queryArgs.controller,\n\t metadata: this.metadata\n\t },\n\t self = this;\n\t\n\t this.isValid();\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t if (options.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\n\t }\n\t }\n\t\n\t if (!query || typeof query !== 'object' || Array.isArray(query)) {\n\t throw new Error('Invalid query parameter: ' + query);\n\t }\n\t\n\t if (query.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && query.hasOwnProperty(attr)) {\n\t object[attr] = query[attr];\n\t }\n\t }\n\t\n\t object = self.addHeaders(object, this.headers);\n\t\n\t /*\n\t * Do not add the token for the checkToken route, to avoid getting a token error when\n\t * a developer simply wish to verify his token\n\t */\n\t if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n\t object.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + self.jwtToken;\n\t }\n\t\n\t if (queryArgs.collection) {\n\t object.collection = queryArgs.collection;\n\t }\n\t\n\t if (queryArgs.index) {\n\t object.index = queryArgs.index;\n\t }\n\t\n\t if (!object.requestId) {\n\t object.requestId = uuid.v4();\n\t }\n\t\n\t if (self.state === 'connected' || (options && options.queuable === false)) {\n\t if (self.state === 'connected') {\n\t emitRequest.call(this, object, cb);\n\t } else if (cb) {\n\t cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n\t }\n\t } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\n\t if (!self.queueFilter || self.queueFilter(object)) {\n\t self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n\t self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n\t }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replays the requests queued during offline mode.\n\t * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n\t */\n\tKuzzle.prototype.replayQueue = function () {\n\t if (this.state !== 'offline' && !this.autoReplay) {\n\t cleanQueue.call(this);\n\t dequeue.call(this);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Sets the default Kuzzle index\n\t *\n\t * @param index\n\t * @returns this\n\t */\n\tKuzzle.prototype.setDefaultIndex = function (index) {\n\t if (typeof index !== 'string') {\n\t throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n\t }\n\t\n\t if (index.length === 0) {\n\t throw new Error('Cannot set an empty index as the default index');\n\t }\n\t\n\t this.defaultIndex = index;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzle.prototype.setHeaders = function (content, replace) {\n\t var self = this;\n\t\n\t if (typeof content !== 'object' || Array.isArray(content)) {\n\t throw new Error('Expected a content object, received a ' + typeof content);\n\t }\n\t\n\t if (replace) {\n\t self.headers = content;\n\t } else {\n\t Object.keys(content).forEach(function (key) {\n\t self.headers[key] = content[key];\n\t });\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.startQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = true;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.stopQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = false;\n\t }\n\t\n\t return this;\n\t};\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\n\t\n\t if (!id) {\n\t throw new Error('A security document must have an id');\n\t }\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t kuzzle: {\n\t value: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\n\t },\n\t // read-only properties\n\t // writable properties\n\t id: {\n\t value: id,\n\t enumerable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'update'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {Object} data - New securityDocument content\n\t * @return {KuzzleSecurityDocument} this\n\t */\n\tKuzzleSecurityDocument.prototype.setContent = function (data) {\n\t this.content = data;\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a pojo\n\t *\n\t * @return {object} pojo representing this securityDocument\n\t */\n\tKuzzleSecurityDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Delete the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurityDocument.prototype.delete = function (options, cb) {\n\t var\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t if (cb) {\n\t cb(null, res.result._id);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Update the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} content - Content to add to KuzzleSecurityDocument\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurityDocument} this\n\t */\n\tKuzzleSecurityDocument.prototype.update = function (content, options, cb) {\n\t var\n\t data = {},\n\t self = this;\n\t\n\t if (typeof content !== 'object') {\n\t throw new Error('Parameter \"content\" must be a object');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = self.id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t self.setContent(response.result._source);\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteUser'\n\t },\n\t updateActionName: {\n\t value: 'updateUser'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.setProfiles = function (profileIds) {\n\t if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n\t throw new Error('Parameter \"profileIds\" must be an array of strings');\n\t }\n\t\n\t this.content.profileIds = profileIds;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.addProfile = function (profileId) {\n\t if (typeof profileId !== 'string') {\n\t throw new Error('Parameter \"profileId\" must be a string');\n\t }\n\t\n\t if (!this.content.profileIds) {\n\t this.content.profileIds = [];\n\t }\n\t\n\t if (this.content.profileIds.indexOf(profileId) === -1) {\n\t this.content.profileIds.push(profileId);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tKuzzleUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content};\n\t};\n\t\n\t/**\n\t * Return the associated profiles IDs\n\t *\n\t * @return {array} the associated profiles IDs\n\t */\n\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_rng) {\n\t // Math.random()-based (RNG)\n\t //\n\t // If all else fails, use Math.random(). It's fast, but is of unspecified\n\t // quality.\n\t var _rnds = new Array(16);\n\t _mathRNG = _rng = function() {\n\t for (var i = 0, r; i < 16; i++) {\n\t if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }\n\t _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n\t }\n\t\n\t return _rnds;\n\t };\n\t if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, bth = _byteToHex;\n\t return bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]];\n\t }\n\t\n\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(16) : null;\n\t options = null;\n\t }\n\t options = options || {};\n\t\n\t var rnds = options.random || (options.rng || _rng)();\n\t\n\t // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\t rnds[6] = (rnds[6] & 0x0f) | 0x40;\n\t rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\t\n\t // Copy bytes to buffer, if provided\n\t if (buf) {\n\t for (var ii = 0; ii < 16; ii++) {\n\t buf[i + ii] = rnds[ii];\n\t }\n\t }\n\t\n\t return buf || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8),\n\t KuzzleSubscribeResult = __webpack_require__(9);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n\t * or like a room for pub/sub messages.\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} collection - name of the data collection to handle\n\t * @param {string} index - Index containing the data collection\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, collection, index) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t index: {\n\t value: index,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (controller, action) {\n\t return {\n\t controller: controller,\n\t action: action,\n\t collection: this.collection,\n\t index: this.index\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Executes an advanced search on the data collection.\n\t *\n\t * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function.\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n\t var\n\t query,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', 'search'), query, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Returns the number of documents matching the provided set of filters.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.count = function (filters, options, cb) {\n\t var\n\t query;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t cb(error, result && result.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Create a new empty data collection, with no associated mapping.\n\t * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n\t * want to create and prepare data collections before storing documents in it.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.create = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('write', 'createCollection'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Create a new document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument object, or a document\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.createDocument = function (id, document, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'create';\n\t\n\t if (id && typeof id !== 'string') {\n\t cb = options;\n\t options = document;\n\t document = id;\n\t id = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (document instanceof KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\n\t }\n\t\n\t if (id) {\n\t data._id = id;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, self.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n\t var doc;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t doc = new KuzzleDocument(self, res.result._id, res.result._source);\n\t doc.version = res.result._version;\n\t cb(null, doc);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete persistent documents.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleDataCollection} this\n\t */\n\tKuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) {\n\t var\n\t action,\n\t data = {};\n\t\n\t if (typeof arg === 'string') {\n\t data._id = arg;\n\t action = 'delete';\n\t } else {\n\t data.body = arg;\n\t action = 'deleteByQuery';\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieve a single stored document using its unique document ID.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n\t */\n\tKuzzleDataCollection.prototype.getMapping = function (options, cb) {\n\t var kuzzleMapping;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\n\t};\n\t\n\t/**\n\t * Publish a realtime message\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument instance or a JSON object\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('write', 'publish'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replace an existing document with a new one.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to replace\n\t * @param {object} content - JSON object representing the new document version\n\t * @param {object} [options] - additional arguments\n\t * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n\t var\n\t self = this,\n\t data = {\n\t _id: documentId,\n\t body: content\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, cb && function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Subscribes to this data collection with a set of filters.\n\t * To subscribe to the entire data collection, simply provide an empty filter.\n\t *\n\t * @param {object} filters - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscriptions options\n\t * @param {responseCallback} cb - called for each new notification\n\t * @returns {*} KuzzleSubscribeResult object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var\n\t room,\n\t subscribeResult;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\t\n\t subscribeResult = new KuzzleSubscribeResult();\n\t room = new KuzzleRoom(this, options);\n\t\n\t room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\t\n\t return subscribeResult;\n\t};\n\t\n\t/**\n\t * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n\t * This method is a lot faster than removing all documents using a query.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tKuzzleDataCollection.prototype.truncate = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('admin', 'truncateCollection'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Update parts of a document\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to update\n\t * @param {object} content - JSON object containing changes to perform on the document\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t data = {\n\t _id: documentId,\n\t body: content\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new KuzzleDocument(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - document id\n\t * @param {object} content - document content\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [options] - subscription configuration\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [mapping] - mapping to instantiate the KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(this, mapping);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n\t * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n\t * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n\t * the amount of data you stored in a collection and the complexity of your database.\n\t *\n\t * The KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t mapping: {\n\t value: mapping || {},\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['set', 'setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Applies the new mapping to the data collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleDataMapping.prototype.apply = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.collection.buildQueryArgs('admin', 'updateMapping'), data, options, function (err) {\n\t if (err) {\n\t return cb && cb(err);\n\t }\n\t\n\t self.refresh(options, cb);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with the mapping stored in Kuzzle\n\t *\n\t * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDataMapping.prototype.refresh = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('admin', 'getMapping'), data, options, function (err, res) {\n\t if (err) {\n\t return cb ? cb(err) : false;\n\t }\n\t\n\t if (res.result[self.collection.index]) {\n\t if (res.result[self.collection.index].mappings[self.collection.collection]) {\n\t self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\t\n\t // Mappings can be empty. The mapping property should never be \"undefined\"\n\t if (self.mapping === undefined) {\n\t self.mapping = {};\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n\t }\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Adds or updates a field mapping.\n\t *\n\t * Changes made by this function won’t be applied until you call the apply method\n\t *\n\t * @param {string} field - Name of the field from which the mapping is to be added or updated\n\t * @param {object} mapping - corresponding field mapping\n\t * @returns {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.prototype.set = function (field, mapping) {\n\t this.mapping[field] = mapping;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle handles documents either as realtime messages or as stored documents.\n\t * KuzzleDocument is the object representation of one of these documents.\n\t *\n\t * Notes:\n\t * - this constructor may be called either with a documentId, a content, neither or both.\n\t * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n\t *\n\t *\n\t * @param {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n\t * @param {string} [documentId] - ID of an existing document\n\t * @param {object} [content] - Initializes this document with the provided content\n\t * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t id: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t version: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t // handling provided arguments\n\t if (!content && documentId && typeof documentId === 'object') {\n\t content = documentId;\n\t documentId = null;\n\t }\n\t\n\t if (content) {\n\t if (content._version) {\n\t this.version = content._version;\n\t delete content._version;\n\t }\n\t this.setContent(content, true);\n\t }\n\t\n\t if (documentId) {\n\t Object.defineProperty(this, 'id', {\n\t value: documentId,\n\t enumerable: true\n\t });\n\t }\n\t\n\t // promisifying\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'refresh', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this document\n\t */\n\tKuzzleDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data._version = this.version;\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Overrides the toString() method in order to return a serialized version of the document\n\t *\n\t * @return {string} serialized version of this object\n\t */\n\tKuzzleDocument.prototype.toString = function () {\n\t return JSON.stringify(this.serialize());\n\t};\n\t\n\t/**\n\t * Deletes this document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.delete = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n\t cb(err, err ? undefined : self.id);\n\t });\n\t};\n\t\n\t/**\n\t * Replaces the current content with the last version of this document stored in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.refresh = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n\t var newDocument;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\n\t newDocument.version = res.result._version;\n\t\n\t cb(null, newDocument);\n\t });\n\t};\n\t\n\t/**\n\t * Saves this document into Kuzzle.\n\t *\n\t * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n\t * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'createOrReplace'), data, options, function (error, res) {\n\t if (error) {\n\t return cb && cb(error);\n\t }\n\t\n\t self.id = res.result._id;\n\t self.version = res.result._version;\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Sends the content of this document as a realtime message.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'publish'), data, options);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {object} data - New content\n\t * @param {boolean} replace - if true: replace this document content with the provided data\n\t */\n\tKuzzleDocument.prototype.setContent = function (data, replace) {\n\t var self = this;\n\t\n\t if (replace) {\n\t this.content = data;\n\t }\n\t else {\n\t Object.keys(data).forEach(function (key) {\n\t self.content[key] = data[key];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Listens to events concerning this document. Has no effect if the document does not have an ID\n\t * (i.e. if the document has not yet been created as a persisted document).\n\t *\n\t * @param {object} [options] - subscription options\n\t * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n\t */\n\tKuzzleDocument.prototype.subscribe = function (options, cb) {\n\t var filters;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided');\n\t }\n\t\n\t filters = { ids: { values: [this.id] } };\n\t\n\t return this.dataCollection.subscribe(filters, options, cb);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleDocument.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t\n\tmodule.exports = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\n/***/ function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * Kuzzle's memory storage is a separate data store from the database layer.\n\t * It is internaly based on Redis. You can access most of Redis functions (all\n\t * lowercased), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(kuzzle) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t this.setHeaders = kuzzle.setHeaders.bind(this);\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.prototype[command] = function () {\n\t var\n\t args = Array.prototype.slice.call(arguments),\n\t options = null,\n\t cb,\n\t query = {\n\t controller: 'ms',\n\t action: command\n\t },\n\t data = {};\n\t\n\t if (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n\t *\n\t * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n\t *\n\t * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n\t * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n\t * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n\t *\n\t * @param {object} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, options) {\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t callback: {\n\t value: null,\n\t writable: true\n\t },\n\t channel: {\n\t value: null,\n\t writable: true\n\t },\n\t id: {\n\t value: uuid.v4()\n\t },\n\t lastRenewal: {\n\t value: null,\n\t writable: true\n\t },\n\t notifier: {\n\t value: null,\n\t writable: true\n\t },\n\t onDoneCB: {\n\t value: null,\n\t writable: true\n\t },\n\t queue: {\n\t value: [],\n\t writable: true\n\t },\n\t // Delay before allowing a subscription renewal\n\t renewalDelay: {\n\t value: 500\n\t },\n\t scope: {\n\t value: options && options.scope ? options.scope : 'all'\n\t },\n\t state: {\n\t value: options && options.state ? options.state : 'done'\n\t },\n\t subscribing: {\n\t value: false,\n\t writable: true\n\t },\n\t users: {\n\t value: options && options.users ? options.users : 'none'\n\t },\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t filters: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t roomId: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t subscribeToSelf: {\n\t value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['count'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Returns the number of other subscriptions on that room.\n\t *\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.count', cb);\n\t\n\t data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\t\n\t if (!isReady.call(this)) {\n\t this.queue.push({action: 'count', args: [cb]});\n\t return;\n\t }\n\t\n\t if (!this.roomId) {\n\t throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n\t cb(err, res && res.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Renew the subscription using new filters\n\t *\n\t * @param {object} [filters] - Filters in Kuzzle DSL format\n\t * @param {responseCallback} notificationCB - called for each new notification\n\t * @param {responseCallback} [cb] - handles the query response\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, notificationCB, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (typeof filters === 'function') {\n\t cb = notificationCB;\n\t notificationCB = filters;\n\t filters = null;\n\t }\n\t\n\t if (!cb) {\n\t cb = self.onDoneCB;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', notificationCB);\n\t\n\t /*\n\t Skip subscription renewal if another one was performed a moment before\n\t */\n\t if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n\t return cb && cb(new Error('Subscription already renewed less than ' + self.renewalDelay + 'ms ago'));\n\t }\n\t\n\t if (filters) {\n\t self.filters = filters;\n\t }\n\t\n\t /*\n\t if not yet connected, register itself to the subscriptions list and wait for the\n\t main Kuzzle object to renew once online\n\t */\n\t if (self.kuzzle.state !== 'connected') {\n\t self.callback = notificationCB;\n\t self.onDoneCB = cb;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t return;\n\t }\n\t\n\t if (self.subscribing) {\n\t self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n\t return;\n\t }\n\t\n\t self.unsubscribe();\n\t self.roomId = null;\n\t self.subscribing = true;\n\t self.callback = notificationCB;\n\t self.onDoneCB = cb;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t\n\t subscribeQuery.body = self.filters;\n\t subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n\t delete self.kuzzle.subscriptions.pending[self.id];\n\t self.subscribing = false;\n\t\n\t if (error) {\n\t self.queue = [];\n\t return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n\t }\n\t\n\t self.lastRenewal = now;\n\t self.roomId = response.result.roomId;\n\t self.channel = response.result.channel;\n\t\n\t if (!self.kuzzle.subscriptions[self.roomId]) {\n\t self.kuzzle.subscriptions[self.roomId] = {};\n\t }\n\t\n\t self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\t\n\t self.notifier = notificationCallback.bind(self);\n\t self.kuzzle.network.on(self.channel, self.notifier);\n\t\n\t dequeue.call(self);\n\t cb && cb(null, self);\n\t });\n\t};\n\t\n\t/**\n\t * Unsubscribes from Kuzzle.\n\t *\n\t * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n\t * pending subscriptions reaches 0, and only if there is still no listener on that room.\n\t * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n\t *\n\t * @return {*} this\n\t */\n\tKuzzleRoom.prototype.unsubscribe = function () {\n\t var\n\t self = this,\n\t room = self.roomId,\n\t interval;\n\t\n\t if (!isReady.call(this)) {\n\t self.queue.push({action: 'unsubscribe', args: []});\n\t return self;\n\t }\n\t\n\t if (room) {\n\t self.kuzzle.network.off(self.channel, this.notifier);\n\t\n\t if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n\t delete self.kuzzle.subscriptions[room];\n\t\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n\t } else {\n\t interval = setInterval(function () {\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t if (!self.kuzzle.subscriptions[room]) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n\t }\n\t clearInterval(interval);\n\t }\n\t }, 100);\n\t }\n\t } else {\n\t delete self.kuzzle.subscriptions[room][self.id];\n\t }\n\t\n\t self.roomId = null;\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzleRoom.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t/**\n\t * Callback called by the network handler when a message is sent to the subscribed room ID\n\t * Calls the registered callback if the notification passes the subscription filters\n\t *\n\t * @param {object} data - data\n\t * @returns {*}\n\t */\n\tfunction notificationCallback (data) {\n\t if (data.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\n\t }\n\t\n\t if (this.kuzzle.requestHistory[data.requestId]) {\n\t if (this.subscribeToSelf) {\n\t this.callback(null, data);\n\t }\n\t delete this.kuzzle.requestHistory[data.requestId];\n\t } else {\n\t this.callback(null, data);\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Dequeue actions performed while subscription was being renewed\n\t */\n\tfunction dequeue () {\n\t var element;\n\t\n\t while (this.queue.length > 0) {\n\t element = this.queue.shift();\n\t\n\t this[element.action].apply(this, element.args);\n\t }\n\t}\n\t\n\tfunction isReady() {\n\t return this.kuzzle.state === 'connected' && !this.subscribing;\n\t}\n\t\n\tmodule.exports = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports) {\n\n\t/**\n\t * Sugar-code handling the result of a KuzzleRoom.renew call\n\t * @constructor\n\t */\n\tfunction KuzzleSubscribeResult() {\n\t this.cbs = [];\n\t}\n\t\n\t/**\n\t * Registers a callback to be called with a subscription result\n\t * @param {Function} cb\n\t */\n\tKuzzleSubscribeResult.prototype.onDone = function (cb) {\n\t this.cbs.push(cb);\n\t return this;\n\t};\n\t\n\t/**\n\t * Calls all registered callbacks\n\t *\n\t * @param {Object} error object\n\t * @param {KuzzleRoom} room\n\t */\n\tKuzzleSubscribeResult.prototype.done = function (error, room) {\n\t this.cbs.forEach(function (cb) {\n\t cb(error, room);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSubscribeResult;\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort, sslConnection) {\n\t // Web browser / NodeJS websocket handling\n\t if (typeof window !== 'undefined') {\n\t // use native websockets if the browser supports it\n\t if (typeof WebSocket !== 'undefined') {\n\t return new (__webpack_require__(12))(host, wsPort, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(11))(host, ioPort, sslConnection);\n\t }\n\t\n\t throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n\t }\n\t\n\t return new (__webpack_require__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction SocketIO(host, port, ssl) {\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.socket = null;\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n\t reconnection: autoReconnect,\n\t reconnectionDelay: reconnectionDelay,\n\t forceNew: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t this.socket.on('connect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t this.socket.on('connect_error', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t this.socket.on('disconnect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t this.socket.on('reconnect', callback);\n\t };\n\t\n\t /**\n\t * Registers a callback on a room. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.once = function (roomId, callback) {\n\t this.socket.once(roomId, callback);\n\t };\n\t\n\t /**\n\t * Registers a callback on a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.on = function (roomId, callback) {\n\t this.socket.on(roomId, callback);\n\t };\n\t\n\t /**\n\t * Unregisters a callback from a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.off = function (roomId, callback) {\n\t this.socket.off(roomId, callback);\n\t };\n\t\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t this.socket.emit('kuzzle', payload);\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port, ssl) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t * @returns {Object} Socket\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function (code, message) {\n\t if (code === 1000) {\n\t poke(self.listeners, 'disconnect');\n\t }\n\t else {\n\t onClientError.call(self, autoReconnect, reconnectionDelay, message);\n\t }\n\t };\n\t\n\t this.client.onerror = function (error) {\n\t onClientError.call(self, autoReconnect, reconnectionDelay, error);\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, data);\n\t }\n\t };\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t this.listeners.connect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t this.listeners.error.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Registers a callback on a room. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.once = function (roomId, callback) {\n\t if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\n\t };\n\t\n\t /**\n\t * Registers a callback on a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.on = function (roomId, callback) {\n\t if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\n\t };\n\t\n\t /**\n\t * Unregisters a callback from a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.off = function (roomId, callback) {\n\t var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\n\t }\n\t };\n\t\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t if (this.client && this.client.readyState === this.client.OPEN) {\n\t this.client.send(JSON.stringify(payload));\n\t }\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * Called when the connection closes with an error state\n\t *\n\t * @param {boolean} autoReconnect\n\t * @param {number} reconnectionDelay\n\t * @param {string|Object} message\n\t */\n\tfunction onClientError(autoReconnect, reconnectionDelay, message) {\n\t var self = this;\n\t\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error', message);\n\t}\n\t\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteProfile'\n\t },\n\t updateActionName: {\n\t value: 'updateProfile'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['hydrate', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\n\t }\n\t});\n\t\n\t/**\n\t * Persist to the persistent layer the current profile\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.save = function (options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!this.content.policies) {\n\t throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.serialize();\n\t\n\t self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Add a policy in the policies list\n\t * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n\t *\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.addPolicy = function (policy) {\n\t\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n\t }\n\t\n\t if (!this.content.policies) {\n\t this.content.policies = [];\n\t }\n\t\n\t this.content.policies.push(policy);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set policies list\n\t * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @returns {KuzzleProfile} this\n\t */\n\tKuzzleProfile.prototype.setPolicies = function (policies) {\n\t\n\t if (!Array.isArray(policies)) {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t\n\t policies.map(function (policy) {\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t });\n\t\n\t this.content.policies = policies;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this securityDocument\n\t */\n\tKuzzleProfile.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Returns the list of policies associated to this profile.\n\t * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @return {object} an array of policies\n\t */\n\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteRole'\n\t },\n\t updateActionName: {\n\t value: 'updateRole'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\n\t }\n\t});\n\t\n\t/**\n\t * Saves this role into Kuzzle.\n\t *\n\t * If this is a new role, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleRole} this object\n\t */\n\tKuzzleRole.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleRole;\n\n/***/ },\n/* 15 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(14),\n\t KuzzleProfile = __webpack_require__(13),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(kuzzle) {\n\t\n\t Object.defineProperty(this, 'kuzzle', {\n\t value: kuzzle\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (action) {\n\t return {\n\t controller: 'security',\n\t action: action\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['roleFactory', 'profileFactory', 'userFactory', 'isActionAllowed'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * Retrieve a single Role using its unique role ID.\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!id) {\n\t throw new Error('Id parameter is mandatory for getRole function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on roles according to a filter\n\t *\n\t * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.prototype.searchRoles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchRoles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = result.result.hits.map(function (doc) {\n\t return new KuzzleRole(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: result.result.total, roles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new role in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same role already exists: throw an error if sets to false.\n\t * Replace the existing role otherwise\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createRole: cannot create a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleRole(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a role in Kuzzle.\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateRole: cannot update a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err) {\n\t cb(err, err ? undefined : new KuzzleRole(self, id, content));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete role.\n\t *\n\t * There is a small delay between role deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Role id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteRole = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRole object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - role id\n\t * @param {object} content - role content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\n\t};\n\t\n\t\n\t/**\n\t * Get a specific profile from kuzzle\n\t *\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on profiles according to a filter\n\t *\n\t *\n\t * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.searchProfiles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new profile in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same profile already exists: throw an error if sets to false.\n\t * Replace the existing profile otherwise\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createProfile: cannot create a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleProfile(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a profile in Kuzzle.\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateProfile: cannot update a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t var updatedContent = {};\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t Object.keys(res.result._source).forEach(function (property) {\n\t updatedContent[property] = res.result._source[property];\n\t });\n\t\n\t cb(null, new KuzzleProfile(self, res.result._id, updatedContent));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete profile.\n\t *\n\t * There is a small delay between profile deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteProfile = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleProfile object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - profile id\n\t * @param {object} content - profile content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\n\t};\n\t\n\t/**\n\t * Get a specific user from kuzzle using its unique ID\n\t *\n\t * @param {string} id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n\t var\n\t data = {_id: id},\n\t self = this;\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for getUser function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on user according to a filter\n\t *\n\t * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - same filters as documents filters\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.searchUsers = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profile` in `content` must only contains the profile id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.updateUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.updateUser: cannot update an user without an user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete user.\n\t *\n\t * There is a small delay between user deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {KuzzleSecurity} this object\n\t */\n\tKuzzleSecurity.prototype.deleteUser = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleUser object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - user id\n\t * @param {object} content - user content\n\t * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\n\t};\n\t\n\t/**\n\t * Tells whether an action is allowed, denied or conditional based on the rights\n\t * rights provided as the first argument. An action is defined as a couple of\n\t * action and controller (mandatory), plus an index and a collection(optional).\n\t *\n\t * @param {object} rights - The rights rights associated to a user\n\t * (see getMyrights and getUserrights).\n\t * @param {string} controller - The controller to check the action onto.\n\t * @param {string} action - The action to perform.\n\t * @param {string} index - (optional) The name of index to perform the action onto.\n\t * @param {string} collection - (optional) The name of the collection to perform the action onto.\n\t *\n\t * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n\t * correspond to rights containing closures.\n\t * See also http://kuzzle.io/guide/#roles-definition\n\t */\n\tKuzzleSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n\t var filteredRights;\n\t\n\t if (!rights || typeof rights !== 'object') {\n\t throw new Error('rights parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!controller || typeof controller !== 'string') {\n\t throw new Error('controller parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!action || typeof action !== 'string') {\n\t throw new Error('action parameter is mandatory for isActionAllowed function');\n\t }\n\t\n\t // We filter in all the rights that match the request (including wildcards).\n\t filteredRights = rights\n\t .filter(function (right) {\n\t return right.controller === controller || right.controller === '*';\n\t })\n\t .filter(function (right) {\n\t return right.action === action || right.action === '*';\n\t })\n\t .filter(function (right) {\n\t return right.index === index || right.index === '*';\n\t })\n\t .filter(function (right) {\n\t return right.collection === collection || right.collection === '*';\n\t });\n\t\n\t // Then, if at least one right allows the action, we return 'allowed'\n\t if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n\t return 'allowed';\n\t }\n\t // If no right allows the action, we check for conditionals.\n\t if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n\t return 'conditional';\n\t }\n\t // Otherwise we return 'denied'.\n\t return 'denied';\n\t};\n\t\n\t\n\t/**\n\t * Gets the rights array of a given user.\n\t *\n\t * @param {string} userId The id of the user.\n\t * @param {object} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.prototype.getUserRights = function (userId, options, cb) {\n\t var\n\t data = {_id: userId},\n\t self = this;\n\t\n\t if (!userId || typeof userId !== 'string') {\n\t throw new Error('userId parameter is mandatory for getUserRights function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap 479b7a96b704e843870d\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\n networkWrapper = require('./networkWrapper');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle object constructor.\n *\n * @constructor\n * @param host - Server name or IP Address to the Kuzzle instance\n * @param [options] - Connection options\n * @param {responseCallback} [cb] - Handles connection response\n * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!host || host === '') {\n throw new Error('host argument missing');\n }\n\n Object.defineProperties(this, {\n // 'private' properties\n collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []},\n queryError: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\n },\n queuing: {\n value: false,\n writable: true\n },\n requestHistory: {\n value: {},\n writable: true\n },\n state: {\n value: 'initializing',\n writable: true\n },\n subscriptions: {\n /*\n Contains the centralized subscription list in the following format:\n pending: \n 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: kuzzleRoomInstance_...\n }\n\n This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n This structure also allows renewing subscriptions after a connection loss\n */\n value: {\n pending: {}\n },\n writable: true\n },\n // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n enumerable: true\n },\n defaultIndex: {\n value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n writable: true,\n enumerable: true\n },\n reconnectionDelay: {\n value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n enumerable: true\n },\n host: {\n value: host,\n writable: true,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true,\n writable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n enumerable: true,\n writable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n enumerable: true\n },\n autoQueue: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoReplay: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoResubscribe: {\n value: true,\n enumerable: true,\n writable: true\n },\n headers: {\n value: {},\n enumerable: true,\n writable: true\n },\n metadata: {\n value: {},\n enumerable: true,\n writable: true\n },\n /*\n Offline queue use the following format:\n [\n {\n ts: ,\n query: 'query',\n cb: callbackFunction\n }\n ]\n */\n offlineQueue: {\n value: [],\n enumerable: true,\n writable: true\n },\n queueFilter: {\n value: null,\n enumerable: true,\n writable: true\n },\n queueMaxSize: {\n value: 500,\n enumerable: true,\n writable: true\n },\n queueTTL: {\n value: 120000,\n enumerable: true,\n writable: true\n },\n replayInterval: {\n value: 10,\n enumerable: true,\n writable: true\n },\n jwtToken: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n offlineQueueLoader: {\n value: null,\n enumerable: true,\n writable: true\n }\n });\n\n if (options) {\n Object.keys(options).forEach(function (opt) {\n if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n self[opt] = options[opt];\n }\n });\n\n if (options.offlineMode === 'auto' && this.autoReconnect) {\n this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n }\n }\n\n // Helper function ensuring that this Kuzzle object is still valid before performing a query\n Object.defineProperty(this, 'isValid', {\n value: function () {\n if (self.state === 'disconnected') {\n throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n }\n }\n });\n\n // Helper function copying headers to the query data\n Object.defineProperty(this, 'addHeaders', {\n value: function (query, headers) {\n Object.keys(headers).forEach(function (header) {\n if (!query[header]) {\n query[header] = headers[header];\n }\n });\n\n return query;\n }\n });\n\n /**\n * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n * and is called by these methods\n */\n Object.defineProperty(this, 'callbackRequired', {\n value: function (errorMessagePrefix, callback) {\n if (!callback || typeof callback !== 'function') {\n throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n }\n }\n });\n\n /**\n * Create an attribute security that embed all methods to manage Role, Profile and User\n */\n Object.defineProperty(this, 'security', {\n value: new KuzzleSecurity(this),\n enumerable: true\n });\n\n /**\n * Emit an event to all registered listeners\n * An event cannot be emitted multiple times before a timeout has been reached.\n */\n Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\n\n if (this.bluebird) {\n return this.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\n\n/**\n * Connects to a Kuzzle instance using the provided host name.\n * @returns {Object} this\n */\nKuzzle.prototype.connect = function () {\n var self = this;\n\n if (self.network) {\n self.disconnect();\n }\n\n self.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\n if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n return self;\n }\n\n self.state = 'connecting';\n self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\n self.network.onConnect(function () {\n self.state = 'connected';\n renewAllSubscriptions.call(self);\n dequeue.call(self);\n self.emitEvent('connected');\n\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n });\n\n self.network.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\n\n if (self.connectCB) {\n self.connectCB(connectionError);\n }\n });\n\n self.network.onDisconnect(function () {\n self.state = 'offline';\n\n if (!self.autoReconnect) {\n self.disconnect();\n }\n\n if (self.autoQueue) {\n self.queuing = true;\n }\n\n self.emitEvent('disconnected');\n });\n\n self.network.onReconnect(function () {\n var reconnect = function () {\n // renew subscriptions\n if (self.autoResubscribe) {\n renewAllSubscriptions.call(self);\n }\n\n // replay queued requests\n if (self.autoReplay) {\n cleanQueue.call(self);\n dequeue.call(self);\n }\n\n // alert listeners\n self.emitEvent('reconnected');\n };\n\n self.state = 'connected';\n\n if (self.jwtToken) {\n self.checkToken(self.jwtToken, function (err, res) {\n // shouldn't obtain an error but let's invalidate the token anyway\n if (err || !res.valid) {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired');\n }\n\n reconnect();\n });\n } else {\n reconnect();\n }\n });\n\n return this;\n};\n\n/**\n * Set the jwtToken used to query kuzzle\n * @param token\n * @returns {Kuzzle}\n */\nKuzzle.prototype.setJwtToken = function(token) {\n if (typeof token === 'string') {\n this.jwtToken = token;\n } else if (typeof token === 'object') {\n if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n this.jwtToken = token.result.jwt;\n } else {\n this.emitEvent('loginAttempt', {\n success: false,\n error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n });\n\n return this;\n }\n } else {\n this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n return this;\n }\n\n renewAllSubscriptions.call(this);\n this.emitEvent('loginAttempt', {success: true});\n return this;\n};\n\n/**\n * Unset the jwtToken used to query kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.unsetJwtToken = function() {\n this.jwtToken = undefined;\n\n removeAllSubscriptions.call(this);\n\n return this;\n};\n\n/**\n * Get the jwtToken used by kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.getJwtToken = function() {\n return this.jwtToken;\n};\n\n/**\n * Send login request to kuzzle with credentials\n * If login success, store the jwtToken into kuzzle object\n *\n * @param strategy\n * @param credentials\n * @param expiresIn\n * @param cb\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = arguments[1];\n } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n request.expiresIn = arguments[1];\n } else if (typeof arguments[1] === 'function') {\n cb = arguments[1];\n }\n }\n if (arguments[2]) {\n if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n request.expiresIn = arguments[2];\n } else if (typeof arguments[2] === 'function') {\n cb = arguments[2];\n }\n }\n if (arguments[3] && typeof arguments[3] === 'function') {\n cb = arguments[3];\n }\n\n if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, function(error, response) {\n if (!error) {\n if (response.result.jwt) {\n self.setJwtToken(response.result.jwt);\n }\n\n cb && cb(null, response.result);\n }\n else {\n cb && cb(error);\n self.emitEvent('loginAttempt', {success: false, error: error.message});\n }\n });\n};\n\n/**\n * Send logout request to kuzzle with jwtToken.\n *\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.logout = function (cb) {\n var\n self = this,\n request = {\n action: 'logout',\n controller: 'auth',\n requestId: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n if (error === null) {\n self.unsetJwtToken();\n cb(null, self);\n }\n else {\n cb(error);\n }\n });\n\n return self;\n};\n\n/**\n * Checks whether a given jwt token still represents a valid session in Kuzzle.\n *\n * @param {string} token The jwt token to check\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n });\n};\n\n/**\n * Gets the rights array of the currently logged user.\n *\n * @param {object} [options] - Optional parameters\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzle.prototype.getMyRights = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.callbackRequired('Kuzzle.getMyRights', cb);\n\n self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n};\n\n/**\n * Update current user in Kuzzle.\n *\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.updateSelf = function (content, options, cb) {\n var\n self = this,\n data = {},\n queryArgs = {controller: 'auth', action: 'updateSelf'};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data.body = content;\n\n self.query(queryArgs, data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return this;\n};\n\n/**\n * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n */\nfunction cleanQueue () {\n var\n self = this,\n now = Date.now(),\n lastDocumentIndex = -1;\n\n if (self.queueTTL > 0) {\n self.offlineQueue.forEach(function (query, index) {\n if (query.ts < now - self.queueTTL) {\n lastDocumentIndex = index;\n }\n });\n\n if (lastDocumentIndex !== -1) {\n self.offlineQueue\n .splice(0, lastDocumentIndex + 1)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n }\n\n if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n self.offlineQueue\n .splice(0, self.offlineQueue.length - self.queueMaxSize)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n}\n\n\n/**\n * Clean history from requests made more than 10s ago\n */\nfunction cleanHistory (requestHistory) {\n var\n now = Date.now();\n\n Object.keys(requestHistory).forEach(function (key) {\n if (requestHistory[key] < now - 10000) {\n delete requestHistory[key];\n }\n });\n\n setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\n}\n\n/**\n * Emit a request to Kuzzle\n *\n * @param {object} request\n * @param {responseCallback} [cb]\n */\nfunction emitRequest (request, cb) {\n var\n self = this;\n\n if (self.jwtToken !== undefined || cb) {\n self.network.once(request.requestId, function (response) {\n var error = null;\n\n if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n if (response.error) {\n error = new Error(response.error.message);\n Object.assign(error, response.error);\n error.status = response.status;\n self.emitEvent('queryError', error, request, cb);\n }\n\n if (cb) {\n cb(error, response);\n }\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.subscribeToSelf to work\n self.requestHistory[request.requestId] = Date.now();\n}\n\n/**\n * Play all queued requests, in order.\n */\nfunction dequeue () {\n var\n self = this,\n additionalQueue,\n uniqueQueue = {},\n dequeuingProcess = function () {\n if (self.offlineQueue.length > 0) {\n emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\n setTimeout(function () {\n dequeuingProcess();\n }, Math.max(0, self.replayInterval));\n } else {\n self.queuing = false;\n }\n };\n\n if (self.offlineQueueLoader) {\n if (typeof self.offlineQueueLoader !== 'function') {\n throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n }\n\n additionalQueue = self.offlineQueueLoader();\n if (Array.isArray(additionalQueue)) {\n self.offlineQueue = additionalQueue\n .concat(self.offlineQueue)\n .filter(function (request) {\n // throws if the query object does not contain required attributes\n if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n }\n\n return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n });\n } else {\n throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n }\n }\n\n dequeuingProcess();\n}\n\n/**\n * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n * successful login attempt\n */\nfunction renewAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.renew(subscription.callback);\n });\n });\n}\n\n/**\n * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n */\nfunction removeAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.unsubscribe();\n });\n });\n}\n\n/**\n * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n * insertion.\n *\n * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\n\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method returns all available statistics from Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAllStatistics = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\n this.query({controller:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n};\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n *\n * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n var\n queryCB,\n body;\n\n if (!cb) {\n if (arguments.length === 1) {\n cb = arguments[0];\n options = null;\n timestamp = null;\n } else {\n cb = arguments[1];\n if (typeof arguments[0] === 'object') {\n options = arguments[0];\n timestamp = null;\n } else {\n timestamp = arguments[0];\n options = null;\n }\n }\n }\n\n queryCB = function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, timestamp ? res.result.hits : [res.result]);\n };\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n body = timestamp ? {body: {startTime: timestamp}} : {};\n this.query({controller: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection object.\n * If no index is specified, takes the default index.\n *\n * @param {string} collection - The name of the data collection you want to manipulate\n * @param {string} [index] - The name of the data index containing the data collection\n * @returns {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = function(collection, index) {\n this.isValid();\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Unable to create a new data collection object: no index specified');\n }\n\n index = this.defaultIndex;\n }\n\n if (typeof index !== 'string' || typeof collection !== 'string') {\n throw new Error('Invalid index or collection argument: string expected');\n }\n\n if (!this.collections[index]) {\n this.collections[index] = {};\n }\n\n if (!this.collections[index][collection]) {\n this.collections[index][collection] = new KuzzleDataCollection(this, collection, index);\n }\n\n return this.collections[index][collection];\n};\n\n/**\n * Empties the offline queue without replaying it.\n *\n * @returns {Kuzzle}\n */\nKuzzle.prototype.flushQueue = function () {\n this.offlineQueue = [];\n return this;\n};\n\n/**\n * Returns the list of known persisted data collections.\n *\n * @param {string} [index] - Index containing collections to be listed\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\n\n args.forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.listCollections: index required');\n }\n\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.listCollections', cb);\n\n if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.collections);\n });\n};\n\n/**\n * Returns the list of existing indexes in Kuzzle\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listIndexes = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.listIndexes', cb);\n\n this.query({controller: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.indexes);\n });\n};\n\n/**\n * Disconnects from Kuzzle and invalidate this instance.\n */\nKuzzle.prototype.disconnect = function () {\n var collection;\n\n this.logout();\n\n this.state = 'disconnected';\n this.network.close();\n this.network = null;\n\n for (collection in this.collections) {\n if (this.collections.hasOwnProperty(collection)) {\n delete this.collections[collection];\n }\n }\n};\n\n/**\n * Returns the server informations\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getServerInfo = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getServerInfo', cb);\n\n this.query({controller: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.serverInfo);\n });\n};\n\n/**\n * Forces an index refresh\n *\n * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n * @returns {Kuzzle}\n */\nKuzzle.prototype.refreshIndex = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.refreshIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n this.query({ index: index, controller: 'admin', action: 'refreshIndex'}, {}, options, cb);\n\n return this;\n};\n\n/**\n * Returns de current autoRefresh status for the given index\n *\n * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optinal arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAutoRefresh = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.getAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n this.query({ index: index, controller: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n};\n\n/**\n * (Un)Sets the autoRefresh flag on the given index\n *\n * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n * @param {boolean} autoRefresh - The autoRefresh value to set\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query result\n * @returns {object} this\n */\nKuzzle.prototype.setAutoRefresh = function () {\n var\n index,\n autoRefresh,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'boolean':\n autoRefresh = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.setAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n if (autoRefresh === undefined) {\n throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n }\n\n this.query({ index: index, controller: 'admin', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\n return this;\n};\n\n/**\n * Return the current Kuzzle's UTC Epoch time, in milliseconds\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.now = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.now', cb);\n\n this.query({controller: 'read', action: 'now'}, {}, options, function (err, res) {\n cb(err, res && res.result.now);\n });\n};\n\n/**\n * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n * Base method used to send read queries to Kuzzle\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} queryArgs - Query configuration\n * @param {object} query - The query data\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n var\n attr,\n object = {\n action: queryArgs.action,\n controller: queryArgs.controller,\n metadata: this.metadata\n },\n self = this;\n\n this.isValid();\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n if (options.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\n }\n }\n\n if (!query || typeof query !== 'object' || Array.isArray(query)) {\n throw new Error('Invalid query parameter: ' + query);\n }\n\n if (query.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && query.hasOwnProperty(attr)) {\n object[attr] = query[attr];\n }\n }\n\n object = self.addHeaders(object, this.headers);\n\n /*\n * Do not add the token for the checkToken route, to avoid getting a token error when\n * a developer simply wish to verify his token\n */\n if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n object.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + self.jwtToken;\n }\n\n if (queryArgs.collection) {\n object.collection = queryArgs.collection;\n }\n\n if (queryArgs.index) {\n object.index = queryArgs.index;\n }\n\n if (!object.requestId) {\n object.requestId = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\n if (!self.queueFilter || self.queueFilter(object)) {\n self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n\n return this;\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\n\n return this;\n};\n\n/**\n * Replays the requests queued during offline mode.\n * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n */\nKuzzle.prototype.replayQueue = function () {\n if (this.state !== 'offline' && !this.autoReplay) {\n cleanQueue.call(this);\n dequeue.call(this);\n }\n\n return this;\n};\n\n/**\n * Sets the default Kuzzle index\n *\n * @param index\n * @returns this\n */\nKuzzle.prototype.setDefaultIndex = function (index) {\n if (typeof index !== 'string') {\n throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n }\n\n if (index.length === 0) {\n throw new Error('Cannot set an empty index as the default index');\n }\n\n this.defaultIndex = index;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzle.prototype.setHeaders = function (content, replace) {\n var self = this;\n\n if (typeof content !== 'object' || Array.isArray(content)) {\n throw new Error('Expected a content object, received a ' + typeof content);\n }\n\n if (replace) {\n self.headers = content;\n } else {\n Object.keys(content).forEach(function (key) {\n self.headers[key] = content[key];\n });\n }\n\n return self;\n};\n\n/**\n * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.startQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = true;\n }\n return this;\n};\n\n/**\n * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.stopQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = false;\n }\n\n return this;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\n\n if (!id) {\n throw new Error('A security document must have an id');\n }\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n kuzzle: {\n value: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\n },\n // read-only properties\n // writable properties\n id: {\n value: id,\n enumerable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n }\n });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'update'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {Object} data - New securityDocument content\n * @return {KuzzleSecurityDocument} this\n */\nKuzzleSecurityDocument.prototype.setContent = function (data) {\n this.content = data;\n return this;\n};\n\n/**\n * Serialize this object into a pojo\n *\n * @return {object} pojo representing this securityDocument\n */\nKuzzleSecurityDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n\n return data;\n};\n\n/**\n * Delete the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurityDocument.prototype.delete = function (options, cb) {\n var\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, res.result._id);\n }\n });\n};\n\n/**\n * Update the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} content - Content to add to KuzzleSecurityDocument\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurityDocument} this\n */\nKuzzleSecurityDocument.prototype.update = function (content, options, cb) {\n var\n data = {},\n self = this;\n\n if (typeof content !== 'object') {\n throw new Error('Parameter \"content\" must be a object');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = self.id;\n data.body = content;\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n self.setContent(response.result._source);\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\nmodule.exports = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.setProfiles = function (profileIds) {\n if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n throw new Error('Parameter \"profileIds\" must be an array of strings');\n }\n\n this.content.profileIds = profileIds;\n\n return this;\n};\n\n/**\n * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.addProfile = function (profileId) {\n if (typeof profileId !== 'string') {\n throw new Error('Parameter \"profileId\" must be a string');\n }\n\n if (!this.content.profileIds) {\n this.content.profileIds = [];\n }\n\n if (this.content.profileIds.indexOf(profileId) === -1) {\n this.content.profileIds.push(profileId);\n }\n\n return this;\n};\n\n/**\n * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {KuzzleUser} this\n */\nKuzzleUser.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nKuzzleUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_rng) {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var _rnds = new Array(16);\n _mathRNG = _rng = function() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }\n _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return _rnds;\n };\n if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, bth = _byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n }\n\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || _rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ii++) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom'),\n KuzzleSubscribeResult = require('./kuzzleSubscribeResult');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n * or like a room for pub/sub messages.\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} collection - name of the data collection to handle\n * @param {string} index - Index containing the data collection\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, collection, index) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\n\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n index: {\n value: index,\n enumerable: true\n },\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (controller, action) {\n return {\n controller: controller,\n action: action,\n collection: this.collection,\n index: this.index\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Executes an advanced search on the data collection.\n *\n * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function.\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'search'), query, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\n });\n};\n\n/**\n * Returns the number of documents matching the provided set of filters.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.count = function (filters, options, cb) {\n var\n query;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n cb(error, result && result.result.count);\n });\n};\n\n/**\n * Create a new empty data collection, with no associated mapping.\n * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n * want to create and prepare data collections before storing documents in it.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.create = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('write', 'createCollection'), data, options, cb);\n\n return this;\n};\n\n/**\n * Create a new document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.createDocument = function (id, document, options, cb) {\n var\n self = this,\n data = {},\n action = 'create';\n\n if (id && typeof id !== 'string') {\n cb = options;\n options = document;\n document = id;\n id = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (document instanceof KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\n }\n\n if (id) {\n data._id = id;\n }\n\n data = self.kuzzle.addHeaders(data, self.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\n doc.version = res.result._version;\n cb(null, doc);\n });\n\n return this;\n};\n\n/**\n * Delete persistent documents.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleDataCollection} this\n */\nKuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) {\n var\n action,\n data = {};\n\n if (typeof arg === 'string') {\n data._id = arg;\n action = 'delete';\n } else {\n data.body = arg;\n action = 'deleteByQuery';\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) {\n if (err) {\n cb(err);\n }\n else {\n cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n }\n });\n\n return this;\n};\n\n/**\n * Retrieve a single stored document using its unique document ID.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n */\nKuzzleDataCollection.prototype.getMapping = function (options, cb) {\n var kuzzleMapping;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('write', 'publish'), data, options, cb);\n\n return this;\n};\n\n/**\n * Replace an existing document with a new one.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to replace\n * @param {object} content - JSON object representing the new document version\n * @param {object} [options] - additional arguments\n * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n var\n self = this,\n data = {\n _id: documentId,\n body: content\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\n};\n\n/**\n * Subscribes to this data collection with a set of filters.\n * To subscribe to the entire data collection, simply provide an empty filter.\n *\n * @param {object} filters - Filters in Kuzzle DSL format\n * @param {object} [options] - subscriptions options\n * @param {responseCallback} cb - called for each new notification\n * @returns {*} KuzzleSubscribeResult object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var\n room,\n subscribeResult;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n subscribeResult = new KuzzleSubscribeResult();\n room = new KuzzleRoom(this, options);\n\n room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\n return subscribeResult;\n};\n\n/**\n * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n * This method is a lot faster than removing all documents using a query.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.truncate = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('admin', 'truncateCollection'), data, options, cb);\n\n return this;\n};\n\n\n/**\n * Update parts of a document\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to update\n * @param {object} content - JSON object containing changes to perform on the document\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Returns an instantiated KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n data = {\n _id: documentId,\n body: content\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new KuzzleDocument(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - document id\n * @param {object} content - document content\n * @constructor\n */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [options] - subscription configuration\n * @constructor\n */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [mapping] - mapping to instantiate the KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(this, mapping);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n * the amount of data you stored in a collection and the complexity of your database.\n *\n * The KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n mapping: {\n value: mapping || {},\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['set', 'setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Applies the new mapping to the data collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleDataMapping.prototype.apply = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.collection.buildQueryArgs('admin', 'updateMapping'), data, options, function (err) {\n if (err) {\n return cb && cb(err);\n }\n\n self.refresh(options, cb);\n });\n\n return this;\n};\n\n/**\n * Replaces the current content with the mapping stored in Kuzzle\n *\n * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDataMapping.prototype.refresh = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('admin', 'getMapping'), data, options, function (err, res) {\n if (err) {\n return cb ? cb(err) : false;\n }\n\n if (res.result[self.collection.index]) {\n if (res.result[self.collection.index].mappings[self.collection.collection]) {\n self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\n // Mappings can be empty. The mapping property should never be \"undefined\"\n if (self.mapping === undefined) {\n self.mapping = {};\n }\n } else {\n return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n }\n } else {\n return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n }\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\n\n/**\n * Adds or updates a field mapping.\n *\n * Changes made by this function won’t be applied until you call the apply method\n *\n * @param {string} field - Name of the field from which the mapping is to be added or updated\n * @param {object} mapping - corresponding field mapping\n * @returns {KuzzleDataMapping}\n */\nKuzzleDataMapping.prototype.set = function (field, mapping) {\n this.mapping[field] = mapping;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle handles documents either as realtime messages or as stored documents.\n * KuzzleDocument is the object representation of one of these documents.\n *\n * Notes:\n * - this constructor may be called either with a documentId, a content, neither or both.\n * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n *\n *\n * @param {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n id: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\n }\n });\n\n // handling provided arguments\n if (!content && documentId && typeof documentId === 'object') {\n content = documentId;\n documentId = null;\n }\n\n if (content) {\n if (content._version) {\n this.version = content._version;\n delete content._version;\n }\n this.setContent(content, true);\n }\n\n if (documentId) {\n Object.defineProperty(this, 'id', {\n value: documentId,\n enumerable: true\n });\n }\n\n // promisifying\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'refresh', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this document\n */\nKuzzleDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data._version = this.version;\n data = this.kuzzle.addHeaders(data, this.headers);\n\n return data;\n};\n\n/**\n * Overrides the toString() method in order to return a serialized version of the document\n *\n * @return {string} serialized version of this object\n */\nKuzzleDocument.prototype.toString = function () {\n return JSON.stringify(this.serialize());\n};\n\n/**\n * Deletes this document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.delete = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\n });\n};\n\n/**\n * Replaces the current content with the last version of this document stored in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.refresh = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\n newDocument.version = res.result._version;\n\n cb(null, newDocument);\n });\n};\n\n/**\n * Saves this document into Kuzzle.\n *\n * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n * of this object.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nKuzzleDocument.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'createOrReplace'), data, options, function (error, res) {\n if (error) {\n return cb && cb(error);\n }\n\n self.id = res.result._id;\n self.version = res.result._version;\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return self;\n};\n\n/**\n * Sends the content of this document as a realtime message.\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'publish'), data, options);\n\n return this;\n};\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {object} data - New content\n * @param {boolean} replace - if true: replace this document content with the provided data\n */\nKuzzleDocument.prototype.setContent = function (data, replace) {\n var self = this;\n\n if (replace) {\n this.content = data;\n }\n else {\n Object.keys(data).forEach(function (key) {\n self.content[key] = data[key];\n });\n }\n\n return this;\n};\n\n/**\n * Listens to events concerning this document. Has no effect if the document does not have an ID\n * (i.e. if the document has not yet been created as a persisted document).\n *\n * @param {object} [options] - subscription options\n * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n */\nKuzzleDocument.prototype.subscribe = function (options, cb) {\n var filters;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided');\n }\n\n filters = { ids: { values: [this.id] } };\n\n return this.dataCollection.subscribe(filters, options, cb);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\n **/","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * Kuzzle's memory storage is a separate data store from the database layer.\n * It is internaly based on Redis. You can access most of Redis functions (all\n * lowercased), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(kuzzle) {\n Object.defineProperties(this, {\n // read-only properties\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n this.setHeaders = kuzzle.setHeaders.bind(this);\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.prototype[command] = function () {\n var\n args = Array.prototype.slice.call(arguments),\n options = null,\n cb,\n query = {\n controller: 'ms',\n action: command\n },\n data = {};\n\n if (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n *\n * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n *\n * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n *\n * @param {object} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, options) {\n // Define properties\n Object.defineProperties(this, {\n // private properties\n callback: {\n value: null,\n writable: true\n },\n channel: {\n value: null,\n writable: true\n },\n id: {\n value: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\n value: null,\n writable: true\n },\n onDoneCB: {\n value: null,\n writable: true\n },\n queue: {\n value: [],\n writable: true\n },\n // Delay before allowing a subscription renewal\n renewalDelay: {\n value: 500\n },\n scope: {\n value: options && options.scope ? options.scope : 'all'\n },\n state: {\n value: options && options.state ? options.state : 'done'\n },\n subscribing: {\n value: false,\n writable: true\n },\n users: {\n value: options && options.users ? options.users : 'none'\n },\n // read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n filters: {\n value: null,\n enumerable: true,\n writable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\n enumerable: true,\n writable: true\n },\n roomId: {\n value: null,\n enumerable: true,\n writable: true\n },\n subscribeToSelf: {\n value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['count'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Returns the number of other subscriptions on that room.\n *\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.count', cb);\n\n data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\n if (!isReady.call(this)) {\n this.queue.push({action: 'count', args: [cb]});\n return;\n }\n\n if (!this.roomId) {\n throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n cb(err, res && res.result.count);\n });\n};\n\n/**\n * Renew the subscription using new filters\n *\n * @param {object} [filters] - Filters in Kuzzle DSL format\n * @param {responseCallback} notificationCB - called for each new notification\n * @param {responseCallback} [cb] - handles the query response\n */\nKuzzleRoom.prototype.renew = function (filters, notificationCB, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (typeof filters === 'function') {\n cb = notificationCB;\n notificationCB = filters;\n filters = null;\n }\n\n if (!cb) {\n cb = self.onDoneCB;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', notificationCB);\n\n /*\n Skip subscription renewal if another one was performed a moment before\n */\n if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n return cb && cb(new Error('Subscription already renewed less than ' + self.renewalDelay + 'ms ago'));\n }\n\n if (filters) {\n self.filters = filters;\n }\n\n /*\n if not yet connected, register itself to the subscriptions list and wait for the\n main Kuzzle object to renew once online\n */\n if (self.kuzzle.state !== 'connected') {\n self.callback = notificationCB;\n self.onDoneCB = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n return;\n }\n\n if (self.subscribing) {\n self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = notificationCB;\n self.onDoneCB = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n }\n\n self.lastRenewal = now;\n self.roomId = response.result.roomId;\n self.channel = response.result.channel;\n\n if (!self.kuzzle.subscriptions[self.roomId]) {\n self.kuzzle.subscriptions[self.roomId] = {};\n }\n\n self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\n self.notifier = notificationCallback.bind(self);\n self.kuzzle.network.on(self.channel, self.notifier);\n\n dequeue.call(self);\n cb && cb(null, self);\n });\n};\n\n/**\n * Unsubscribes from Kuzzle.\n *\n * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n * pending subscriptions reaches 0, and only if there is still no listener on that room.\n * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n *\n * @return {*} this\n */\nKuzzleRoom.prototype.unsubscribe = function () {\n var\n self = this,\n room = self.roomId,\n interval;\n\n if (!isReady.call(this)) {\n self.queue.push({action: 'unsubscribe', args: []});\n return self;\n }\n\n if (room) {\n self.kuzzle.network.off(self.channel, this.notifier);\n\n if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n delete self.kuzzle.subscriptions[room];\n\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n } else {\n interval = setInterval(function () {\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n if (!self.kuzzle.subscriptions[room]) {\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'off'), {body: {roomId: room}});\n }\n clearInterval(interval);\n }\n }, 100);\n }\n } else {\n delete self.kuzzle.subscriptions[room][self.id];\n }\n\n self.roomId = null;\n }\n\n return self;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzleRoom.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n/**\n * Callback called by the network handler when a message is sent to the subscribed room ID\n * Calls the registered callback if the notification passes the subscription filters\n *\n * @param {object} data - data\n * @returns {*}\n */\nfunction notificationCallback (data) {\n if (data.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\n }\n\n if (this.kuzzle.requestHistory[data.requestId]) {\n if (this.subscribeToSelf) {\n this.callback(null, data);\n }\n delete this.kuzzle.requestHistory[data.requestId];\n } else {\n this.callback(null, data);\n }\n}\n\n\n/**\n * Dequeue actions performed while subscription was being renewed\n */\nfunction dequeue () {\n var element;\n\n while (this.queue.length > 0) {\n element = this.queue.shift();\n\n this[element.action].apply(this, element.args);\n }\n}\n\nfunction isReady() {\n return this.kuzzle.state === 'connected' && !this.subscribing;\n}\n\nmodule.exports = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n * Sugar-code handling the result of a KuzzleRoom.renew call\n * @constructor\n */\nfunction KuzzleSubscribeResult() {\n this.cbs = [];\n}\n\n/**\n * Registers a callback to be called with a subscription result\n * @param {Function} cb\n */\nKuzzleSubscribeResult.prototype.onDone = function (cb) {\n this.cbs.push(cb);\n return this;\n};\n\n/**\n * Calls all registered callbacks\n *\n * @param {Object} error object\n * @param {KuzzleRoom} room\n */\nKuzzleSubscribeResult.prototype.done = function (error, room) {\n this.cbs.forEach(function (cb) {\n cb(error, room);\n });\n};\n\nmodule.exports = KuzzleSubscribeResult;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleSubscribeResult.js\n ** module id = 9\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort, sslConnection) {\n // Web browser / NodeJS websocket handling\n if (typeof window !== 'undefined') {\n // use native websockets if the browser supports it\n if (typeof WebSocket !== 'undefined') {\n return new (require('./wrappers/wsbrowsers'))(host, wsPort, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort, sslConnection);\n }\n\n throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n }\n\n return new (require('./wrappers/wsnode'))(host, wsPort, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 10\n ** module chunks = 0\n **/","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\n });\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n this.socket.on('connect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n this.socket.on('connect_error', callback);\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.socket.on('disconnect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n this.socket.on('reconnect', callback);\n };\n\n /**\n * Registers a callback on a room. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.once = function (roomId, callback) {\n this.socket.once(roomId, callback);\n };\n\n /**\n * Registers a callback on a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.on = function (roomId, callback) {\n this.socket.on(roomId, callback);\n };\n\n /**\n * Unregisters a callback from a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.off = function (roomId, callback) {\n this.socket.off(roomId, callback);\n };\n\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n this.socket.emit('kuzzle', payload);\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 11\n ** module chunks = 0\n **/","function WSBrowsers(host, port, ssl) {\n var self = this;\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n * @returns {Object} Socket\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function (code, message) {\n if (code === 1000) {\n poke(self.listeners, 'disconnect');\n }\n else {\n onClientError.call(self, autoReconnect, reconnectionDelay, message);\n }\n };\n\n this.client.onerror = function (error) {\n onClientError.call(self, autoReconnect, reconnectionDelay, error);\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, data);\n }\n };\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n this.listeners.connect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n this.listeners.reconnect.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Registers a callback on a room. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.once = function (roomId, callback) {\n if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\n };\n\n /**\n * Registers a callback on a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.on = function (roomId, callback) {\n if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Unregisters a callback from a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.off = function (roomId, callback) {\n var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\n\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n if (this.client && this.client.readyState === this.client.OPEN) {\n this.client.send(JSON.stringify(payload));\n }\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\n/**\n * Called when the connection closes with an error state\n *\n * @param {boolean} autoReconnect\n * @param {number} reconnectionDelay\n * @param {string|Object} message\n */\nfunction onClientError(autoReconnect, reconnectionDelay, message) {\n var self = this;\n\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error', message);\n}\n\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 12\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteProfile'\n },\n updateActionName: {\n value: 'updateProfile'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['hydrate', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\n }\n});\n\n/**\n * Persist to the persistent layer the current profile\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.save = function (options, cb) {\n var\n data,\n self = this;\n\n if (!this.content.policies) {\n throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.serialize();\n\n self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n\n/**\n * Add a policy in the policies list\n * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n *\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.addPolicy = function (policy) {\n\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n }\n\n if (!this.content.policies) {\n this.content.policies = [];\n }\n\n this.content.policies.push(policy);\n\n return this;\n};\n\n/**\n * Set policies list\n * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @returns {KuzzleProfile} this\n */\nKuzzleProfile.prototype.setPolicies = function (policies) {\n\n if (!Array.isArray(policies)) {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n\n policies.map(function (policy) {\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n });\n\n this.content.policies = policies;\n\n return this;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this securityDocument\n */\nKuzzleProfile.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n\n return data;\n};\n\n/**\n * Returns the list of policies associated to this profile.\n * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @return {object} an array of policies\n */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 13\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteRole'\n },\n updateActionName: {\n value: 'updateRole'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\n }\n});\n\n/**\n * Saves this role into Kuzzle.\n *\n * If this is a new role, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n * of this object.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleRole} this object\n */\nKuzzleRole.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 14\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(kuzzle) {\n\n Object.defineProperty(this, 'kuzzle', {\n value: kuzzle\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (action) {\n return {\n controller: 'security',\n action: action\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['roleFactory', 'profileFactory', 'userFactory', 'isActionAllowed'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * Retrieve a single Role using its unique role ID.\n *\n * @param {string} id\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on roles according to a filter\n *\n * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a role that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.prototype.searchRoles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchRoles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = result.result.hits.map(function (doc) {\n return new KuzzleRole(self, doc._id, doc._source);\n });\n\n cb(null, { total: result.result.total, roles: documents });\n });\n};\n\n/**\n * Create a new role in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same role already exists: throw an error if sets to false.\n * Replace the existing role otherwise\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createRole = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createRole: cannot create a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleRole(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a role in Kuzzle.\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateRole: cannot update a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err) {\n cb(err, err ? undefined : new KuzzleRole(self, id, content));\n });\n\n return this;\n};\n\n/**\n * Delete role.\n *\n * There is a small delay between role deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a role that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Role id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteRole = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleRole object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - role id\n * @param {object} content - role content\n * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on profiles according to a filter\n *\n *\n * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.searchProfiles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\n });\n};\n\n/**\n * Create a new profile in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same profile already exists: throw an error if sets to false.\n * Replace the existing profile otherwise\n *\n * @param {string} id - profile identifier\n * @param {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createProfile: cannot create a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleProfile(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateProfile: cannot update a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n var updatedContent = {};\n\n if (err) {\n return cb(err);\n }\n\n Object.keys(res.result._source).forEach(function (property) {\n updatedContent[property] = res.result._source[property];\n });\n\n cb(null, new KuzzleProfile(self, res.result._id, updatedContent));\n });\n\n return this;\n};\n\n/**\n * Delete profile.\n *\n * There is a small delay between profile deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteProfile = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleProfile object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - profile id\n * @param {object} content - profile content\n * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n var\n data = {_id: id},\n self = this;\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for getUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\n });\n};\n\n/**\n * Executes a search on user according to a filter\n *\n * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a user that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - same filters as documents filters\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.searchUsers = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.updateUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.updateUser: cannot update an user without an user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source));\n });\n\n return this;\n};\n\n/**\n * Delete user.\n *\n * There is a small delay between user deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a user that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {KuzzleSecurity} this object\n */\nKuzzleSecurity.prototype.deleteUser = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleUser object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - user id\n * @param {object} content - user content\n * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\n};\n\n/**\n * Tells whether an action is allowed, denied or conditional based on the rights\n * rights provided as the first argument. An action is defined as a couple of\n * action and controller (mandatory), plus an index and a collection(optional).\n *\n * @param {object} rights - The rights rights associated to a user\n * (see getMyrights and getUserrights).\n * @param {string} controller - The controller to check the action onto.\n * @param {string} action - The action to perform.\n * @param {string} index - (optional) The name of index to perform the action onto.\n * @param {string} collection - (optional) The name of the collection to perform the action onto.\n *\n * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n * correspond to rights containing closures.\n * See also http://kuzzle.io/guide/#roles-definition\n */\nKuzzleSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n var filteredRights;\n\n if (!rights || typeof rights !== 'object') {\n throw new Error('rights parameter is mandatory for isActionAllowed function');\n }\n if (!controller || typeof controller !== 'string') {\n throw new Error('controller parameter is mandatory for isActionAllowed function');\n }\n if (!action || typeof action !== 'string') {\n throw new Error('action parameter is mandatory for isActionAllowed function');\n }\n\n // We filter in all the rights that match the request (including wildcards).\n filteredRights = rights\n .filter(function (right) {\n return right.controller === controller || right.controller === '*';\n })\n .filter(function (right) {\n return right.action === action || right.action === '*';\n })\n .filter(function (right) {\n return right.index === index || right.index === '*';\n })\n .filter(function (right) {\n return right.collection === collection || right.collection === '*';\n });\n\n // Then, if at least one right allows the action, we return 'allowed'\n if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n return 'allowed';\n }\n // If no right allows the action, we check for conditionals.\n if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n return 'conditional';\n }\n // Otherwise we return 'denied'.\n return 'denied';\n};\n\n\n/**\n * Gets the rights array of a given user.\n *\n * @param {string} userId The id of the user.\n * @param {object} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.prototype.getUserRights = function (userId, options, cb) {\n var\n data = {_id: userId},\n self = this;\n\n if (!userId || typeof userId !== 'string') {\n throw new Error('userId parameter is mandatory for getUserRights function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\n this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 15\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/package.json b/package.json index 2e403f307..ce034f4f3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kuzzle-sdk", - "version": "2.1.3", + "version": "2.1.4", "description": "Official Javascript SDK for Kuzzle", "author": "The Kuzzle Team ", "repository": { diff --git a/src/kuzzleRoom.js b/src/kuzzleRoom.js index 19e66e554..e5eade033 100644 --- a/src/kuzzleRoom.js +++ b/src/kuzzleRoom.js @@ -45,6 +45,10 @@ function KuzzleRoom(kuzzleDataCollection, options) { value: null, writable: true }, + onDoneCB: { + value: null, + writable: true + }, queue: { value: [], writable: true @@ -166,13 +170,17 @@ KuzzleRoom.prototype.renew = function (filters, notificationCB, cb) { filters = null; } + if (!cb) { + cb = self.onDoneCB; + } + self.kuzzle.callbackRequired('KuzzleRoom.renew', notificationCB); /* Skip subscription renewal if another one was performed a moment before */ if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) { - return; + return cb && cb(new Error('Subscription already renewed less than ' + self.renewalDelay + 'ms ago')); } if (filters) { @@ -185,6 +193,7 @@ KuzzleRoom.prototype.renew = function (filters, notificationCB, cb) { */ if (self.kuzzle.state !== 'connected') { self.callback = notificationCB; + self.onDoneCB = cb; self.kuzzle.subscriptions.pending[self.id] = self; return; } @@ -198,6 +207,7 @@ KuzzleRoom.prototype.renew = function (filters, notificationCB, cb) { self.roomId = null; self.subscribing = true; self.callback = notificationCB; + self.onDoneCB = cb; self.kuzzle.subscriptions.pending[self.id] = self; subscribeQuery.body = self.filters;