diff --git a/dist/syncState.js b/dist/syncState.js index af5af8f..864dc6d 100644 --- a/dist/syncState.js +++ b/dist/syncState.js @@ -26,8 +26,8 @@ var defaultConfig = { prepareState: function prepareState(state) { return state; }, - receiveState: function receiveState(state) { - return state; + receiveState: function receiveState(prevState, nextState) { + return nextState; } }; diff --git a/dist/syncState.umd.js b/dist/syncState.umd.js index a40f80f..437b045 100644 --- a/dist/syncState.umd.js +++ b/dist/syncState.umd.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t,n){"use strict";(function(e){function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise((function(t){return setTimeout(t,e)}))}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(){return Math.random().toString(36).substring(2)}n.d(t,"b",(function(){return r})),n.d(t,"f",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"c",(function(){return c})),n.d(t,"a",(function(){return l}));var s=0,u=0;function c(){var e=(new Date).getTime();return e===s?1e3*e+ ++u:(s=e,u=0,1e3*e)}var l="[object process]"===Object.prototype.toString.call(void 0!==e?e:0)}).call(this,n(4))},function(e,t){e.exports=!1},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initMessageListener=t.initStateWithPrevTab=t.withReduxStateSync=t.createReduxStateSync=t.createStateSyncMiddleware=t.INIT_MESSAGE_LISTENER=t.RECEIVE_INIT_STATE=t.SEND_INIT_STATE=t.GET_INIT_STATE=void 0,t.generateUuidForAction=h,t.isActionAllowed=p,t.isActionSynced=function(e){return!!e.$isSync},t.MessageListener=m;var r=n(6),o=0,i=t.GET_INIT_STATE="&_GET_INIT_STATE",a=t.SEND_INIT_STATE="&_SEND_INIT_STATE",s=t.RECEIVE_INIT_STATE="&_RECEIVE_INIT_STATE",u=t.INIT_MESSAGE_LISTENER="&_INIT_MESSAGE_LISTENER",c={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:void 0,prepareState:function(e){return e},receiveState:function(e){return e}};function l(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function d(){return""+l()+l()+"-"+l()+"-"+l()+"-"+l()+"-"+l()+l()+l()}var f=d();function h(e){var t=e;return t.$uuid=d(),t.$wuid=f,t}function p(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e.type)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e.type)>=0}),o}function m(e){var t=e.channel,n=e.dispatch,r=e.allowed,u=!1,c={};this.handleOnMessage=function(e){var t;e.$wuid!==f&&(e.type!==s&&e.$uuid&&e.$uuid!==o&&(e.type!==i||c[e.$wuid]?e.type!==a||c[e.$wuid]?r(e)&&(o=e.$uuid,n(Object.assign(e,{$isSync:!0}))):u||(u=!0,n((t=e.payload,{type:s,payload:t}))):(c[e.$wuid]=!0,n({type:a}))))},this.messageChannel=t,this.messageChannel.onmessage=this.handleOnMessage}t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,t=p(e),n=new r.BroadcastChannel(e.channel,e.broadcastChannelOption),s=e.prepareState||c.prepareState,u=null;return function(e){var r=e.getState,c=e.dispatch;return function(e){return function(l){if(u||(u=new m({channel:n,dispatch:c,allowed:t})),l&&!l.$uuid){var d=h(l);o=d.$uuid;try{if(l.type===a)return r()&&(d.payload=s(r()),n.postMessage(d)),e(l);(t(d)||l.type===i)&&n.postMessage(d)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(Object.assign(l,{$isSync:void 0!==l.$isSync&&l.$isSync}))}}}};var v=t.createReduxStateSync=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.receiveState;return function(n,r){var o=n;return r.type===s&&(o=t(n,r.payload)),e(o,r)}};t.withReduxStateSync=v,t.initStateWithPrevTab=function(e){(0,e.dispatch)({type:i})},t.initMessageListener=function(e){(0,e.dispatch)({type:u})}},function(e,t){var n,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=s(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d1)for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=45e3),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=12e4),void 0===t.node.useFastPath&&(t.node.useFastPath=!0),t}var u=r.c;function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e,t){var n=e.transaction("messages").objectStore("messages"),r=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return n.openCursor(e)}catch(e){return n.openCursor()}}()).onsuccess=function(n){var o=n.target.result;o?o.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time0||e._addEL.internal.length>0}function O(e,t,n){e._addEL[t].push(n),function(e){if(!e._iL&&C(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},n=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,n)})):(e._iL=!0,e.method.onMessage(e._state,t,n))}}(e)}function x(e,t,n){e._addEL[t]=e._addEL[t].filter((function(e){return e!==n})),function(e){if(e._iL&&!C(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}k._pubkey=!0,k.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return M(this,"message",e)},postInternal:function(e){return M(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};x(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,O(this,"message",t)):this._onML=null},addEventListener:function(e,t){O(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){x(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}};var A=n(1),j=n.n(A);var N={add:function(e){if("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope);else{if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",(function(){e()}),!0),window.addEventListener("unload",(function(){e()}),!0)}}},B=n(2),D=n.n(B),R=j.a?D.a:N,$=new Set,G=!1;function F(){var e=[];return $.forEach((function(t){e.push(t()),$.delete(t)})),Promise.all(e)}var J={add:function(e){if(G||(G=!0,R.add(F)),"function"!=typeof e)throw new Error("Listener is no function");return $.add(e),{remove:function(){return $.delete(e)},run:function(){return $.delete(e),e()}}},runAll:F,removeAll:function(){$.clear()},getSize:function(){return $.size}},U=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Object(r.e)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function W(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}function V(e){e.isLeader=!0;var t=J.add((function(){return e.die()}));e._unl.push(t);var n=function(t){"leader"===t.context&&"apply"===t.action&&W(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),W(e,"tell"))};return e._channel.addEventListener("internal",n),e._lstns.push(n),W(e,"tell")}function z(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(t,e);var n=new U(e,t);return e._befC.push((function(){return n.die()})),e._leaderElector=n,n}U.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,n=[],o=function(r){"leader"===r.context&&r.token!=e.token&&(n.push(r),"apply"===r.action&&r.token>e.token&&(t=!0),"tell"===r.action&&(t=!0))};return this._channel.addEventListener("internal",o),W(this,"apply").then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e,"apply")})).then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e)})).then((function(){return V(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",o),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var n=!1;function r(){n||(n=!0,clearInterval(o),e._channel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&r()}));var o=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&r()}))}),e._options.fallbackInterval);e._invs.push(o);var i=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&r()}))};e._channel.addEventListener("internal",i),e._lstns.push(i)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),W(this,"death")}}}])})); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t,n){"use strict";(function(e){function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise((function(t){return setTimeout(t,e)}))}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(){return Math.random().toString(36).substring(2)}n.d(t,"b",(function(){return r})),n.d(t,"f",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"c",(function(){return c})),n.d(t,"a",(function(){return l}));var s=0,u=0;function c(){var e=(new Date).getTime();return e===s?1e3*e+ ++u:(s=e,u=0,1e3*e)}var l="[object process]"===Object.prototype.toString.call(void 0!==e?e:0)}).call(this,n(4))},function(e,t){e.exports=!1},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initMessageListener=t.initStateWithPrevTab=t.withReduxStateSync=t.createReduxStateSync=t.createStateSyncMiddleware=t.INIT_MESSAGE_LISTENER=t.RECEIVE_INIT_STATE=t.SEND_INIT_STATE=t.GET_INIT_STATE=void 0,t.generateUuidForAction=h,t.isActionAllowed=p,t.isActionSynced=function(e){return!!e.$isSync},t.MessageListener=m;var r=n(6),o=0,i=t.GET_INIT_STATE="&_GET_INIT_STATE",a=t.SEND_INIT_STATE="&_SEND_INIT_STATE",s=t.RECEIVE_INIT_STATE="&_RECEIVE_INIT_STATE",u=t.INIT_MESSAGE_LISTENER="&_INIT_MESSAGE_LISTENER",c={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:void 0,prepareState:function(e){return e},receiveState:function(e,t){return t}};function l(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function d(){return""+l()+l()+"-"+l()+"-"+l()+"-"+l()+"-"+l()+l()+l()}var f=d();function h(e){var t=e;return t.$uuid=d(),t.$wuid=f,t}function p(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e.type)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e.type)>=0}),o}function m(e){var t=e.channel,n=e.dispatch,r=e.allowed,u=!1,c={};this.handleOnMessage=function(e){var t;e.$wuid!==f&&(e.type!==s&&e.$uuid&&e.$uuid!==o&&(e.type!==i||c[e.$wuid]?e.type!==a||c[e.$wuid]?r(e)&&(o=e.$uuid,n(Object.assign(e,{$isSync:!0}))):u||(u=!0,n((t=e.payload,{type:s,payload:t}))):(c[e.$wuid]=!0,n({type:a}))))},this.messageChannel=t,this.messageChannel.onmessage=this.handleOnMessage}t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,t=p(e),n=new r.BroadcastChannel(e.channel,e.broadcastChannelOption),s=e.prepareState||c.prepareState,u=null;return function(e){var r=e.getState,c=e.dispatch;return function(e){return function(l){if(u||(u=new m({channel:n,dispatch:c,allowed:t})),l&&!l.$uuid){var d=h(l);o=d.$uuid;try{if(l.type===a)return r()&&(d.payload=s(r()),n.postMessage(d)),e(l);(t(d)||l.type===i)&&n.postMessage(d)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(Object.assign(l,{$isSync:void 0!==l.$isSync&&l.$isSync}))}}}};var v=t.createReduxStateSync=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.receiveState;return function(n,r){var o=n;return r.type===s&&(o=t(n,r.payload)),e(o,r)}};t.withReduxStateSync=v,t.initStateWithPrevTab=function(e){(0,e.dispatch)({type:i})},t.initMessageListener=function(e){(0,e.dispatch)({type:u})}},function(e,t){var n,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=s(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d1)for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=45e3),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=12e4),void 0===t.node.useFastPath&&(t.node.useFastPath=!0),t}var u=r.c;function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e,t){var n=e.transaction("messages").objectStore("messages"),r=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return n.openCursor(e)}catch(e){return n.openCursor()}}()).onsuccess=function(n){var o=n.target.result;o?o.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time0||e._addEL.internal.length>0}function O(e,t,n){e._addEL[t].push(n),function(e){if(!e._iL&&C(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},n=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,n)})):(e._iL=!0,e.method.onMessage(e._state,t,n))}}(e)}function x(e,t,n){e._addEL[t]=e._addEL[t].filter((function(e){return e!==n})),function(e){if(e._iL&&!C(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}k._pubkey=!0,k.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return M(this,"message",e)},postInternal:function(e){return M(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};x(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,O(this,"message",t)):this._onML=null},addEventListener:function(e,t){O(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){x(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}};var A=n(1),j=n.n(A);var N={add:function(e){if("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope);else{if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",(function(){e()}),!0),window.addEventListener("unload",(function(){e()}),!0)}}},B=n(2),D=n.n(B),R=j.a?D.a:N,$=new Set,G=!1;function F(){var e=[];return $.forEach((function(t){e.push(t()),$.delete(t)})),Promise.all(e)}var J={add:function(e){if(G||(G=!0,R.add(F)),"function"!=typeof e)throw new Error("Listener is no function");return $.add(e),{remove:function(){return $.delete(e)},run:function(){return $.delete(e),e()}}},runAll:F,removeAll:function(){$.clear()},getSize:function(){return $.size}},U=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Object(r.e)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function W(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}function V(e){e.isLeader=!0;var t=J.add((function(){return e.die()}));e._unl.push(t);var n=function(t){"leader"===t.context&&"apply"===t.action&&W(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),W(e,"tell"))};return e._channel.addEventListener("internal",n),e._lstns.push(n),W(e,"tell")}function z(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(t,e);var n=new U(e,t);return e._befC.push((function(){return n.die()})),e._leaderElector=n,n}U.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,n=[],o=function(r){"leader"===r.context&&r.token!=e.token&&(n.push(r),"apply"===r.action&&r.token>e.token&&(t=!0),"tell"===r.action&&(t=!0))};return this._channel.addEventListener("internal",o),W(this,"apply").then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e,"apply")})).then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e)})).then((function(){return V(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",o),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var n=!1;function r(){n||(n=!0,clearInterval(o),e._channel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&r()}));var o=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&r()}))}),e._options.fallbackInterval);e._invs.push(o);var i=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&r()}))};e._channel.addEventListener("internal",i),e._lstns.push(i)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),W(this,"death")}}}])})); //# sourceMappingURL=syncState.umd.js.map \ No newline at end of file diff --git a/dist/syncState.umd.js.map b/dist/syncState.umd.js.map index 85f308b..922c263 100644 --- a/dist/syncState.umd.js.map +++ b/dist/syncState.umd.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://reduxStateSync/webpack/universalModuleDefinition","webpack://reduxStateSync/webpack/bootstrap","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/util.js","webpack://reduxStateSync/./node_modules/detect-node/browser.js","webpack://reduxStateSync/./src/syncState.js","webpack://reduxStateSync/./node_modules/process/browser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/native.js","webpack://reduxStateSync/./node_modules/oblivious-set/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/options.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/indexed-db.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/localstorage.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/simulate.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/method-chooser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/broadcast-channel.js","webpack://reduxStateSync/./node_modules/unload/dist/es/browser.js","webpack://reduxStateSync/./node_modules/unload/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/leader-election.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","isPromise","obj","then","sleep","time","Promise","res","setTimeout","randomInt","min","max","Math","floor","random","randomToken","toString","substring","lastMs","additional","microSeconds","ms","Date","getTime","isNode","process","generateUuidForAction","isActionAllowed","isActionSynced","action","$isSync","MessageListener","lastUuid","GET_INIT_STATE","SEND_INIT_STATE","RECEIVE_INIT_STATE","INIT_MESSAGE_LISTENER","defaultConfig","channel","predicate","blacklist","whitelist","broadcastChannelOption","undefined","prepareState","state","receiveState","s4","guid","WINDOW_STATE_SYNC_ID","stampedAction","$uuid","$wuid","allowed","Array","isArray","indexOf","type","dispatch","isSynced","tabs","this","handleOnMessage","assign","payload","messageChannel","onmessage","createStateSyncMiddleware","config","BroadcastChannel","messageListener","getState","next","postMessage","e","console","error","createReduxStateSync","appReducer","initState","withReduxStateSync","initStateWithPrevTab","initMessageListener","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","Error","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","channelName","messagesCallback","bc","subFns","msg","data","close","channelState","onMessage","fn","messageJson","resolve","err","reject","canBeUsed","_pubkey","averageResponseTime","ObliviousSet","ttl","set","Set","timeMap","Map","has","add","_this","now","obliviousSet","olderThen","iterator","delete","removeTooOldValues","clear","fillOptionsWithDefaults","originalOptions","options","JSON","parse","stringify","webWorkerSupport","idb","fallbackInterval","onclose","localstorage","removeTimeout","methods","node","useFastPath","getIdb","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","getMessagesHigherThan","db","lastCursorId","objectStore","transaction","ret","keyRangeValue","IDBKeyRange","bound","Infinity","openCursor","onsuccess","ev","cursor","target","result","id","cleanOldMessages","msgObk","getOldMessages","tooOld","all","map","msgObj","request","removeMessageById","readNewMessages","closed","newerMessages","filter","uuid","eMIs","messagesCallbackTime","_filterMessage","sort","msgObjA","msgObjB","forEach","dbName","openRequest","open","onupgradeneeded","createObjectStore","keyPath","autoIncrement","rej","onerror","createDatabase","writeBlockPromise","readQueuePromises","_readLoop","readerUuid","writeObject","oncomplete","writeMessage","getLocalStorage","localStorage","storageKey","ls","setItem","removeItem","listener","newValue","addEventListener","addStorageEventListener","token","removeEventListener","writeObj","document","createEvent","initEvent","dispatchEvent","userAgent","navigator","toLowerCase","includes","defaultTime","SIMULATE_CHANNELS","from","METHODS","NodeMethod","chooseMethod","chooseMethods","Boolean","find","useMethod","method","ENFORCED_OPTIONS","maybePromise","_iL","_onML","_addEL","message","internal","_uMP","_befC","_prepP","_state","clearNodeFolder","enforceOptions","_post","broadcastChannel","sendPromise","_hasMessageListeners","_addListenerObject","listenerFn","_startListening","_removeListenerObject","_stopListening","postInternal","listenObj","awaitPrepare","WorkerGlobalScope","self","USE_METHOD","LISTENERS","startedListening","runAll","promises","remove","removeAll","getSize","size","_channel","_options","isLeader","isDead","_isApl","_reApply","_unl","_lstns","_invs","_dpL","_dpLC","_sendMessage","leaderElector","msgJson","context","beLeader","unloadFn","die","isLeaderListener","createLeaderElection","_leaderElector","responseTime","elector","applyOnce","stopCriteria","recieved","handleMessage","success","awaitLeadership","_aLP","resolved","finish","clearInterval","interval","whenDeathListener","setInterval","_this2","uFn"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAwB,eAAID,IAE5BD,EAAqB,eAAIC,IAR3B,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,i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H,IAAImB,EAAS5R,KAEb,IAAIA,KAAK2P,OAeT,OAdA3P,KAAK2P,QAAS,EAEd3P,KAAK+P,OAAO7F,SAAQ,SAAUwB,GAC5B,OAAOkG,EAAOpC,SAASzD,oBAAoB,WAAYL,MAGzD1L,KAAKgQ,MAAM9F,SAAQ,SAAUuH,GAC3B,OAAOD,cAAcC,MAGvBzR,KAAK8P,KAAK5F,SAAQ,SAAU2H,GAC1BA,EAAIzC,YAGCe,EAAanQ,KAAM","file":"syncState.umd.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 if(typeof exports === 'object')\n\t\texports[\"reduxStateSync\"] = factory();\n\telse\n\t\troot[\"reduxStateSync\"] = factory();\n})(window, function() {\nreturn "," \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 \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\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.l = 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// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 3);\n","/**\n * returns true if the given object is a promise\n */\nexport function isPromise(obj) {\n if (obj && typeof obj.then === 'function') {\n return true;\n } else {\n return false;\n }\n}\nexport function sleep(time) {\n if (!time) time = 0;\n return new Promise(function (res) {\n return setTimeout(res, time);\n });\n}\nexport function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/**\n * https://stackoverflow.com/a/8084248\n */\n\nexport function randomToken() {\n return Math.random().toString(36).substring(2);\n}\nvar lastMs = 0;\nvar additional = 0;\n/**\n * returns the current time in micro-seconds,\n * WARNING: This is a pseudo-function\n * Performance.now is not reliable in webworkers, so we just make sure to never return the same time.\n * This is enough in browsers, and this function will not be used in nodejs.\n * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.\n */\n\nexport function microSeconds() {\n var ms = new Date().getTime();\n\n if (ms === lastMs) {\n additional++;\n return ms * 1000 + additional;\n } else {\n lastMs = ms;\n additional = 0;\n return ms * 1000;\n }\n}\n/**\n * copied from the 'detect-node' npm module\n * We cannot use the module directly because it causes problems with rollup\n * @link https://github.com/iliakan/detect-node/blob/master/index.js\n */\n\nexport var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';","module.exports = false;\n\n","import { BroadcastChannel } from 'broadcast-channel';\n\nlet lastUuid = 0;\nexport const GET_INIT_STATE = '&_GET_INIT_STATE';\nexport const SEND_INIT_STATE = '&_SEND_INIT_STATE';\nexport const RECEIVE_INIT_STATE = '&_RECEIVE_INIT_STATE';\nexport const INIT_MESSAGE_LISTENER = '&_INIT_MESSAGE_LISTENER';\n\nconst defaultConfig = {\n channel: 'redux_state_sync',\n predicate: null,\n blacklist: [],\n whitelist: [],\n broadcastChannelOption: undefined,\n prepareState: state => state,\n receiveState: state => state,\n};\n\nconst getIniteState = () => ({ type: GET_INIT_STATE });\nconst sendIniteState = () => ({ type: SEND_INIT_STATE });\nconst receiveIniteState = state => ({ type: RECEIVE_INIT_STATE, payload: state });\nconst initListener = () => ({ type: INIT_MESSAGE_LISTENER });\n\nfunction s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n}\n\nfunction guid() {\n return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;\n}\n\n// generate current window unique id\nconst WINDOW_STATE_SYNC_ID = guid();\n// export for test\nexport function generateUuidForAction(action) {\n const stampedAction = action;\n stampedAction.$uuid = guid();\n stampedAction.$wuid = WINDOW_STATE_SYNC_ID;\n return stampedAction;\n}\n// export for test\nexport function isActionAllowed({ predicate, blacklist, whitelist }) {\n let allowed = () => true;\n\n if (predicate && typeof predicate === 'function') {\n allowed = predicate;\n } else if (Array.isArray(blacklist)) {\n allowed = action => blacklist.indexOf(action.type) < 0;\n } else if (Array.isArray(whitelist)) {\n allowed = action => whitelist.indexOf(action.type) >= 0;\n }\n return allowed;\n}\n// export for test\nexport function isActionSynced(action) {\n return !!action.$isSync;\n}\n// export for test\nexport function MessageListener({ channel, dispatch, allowed }) {\n let isSynced = false;\n const tabs = {};\n this.handleOnMessage = stampedAction => {\n // Ignore if this action is triggered by this window\n if (stampedAction.$wuid === WINDOW_STATE_SYNC_ID) {\n return;\n }\n // IE bug https://stackoverflow.com/questions/18265556/why-does-internet-explorer-fire-the-window-storage-event-on-the-window-that-st\n if (stampedAction.type === RECEIVE_INIT_STATE) {\n return;\n }\n // ignore other values that saved to localstorage.\n if (stampedAction.$uuid && stampedAction.$uuid !== lastUuid) {\n if (stampedAction.type === GET_INIT_STATE && !tabs[stampedAction.$wuid]) {\n tabs[stampedAction.$wuid] = true;\n dispatch(sendIniteState());\n } else if (stampedAction.type === SEND_INIT_STATE && !tabs[stampedAction.$wuid]) {\n if (!isSynced) {\n isSynced = true;\n dispatch(receiveIniteState(stampedAction.payload));\n }\n } else if (allowed(stampedAction)) {\n lastUuid = stampedAction.$uuid;\n dispatch(\n Object.assign(stampedAction, {\n $isSync: true,\n }),\n );\n }\n }\n };\n this.messageChannel = channel;\n this.messageChannel.onmessage = this.handleOnMessage;\n}\n\nexport const createStateSyncMiddleware = (config = defaultConfig) => {\n const allowed = isActionAllowed(config);\n const channel = new BroadcastChannel(config.channel, config.broadcastChannelOption);\n const prepareState = config.prepareState || defaultConfig.prepareState;\n let messageListener = null;\n\n return ({ getState, dispatch }) => next => action => {\n // create message receiver\n if (!messageListener) {\n messageListener = new MessageListener({ channel, dispatch, allowed });\n }\n // post messages\n if (action && !action.$uuid) {\n const stampedAction = generateUuidForAction(action);\n lastUuid = stampedAction.$uuid;\n try {\n if (action.type === SEND_INIT_STATE) {\n if (getState()) {\n stampedAction.payload = prepareState(getState());\n channel.postMessage(stampedAction);\n }\n return next(action);\n }\n if (allowed(stampedAction) || action.type === GET_INIT_STATE) {\n channel.postMessage(stampedAction);\n }\n } catch (e) {\n console.error(\"Your browser doesn't support cross tab communication\");\n }\n }\n return next(\n Object.assign(action, {\n $isSync: typeof action.$isSync === 'undefined' ? false : action.$isSync,\n }),\n );\n };\n};\n\n// eslint-disable-next-line max-len\nexport const createReduxStateSync = (appReducer, receiveState = defaultConfig.receiveState) => (state, action) => {\n let initState = state;\n if (action.type === RECEIVE_INIT_STATE) {\n initState = receiveState(state, action.payload);\n }\n return appReducer(initState, action);\n};\n\n// init state with other tab's state\nexport const withReduxStateSync = createReduxStateSync;\n\nexport const initStateWithPrevTab = ({ dispatch }) => {\n dispatch(getIniteState());\n};\n\n/*\nif don't dispath any action, the store.dispath will not be available for message listener.\ntherefor need to trigger an empty action to init the messageListener.\n\nhowever, if already using initStateWithPrevTab, this function will be redundant\n*/\nexport const initMessageListener = ({ dispatch }) => {\n dispatch(initListener());\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import { microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nexport var type = 'native';\nexport function create(channelName) {\n var state = {\n messagesCallback: null,\n bc: new BroadcastChannel(channelName),\n subFns: [] // subscriberFunctions\n\n };\n\n state.bc.onmessage = function (msg) {\n if (state.messagesCallback) {\n state.messagesCallback(msg.data);\n }\n };\n\n return state;\n}\nexport function close(channelState) {\n channelState.bc.close();\n channelState.subFns = [];\n}\nexport function postMessage(channelState, messageJson) {\n try {\n channelState.bc.postMessage(messageJson, false);\n return Promise.resolve();\n } catch (err) {\n return Promise.reject(err);\n }\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n /**\n * in the electron-renderer, isNode will be true even if we are in browser-context\n * so we also check if window is undefined\n */\n if (isNode && typeof window === 'undefined') return false;\n\n if (typeof BroadcastChannel === 'function') {\n if (BroadcastChannel._pubkey) {\n throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');\n }\n\n return true;\n } else return false;\n}\nexport function averageResponseTime() {\n return 150;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * this is a set which automatically forgets\n * a given entry when a new entry is set and the ttl\n * of the old one is over\n */\nvar ObliviousSet = /** @class */ (function () {\n function ObliviousSet(ttl) {\n this.ttl = ttl;\n this.set = new Set();\n this.timeMap = new Map();\n }\n ObliviousSet.prototype.has = function (value) {\n return this.set.has(value);\n };\n ObliviousSet.prototype.add = function (value) {\n var _this = this;\n this.timeMap.set(value, now());\n this.set.add(value);\n /**\n * When a new value is added,\n * start the cleanup at the next tick\n * to not block the cpu for more important stuff\n * that might happen.\n */\n setTimeout(function () {\n removeTooOldValues(_this);\n }, 0);\n };\n ObliviousSet.prototype.clear = function () {\n this.set.clear();\n this.timeMap.clear();\n };\n return ObliviousSet;\n}());\nexport { ObliviousSet };\n/**\n * Removes all entries from the set\n * where the TTL has expired\n */\nexport function removeTooOldValues(obliviousSet) {\n var olderThen = now() - obliviousSet.ttl;\n var iterator = obliviousSet.set[Symbol.iterator]();\n /**\n * Because we can assume the new values are added at the bottom,\n * we start from the top and stop as soon as we reach a non-too-old value.\n */\n while (true) {\n var value = iterator.next().value;\n if (!value) {\n return; // no more elements\n }\n var time = obliviousSet.timeMap.get(value);\n if (time < olderThen) {\n obliviousSet.timeMap.delete(value);\n obliviousSet.set.delete(value);\n }\n else {\n // We reached a value that is not old enough\n return;\n }\n }\n}\nexport function now() {\n return new Date().getTime();\n}\n//# sourceMappingURL=index.js.map","export function fillOptionsWithDefaults() {\n var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = JSON.parse(JSON.stringify(originalOptions)); // main\n\n if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; // indexed-db\n\n if (!options.idb) options.idb = {}; // after this time the messages get deleted\n\n if (!options.idb.ttl) options.idb.ttl = 1000 * 45;\n if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; // handles abrupt db onclose events.\n\n if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose; // localstorage\n\n if (!options.localstorage) options.localstorage = {};\n if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; // custom methods\n\n if (originalOptions.methods) options.methods = originalOptions.methods; // node\n\n if (!options.node) options.node = {};\n if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;\n\n if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;\n return options;\n}","/**\n * this method uses indexeddb to store the messages\n * There is currently no observerAPI for idb\n * @link https://github.com/w3c/IndexedDB/issues/51\n */\nimport { sleep, randomInt, randomToken, microSeconds as micro, isNode } from '../util.js';\nexport var microSeconds = micro;\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nvar DB_PREFIX = 'pubkey.broadcast-channel-0-';\nvar OBJECT_STORE_ID = 'messages';\nexport var type = 'idb';\nexport function getIdb() {\n if (typeof indexedDB !== 'undefined') return indexedDB;\n\n if (typeof window !== 'undefined') {\n if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;\n if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;\n if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;\n }\n\n return false;\n}\nexport function createDatabase(channelName) {\n var IndexedDB = getIdb(); // create table\n\n var dbName = DB_PREFIX + channelName;\n var openRequest = IndexedDB.open(dbName, 1);\n\n openRequest.onupgradeneeded = function (ev) {\n var db = ev.target.result;\n db.createObjectStore(OBJECT_STORE_ID, {\n keyPath: 'id',\n autoIncrement: true\n });\n };\n\n var dbPromise = new Promise(function (res, rej) {\n openRequest.onerror = function (ev) {\n return rej(ev);\n };\n\n openRequest.onsuccess = function () {\n res(openRequest.result);\n };\n });\n return dbPromise;\n}\n/**\n * writes the new message to the database\n * so other readers can find it\n */\n\nexport function writeMessage(db, readerUuid, messageJson) {\n var time = new Date().getTime();\n var writeObject = {\n uuid: readerUuid,\n time: time,\n data: messageJson\n };\n var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');\n return new Promise(function (res, rej) {\n transaction.oncomplete = function () {\n return res();\n };\n\n transaction.onerror = function (ev) {\n return rej(ev);\n };\n\n var objectStore = transaction.objectStore(OBJECT_STORE_ID);\n objectStore.add(writeObject);\n });\n}\nexport function getAllMessages(db) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n ret.push(cursor.value); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n res(ret);\n }\n };\n });\n}\nexport function getMessagesHigherThan(db, lastCursorId) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n\n function openCursor() {\n // Occasionally Safari will fail on IDBKeyRange.bound, this\n // catches that error, having it open the cursor to the first\n // item. When it gets data it will advance to the desired key.\n try {\n var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n return objectStore.openCursor(keyRangeValue);\n } catch (e) {\n return objectStore.openCursor();\n }\n }\n\n return new Promise(function (res) {\n openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n if (cursor.value.id < lastCursorId + 1) {\n cursor[\"continue\"](lastCursorId + 1);\n } else {\n ret.push(cursor.value);\n cursor[\"continue\"]();\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function removeMessageById(db, id) {\n var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)[\"delete\"](id);\n return new Promise(function (res) {\n request.onsuccess = function () {\n return res();\n };\n });\n}\nexport function getOldMessages(db, ttl) {\n var olderThen = new Date().getTime() - ttl;\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n var msgObk = cursor.value;\n\n if (msgObk.time < olderThen) {\n ret.push(msgObk); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n // no more old messages,\n res(ret);\n return;\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function cleanOldMessages(db, ttl) {\n return getOldMessages(db, ttl).then(function (tooOld) {\n return Promise.all(tooOld.map(function (msgObj) {\n return removeMessageById(db, msgObj.id);\n }));\n });\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n return createDatabase(channelName).then(function (db) {\n var state = {\n closed: false,\n lastCursorId: 0,\n channelName: channelName,\n options: options,\n uuid: randomToken(),\n\n /**\n * emittedMessagesIds\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n eMIs: new ObliviousSet(options.idb.ttl * 2),\n // ensures we do not read messages in parrallel\n writeBlockPromise: Promise.resolve(),\n messagesCallback: null,\n readQueuePromises: [],\n db: db\n };\n /**\n * Handle abrupt closes that do not originate from db.close().\n * This could happen, for example, if the underlying storage is\n * removed or if the user clears the database in the browser's\n * history preferences.\n */\n\n db.onclose = function () {\n state.closed = true;\n if (options.idb.onclose) options.idb.onclose();\n };\n /**\n * if service-workers are used,\n * we have no 'storage'-event if they post a message,\n * therefore we also have to set an interval\n */\n\n\n _readLoop(state);\n\n return state;\n });\n}\n\nfunction _readLoop(state) {\n if (state.closed) return;\n readNewMessages(state).then(function () {\n return sleep(state.options.idb.fallbackInterval);\n }).then(function () {\n return _readLoop(state);\n });\n}\n\nfunction _filterMessage(msgObj, state) {\n if (msgObj.uuid === state.uuid) return false; // send by own\n\n if (state.eMIs.has(msgObj.id)) return false; // already emitted\n\n if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback\n\n return true;\n}\n/**\n * reads all new messages from the database and emits them\n */\n\n\nfunction readNewMessages(state) {\n // channel already closed\n if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages\n\n if (!state.messagesCallback) return Promise.resolve();\n return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {\n var useMessages = newerMessages\n /**\n * there is a bug in iOS where the msgObj can be undefined some times\n * so we filter them out\n * @link https://github.com/pubkey/broadcast-channel/issues/19\n */\n .filter(function (msgObj) {\n return !!msgObj;\n }).map(function (msgObj) {\n if (msgObj.id > state.lastCursorId) {\n state.lastCursorId = msgObj.id;\n }\n\n return msgObj;\n }).filter(function (msgObj) {\n return _filterMessage(msgObj, state);\n }).sort(function (msgObjA, msgObjB) {\n return msgObjA.time - msgObjB.time;\n }); // sort by time\n\n useMessages.forEach(function (msgObj) {\n if (state.messagesCallback) {\n state.eMIs.add(msgObj.id);\n state.messagesCallback(msgObj.data);\n }\n });\n return Promise.resolve();\n });\n}\n\nexport function close(channelState) {\n channelState.closed = true;\n channelState.db.close();\n}\nexport function postMessage(channelState, messageJson) {\n channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {\n return writeMessage(channelState.db, channelState.uuid, messageJson);\n }).then(function () {\n if (randomInt(0, 10) === 0) {\n /* await (do not await) */\n cleanOldMessages(channelState.db, channelState.options.idb.ttl);\n }\n });\n return channelState.writeBlockPromise;\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n readNewMessages(channelState);\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var idb = getIdb();\n if (!idb) return false;\n return true;\n}\nexport function averageResponseTime(options) {\n return options.idb.fallbackInterval * 2;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * A localStorage-only method which uses localstorage and its 'storage'-event\n * This does not work inside of webworkers because they have no access to locastorage\n * This is basically implemented to support IE9 or your grandmothers toaster.\n * @link https://caniuse.com/#feat=namevalue-storage\n * @link https://caniuse.com/#feat=indexeddb\n */\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nimport { sleep, randomToken, microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nvar KEY_PREFIX = 'pubkey.broadcastChannel-';\nexport var type = 'localstorage';\n/**\n * copied from crosstab\n * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32\n */\n\nexport function getLocalStorage() {\n var localStorage;\n if (typeof window === 'undefined') return null;\n\n try {\n localStorage = window.localStorage;\n localStorage = window['ie8-eventlistener/storage'] || window.localStorage;\n } catch (e) {// New versions of Firefox throw a Security exception\n // if cookies are disabled. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153\n }\n\n return localStorage;\n}\nexport function storageKey(channelName) {\n return KEY_PREFIX + channelName;\n}\n/**\n* writes the new message to the storage\n* and fires the storage-event so other readers can find it\n*/\n\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n sleep().then(function () {\n var key = storageKey(channelState.channelName);\n var writeObj = {\n token: randomToken(),\n time: new Date().getTime(),\n data: messageJson,\n uuid: channelState.uuid\n };\n var value = JSON.stringify(writeObj);\n getLocalStorage().setItem(key, value);\n /**\n * StorageEvent does not fire the 'storage' event\n * in the window that changes the state of the local storage.\n * So we fire it manually\n */\n\n var ev = document.createEvent('Event');\n ev.initEvent('storage', true, true);\n ev.key = key;\n ev.newValue = value;\n window.dispatchEvent(ev);\n res();\n });\n });\n}\nexport function addStorageEventListener(channelName, fn) {\n var key = storageKey(channelName);\n\n var listener = function listener(ev) {\n if (ev.key === key) {\n fn(JSON.parse(ev.newValue));\n }\n };\n\n window.addEventListener('storage', listener);\n return listener;\n}\nexport function removeStorageEventListener(listener) {\n window.removeEventListener('storage', listener);\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n\n if (!canBeUsed()) {\n throw new Error('BroadcastChannel: localstorage cannot be used');\n }\n\n var uuid = randomToken();\n /**\n * eMIs\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n\n var eMIs = new ObliviousSet(options.localstorage.removeTimeout);\n var state = {\n channelName: channelName,\n uuid: uuid,\n eMIs: eMIs // emittedMessagesIds\n\n };\n state.listener = addStorageEventListener(channelName, function (msgObj) {\n if (!state.messagesCallback) return; // no listener\n\n if (msgObj.uuid === uuid) return; // own message\n\n if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted\n\n if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old\n\n eMIs.add(msgObj.token);\n state.messagesCallback(msgObj.data);\n });\n return state;\n}\nexport function close(channelState) {\n removeStorageEventListener(channelState.listener);\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var ls = getLocalStorage();\n if (!ls) return false;\n\n try {\n var key = '__broadcastchannel_check';\n ls.setItem(key, 'works');\n ls.removeItem(key);\n } catch (e) {\n // Safari 10 in private mode will not allow write access to local\n // storage and fail with a QuotaExceededError. See\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes\n return false;\n }\n\n return true;\n}\nexport function averageResponseTime() {\n var defaultTime = 120;\n var userAgent = navigator.userAgent.toLowerCase();\n\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n // safari is much slower so this time is higher\n return defaultTime * 2;\n }\n\n return defaultTime;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import { microSeconds as micro } from '../util';\nexport var microSeconds = micro;\nexport var type = 'simulate';\nvar SIMULATE_CHANNELS = new Set();\nexport function create(channelName) {\n var state = {\n name: channelName,\n messagesCallback: null\n };\n SIMULATE_CHANNELS.add(state);\n return state;\n}\nexport function close(channelState) {\n SIMULATE_CHANNELS[\"delete\"](channelState);\n}\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n return setTimeout(function () {\n var channelArray = Array.from(SIMULATE_CHANNELS);\n channelArray.filter(function (channel) {\n return channel.name === channelState.name;\n }).filter(function (channel) {\n return channel !== channelState;\n }).filter(function (channel) {\n return !!channel.messagesCallback;\n }).forEach(function (channel) {\n return channel.messagesCallback(messageJson);\n });\n res();\n }, 5);\n });\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n return true;\n}\nexport function averageResponseTime() {\n return 5;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import NativeMethod from './methods/native.js';\nimport IndexeDbMethod from './methods/indexed-db.js';\nimport LocalstorageMethod from './methods/localstorage.js';\nimport SimulateMethod from './methods/simulate.js';\nimport { isNode } from './util'; // order is important\n\nvar METHODS = [NativeMethod, // fastest\nIndexeDbMethod, LocalstorageMethod];\n/**\n * The NodeMethod is loaded lazy\n * so it will not get bundled in browser-builds\n */\n\nif (isNode) {\n /**\n * we use the non-transpiled code for nodejs\n * because it runs faster\n */\n var NodeMethod = require('../../src/methods/' + // use this hack so that browserify and others\n // do not import the node-method by default\n // when bundling.\n 'node.js');\n /**\n * this will be false for webpackbuilds\n * which will shim the node-method with an empty object {}\n */\n\n\n if (typeof NodeMethod.canBeUsed === 'function') {\n METHODS.push(NodeMethod);\n }\n}\n\nexport function chooseMethod(options) {\n var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen\n\n if (options.type) {\n if (options.type === 'simulate') {\n // only use simulate-method if directly chosen\n return SimulateMethod;\n }\n\n var ret = chooseMethods.find(function (m) {\n return m.type === options.type;\n });\n if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;\n }\n /**\n * if no webworker support is needed,\n * remove idb from the list so that localstorage is been chosen\n */\n\n\n if (!options.webWorkerSupport && !isNode) {\n chooseMethods = chooseMethods.filter(function (m) {\n return m.type !== 'idb';\n });\n }\n\n var useMethod = chooseMethods.find(function (method) {\n return method.canBeUsed();\n });\n if (!useMethod) throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(function (m) {\n return m.type;\n })));else return useMethod;\n}","import { isPromise } from './util.js';\nimport { chooseMethod } from './method-chooser.js';\nimport { fillOptionsWithDefaults } from './options.js';\nexport var BroadcastChannel = function BroadcastChannel(name, options) {\n this.name = name;\n\n if (ENFORCED_OPTIONS) {\n options = ENFORCED_OPTIONS;\n }\n\n this.options = fillOptionsWithDefaults(options);\n this.method = chooseMethod(this.options); // isListening\n\n this._iL = false;\n /**\n * _onMessageListener\n * setting onmessage twice,\n * will overwrite the first listener\n */\n\n this._onML = null;\n /**\n * _addEventListeners\n */\n\n this._addEL = {\n message: [],\n internal: []\n };\n /**\n * Unsend message promises\n * where the sending is still in progress\n * @type {Set}\n */\n\n this._uMP = new Set();\n /**\n * _beforeClose\n * array of promises that will be awaited\n * before the channel is closed\n */\n\n this._befC = [];\n /**\n * _preparePromise\n */\n\n this._prepP = null;\n\n _prepareChannel(this);\n}; // STATICS\n\n/**\n * used to identify if someone overwrites\n * window.BroadcastChannel with this\n * See methods/native.js\n */\n\nBroadcastChannel._pubkey = true;\n/**\n * clears the tmp-folder if is node\n * @return {Promise} true if has run, false if not node\n */\n\nexport function clearNodeFolder(options) {\n options = fillOptionsWithDefaults(options);\n var method = chooseMethod(options);\n\n if (method.type === 'node') {\n return method.clearNodeFolder().then(function () {\n return true;\n });\n } else {\n return Promise.resolve(false);\n }\n}\n/**\n * if set, this method is enforced,\n * no mather what the options are\n */\n\nvar ENFORCED_OPTIONS;\nexport function enforceOptions(options) {\n ENFORCED_OPTIONS = options;\n} // PROTOTYPE\n\nBroadcastChannel.prototype = {\n postMessage: function postMessage(msg) {\n if (this.closed) {\n throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');\n }\n\n return _post(this, 'message', msg);\n },\n postInternal: function postInternal(msg) {\n return _post(this, 'internal', msg);\n },\n\n set onmessage(fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _removeListenerObject(this, 'message', this._onML);\n\n if (fn && typeof fn === 'function') {\n this._onML = listenObj;\n\n _addListenerObject(this, 'message', listenObj);\n } else {\n this._onML = null;\n }\n },\n\n addEventListener: function addEventListener(type, fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _addListenerObject(this, type, listenObj);\n },\n removeEventListener: function removeEventListener(type, fn) {\n var obj = this._addEL[type].find(function (obj) {\n return obj.fn === fn;\n });\n\n _removeListenerObject(this, type, obj);\n },\n close: function close() {\n var _this = this;\n\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();\n this._onML = null;\n this._addEL.message = [];\n return awaitPrepare // wait until all current sending are processed\n .then(function () {\n return Promise.all(Array.from(_this._uMP));\n }) // run before-close hooks\n .then(function () {\n return Promise.all(_this._befC.map(function (fn) {\n return fn();\n }));\n }) // close the channel\n .then(function () {\n return _this.method.close(_this._state);\n });\n },\n\n get type() {\n return this.method.type;\n },\n\n get isClosed() {\n return this.closed;\n }\n\n};\n/**\n * Post a message over the channel\n * @returns {Promise} that resolved when the message sending is done\n */\n\nfunction _post(broadcastChannel, type, msg) {\n var time = broadcastChannel.method.microSeconds();\n var msgObj = {\n time: time,\n type: type,\n data: msg\n };\n var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();\n return awaitPrepare.then(function () {\n var sendPromise = broadcastChannel.method.postMessage(broadcastChannel._state, msgObj); // add/remove to unsend messages list\n\n broadcastChannel._uMP.add(sendPromise);\n\n sendPromise[\"catch\"]().then(function () {\n return broadcastChannel._uMP[\"delete\"](sendPromise);\n });\n return sendPromise;\n });\n}\n\nfunction _prepareChannel(channel) {\n var maybePromise = channel.method.create(channel.name, channel.options);\n\n if (isPromise(maybePromise)) {\n channel._prepP = maybePromise;\n maybePromise.then(function (s) {\n // used in tests to simulate slow runtime\n\n /*if (channel.options.prepareDelay) {\n await new Promise(res => setTimeout(res, this.options.prepareDelay));\n }*/\n channel._state = s;\n });\n } else {\n channel._state = maybePromise;\n }\n}\n\nfunction _hasMessageListeners(channel) {\n if (channel._addEL.message.length > 0) return true;\n if (channel._addEL.internal.length > 0) return true;\n return false;\n}\n\nfunction _addListenerObject(channel, type, obj) {\n channel._addEL[type].push(obj);\n\n _startListening(channel);\n}\n\nfunction _removeListenerObject(channel, type, obj) {\n channel._addEL[type] = channel._addEL[type].filter(function (o) {\n return o !== obj;\n });\n\n _stopListening(channel);\n}\n\nfunction _startListening(channel) {\n if (!channel._iL && _hasMessageListeners(channel)) {\n // someone is listening, start subscribing\n var listenerFn = function listenerFn(msgObj) {\n channel._addEL[msgObj.type].forEach(function (obj) {\n if (msgObj.time >= obj.time) {\n obj.fn(msgObj.data);\n }\n });\n };\n\n var time = channel.method.microSeconds();\n\n if (channel._prepP) {\n channel._prepP.then(function () {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n });\n } else {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n }\n }\n}\n\nfunction _stopListening(channel) {\n if (channel._iL && !_hasMessageListeners(channel)) {\n // noone is listening, stop subscribing\n channel._iL = false;\n var time = channel.method.microSeconds();\n channel.method.onMessage(channel._state, null, time);\n }\n}","/* global WorkerGlobalScope */\nfunction add(fn) {\n if (typeof WorkerGlobalScope === 'function' && self instanceof WorkerGlobalScope) {// this is run inside of a webworker\n } else {\n /**\n * if we are on react-native, there is no window.addEventListener\n * @link https://github.com/pubkey/unload/issues/6\n */\n if (typeof window.addEventListener !== 'function') return;\n /**\n * for normal browser-windows, we use the beforeunload-event\n */\n\n window.addEventListener('beforeunload', function () {\n fn();\n }, true);\n /**\n * for iframes, we have to use the unload-event\n * @link https://stackoverflow.com/q/47533670/3443137\n */\n\n window.addEventListener('unload', function () {\n fn();\n }, true);\n }\n /**\n * TODO add fallback for safari-mobile\n * @link https://stackoverflow.com/a/26193516/3443137\n */\n\n}\n\nexport default {\n add: add\n};","import isNode from 'detect-node';\nimport BrowserMethod from './browser.js';\nimport NodeMethod from './node.js';\nvar USE_METHOD = isNode ? NodeMethod : BrowserMethod;\nvar LISTENERS = new Set();\nvar startedListening = false;\n\nfunction startListening() {\n if (startedListening) return;\n startedListening = true;\n USE_METHOD.add(runAll);\n}\n\nexport function add(fn) {\n startListening();\n if (typeof fn !== 'function') throw new Error('Listener is no function');\n LISTENERS.add(fn);\n var addReturn = {\n remove: function remove() {\n return LISTENERS[\"delete\"](fn);\n },\n run: function run() {\n LISTENERS[\"delete\"](fn);\n return fn();\n }\n };\n return addReturn;\n}\nexport function runAll() {\n var promises = [];\n LISTENERS.forEach(function (fn) {\n promises.push(fn());\n LISTENERS[\"delete\"](fn);\n });\n return Promise.all(promises);\n}\nexport function removeAll() {\n LISTENERS.clear();\n}\nexport function getSize() {\n return LISTENERS.size;\n}\nexport default {\n add: add,\n runAll: runAll,\n removeAll: removeAll,\n getSize: getSize\n};","import { sleep, randomToken } from './util.js';\nimport unload from 'unload';\n\nvar LeaderElection = function LeaderElection(channel, options) {\n this._channel = channel;\n this._options = options;\n this.isLeader = false;\n this.isDead = false;\n this.token = randomToken();\n this._isApl = false; // _isApplying\n\n this._reApply = false; // things to clean up\n\n this._unl = []; // _unloads\n\n this._lstns = []; // _listeners\n\n this._invs = []; // _intervals\n\n this._dpL = function () {}; // onduplicate listener\n\n\n this._dpLC = false; // true when onduplicate called\n};\n\nLeaderElection.prototype = {\n applyOnce: function applyOnce() {\n var _this = this;\n\n if (this.isLeader) return Promise.resolve(false);\n if (this.isDead) return Promise.resolve(false); // do nothing if already running\n\n if (this._isApl) {\n this._reApply = true;\n return Promise.resolve(false);\n }\n\n this._isApl = true;\n var stopCriteria = false;\n var recieved = [];\n\n var handleMessage = function handleMessage(msg) {\n if (msg.context === 'leader' && msg.token != _this.token) {\n recieved.push(msg);\n\n if (msg.action === 'apply') {\n // other is applying\n if (msg.token > _this.token) {\n // other has higher token, stop applying\n stopCriteria = true;\n }\n }\n\n if (msg.action === 'tell') {\n // other is already leader\n stopCriteria = true;\n }\n }\n };\n\n this._channel.addEventListener('internal', handleMessage);\n\n var ret = _sendMessage(this, 'apply') // send out that this one is applying\n .then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this, 'apply');\n }).then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this);\n }).then(function () {\n return beLeader(_this);\n }) // no one disagreed -> this one is now leader\n .then(function () {\n return true;\n })[\"catch\"](function () {\n return false;\n }) // apply not successfull\n .then(function (success) {\n _this._channel.removeEventListener('internal', handleMessage);\n\n _this._isApl = false;\n\n if (!success && _this._reApply) {\n _this._reApply = false;\n return _this.applyOnce();\n } else return success;\n });\n\n return ret;\n },\n awaitLeadership: function awaitLeadership() {\n if (\n /* _awaitLeadershipPromise */\n !this._aLP) {\n this._aLP = _awaitLeadershipOnce(this);\n }\n\n return this._aLP;\n },\n\n set onduplicate(fn) {\n this._dpL = fn;\n },\n\n die: function die() {\n var _this2 = this;\n\n if (this.isDead) return;\n this.isDead = true;\n\n this._lstns.forEach(function (listener) {\n return _this2._channel.removeEventListener('internal', listener);\n });\n\n this._invs.forEach(function (interval) {\n return clearInterval(interval);\n });\n\n this._unl.forEach(function (uFn) {\n uFn.remove();\n });\n\n return _sendMessage(this, 'death');\n }\n};\n\nfunction _awaitLeadershipOnce(leaderElector) {\n if (leaderElector.isLeader) return Promise.resolve();\n return new Promise(function (res) {\n var resolved = false;\n\n function finish() {\n if (resolved) {\n return;\n }\n\n resolved = true;\n clearInterval(interval);\n\n leaderElector._channel.removeEventListener('internal', whenDeathListener);\n\n res(true);\n } // try once now\n\n\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n }); // try on fallbackInterval\n\n var interval = setInterval(function () {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n }, leaderElector._options.fallbackInterval);\n\n leaderElector._invs.push(interval); // try when other leader dies\n\n\n var whenDeathListener = function whenDeathListener(msg) {\n if (msg.context === 'leader' && msg.action === 'death') {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) finish();\n });\n }\n };\n\n leaderElector._channel.addEventListener('internal', whenDeathListener);\n\n leaderElector._lstns.push(whenDeathListener);\n });\n}\n/**\n * sends and internal message over the broadcast-channel\n */\n\n\nfunction _sendMessage(leaderElector, action) {\n var msgJson = {\n context: 'leader',\n action: action,\n token: leaderElector.token\n };\n return leaderElector._channel.postInternal(msgJson);\n}\n\nexport function beLeader(leaderElector) {\n leaderElector.isLeader = true;\n var unloadFn = unload.add(function () {\n return leaderElector.die();\n });\n\n leaderElector._unl.push(unloadFn);\n\n var isLeaderListener = function isLeaderListener(msg) {\n if (msg.context === 'leader' && msg.action === 'apply') {\n _sendMessage(leaderElector, 'tell');\n }\n\n if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) {\n /**\n * another instance is also leader!\n * This can happen on rare events\n * like when the CPU is at 100% for long time\n * or the tabs are open very long and the browser throttles them.\n * @link https://github.com/pubkey/broadcast-channel/issues/414\n * @link https://github.com/pubkey/broadcast-channel/issues/385\n */\n leaderElector._dpLC = true;\n\n leaderElector._dpL(); // message the lib user so the app can handle the problem\n\n\n _sendMessage(leaderElector, 'tell'); // ensure other leader also knows the problem\n\n }\n };\n\n leaderElector._channel.addEventListener('internal', isLeaderListener);\n\n leaderElector._lstns.push(isLeaderListener);\n\n return _sendMessage(leaderElector, 'tell');\n}\n\nfunction fillOptionsWithDefaults(options, channel) {\n if (!options) options = {};\n options = JSON.parse(JSON.stringify(options));\n\n if (!options.fallbackInterval) {\n options.fallbackInterval = 3000;\n }\n\n if (!options.responseTime) {\n options.responseTime = channel.method.averageResponseTime(channel.options);\n }\n\n return options;\n}\n\nexport function createLeaderElection(channel, options) {\n if (channel._leaderElector) {\n throw new Error('BroadcastChannel already has a leader-elector');\n }\n\n options = fillOptionsWithDefaults(options, channel);\n var elector = new LeaderElection(channel, options);\n\n channel._befC.push(function () {\n return elector.die();\n });\n\n channel._leaderElector = elector;\n return elector;\n}"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://reduxStateSync/webpack/universalModuleDefinition","webpack://reduxStateSync/webpack/bootstrap","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/util.js","webpack://reduxStateSync/./node_modules/detect-node/browser.js","webpack://reduxStateSync/./src/syncState.js","webpack://reduxStateSync/./node_modules/process/browser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/native.js","webpack://reduxStateSync/./node_modules/oblivious-set/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/options.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/indexed-db.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/localstorage.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/simulate.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/method-chooser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/broadcast-channel.js","webpack://reduxStateSync/./node_modules/unload/dist/es/browser.js","webpack://reduxStateSync/./node_modules/unload/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/leader-election.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","isPromise","obj","then","sleep","time","Promise","res","setTimeout","randomInt","min","max","Math","floor","random","randomToken","toString","substring","lastMs","additional","microSeconds","ms","Date","getTime","isNode","process","generateUuidForAction","isActionAllowed","isActionSynced","action","$isSync","MessageListener","lastUuid","GET_INIT_STATE","SEND_INIT_STATE","RECEIVE_INIT_STATE","INIT_MESSAGE_LISTENER","defaultConfig","channel","predicate","blacklist","whitelist","broadcastChannelOption","undefined","prepareState","state","receiveState","prevState","nextState","s4","guid","WINDOW_STATE_SYNC_ID","stampedAction","$uuid","$wuid","allowed","Array","isArray","indexOf","type","dispatch","isSynced","tabs","this","handleOnMessage","assign","payload","messageChannel","onmessage","createStateSyncMiddleware","config","BroadcastChannel","messageListener","getState","next","postMessage","e","console","error","createReduxStateSync","appReducer","initState","withReduxStateSync","initStateWithPrevTab","initMessageListener","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","Error","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","channelName","messagesCallback","bc","subFns","msg","data","close","channelState","onMessage","fn","messageJson","resolve","err","reject","canBeUsed","_pubkey","averageResponseTime","ObliviousSet","ttl","set","Set","timeMap","Map","has","add","_this","now","obliviousSet","olderThen","iterator","delete","removeTooOldValues","clear","fillOptionsWithDefaults","originalOptions","options","JSON","parse","stringify","webWorkerSupport","idb","fallbackInterval","onclose","localstorage","removeTimeout","methods","node","useFastPath","getIdb","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","getMessagesHigherThan","db","lastCursorId","objectStore","transaction","ret","keyRangeValue","IDBKeyRange","bound","Infinity","openCursor","onsuccess","ev","cursor","target","result","id","cleanOldMessages","msgObk","getOldMessages","tooOld","all","map","msgObj","request","removeMessageById","readNewMessages","closed","newerMessages","filter","uuid","eMIs","messagesCallbackTime","_filterMessage","sort","msgObjA","msgObjB","forEach","dbName","openRequest","open","onupgradeneeded","createObjectStore","keyPath","autoIncrement","rej","onerror","createDatabase","writeBlockPromise","readQueuePromises","_readLoop","readerUuid","writeObject","oncomplete","writeMessage","getLocalStorage","localStorage","storageKey","ls","setItem","removeItem","listener","newValue","addEventListener","addStorageEventListener","token","removeEventListener","writeObj","document","createEvent","initEvent","dispatchEvent","userAgent","navigator","toLowerCase","includes","defaultTime","SIMULATE_CHANNELS","from","METHODS","NodeMethod","chooseMethod","chooseMethods","Boolean","find","useMethod","method","ENFORCED_OPTIONS","maybePromise","_iL","_onML","_addEL","message","internal","_uMP","_befC","_prepP","_state","clearNodeFolder","enforceOptions","_post","broadcastChannel","sendPromise","_hasMessageListeners","_addListenerObject","listenerFn","_startListening","_removeListenerObject","_stopListening","postInternal","listenObj","awaitPrepare","WorkerGlobalScope","self","USE_METHOD","LISTENERS","startedListening","runAll","promises","remove","removeAll","getSize","size","_channel","_options","isLeader","isDead","_isApl","_reApply","_unl","_lstns","_invs","_dpL","_dpLC","_sendMessage","leaderElector","msgJson","context","beLeader","unloadFn","die","isLeaderListener","createLeaderElection","_leaderElector","responseTime","elector","applyOnce","stopCriteria","recieved","handleMessage","success","awaitLeadership","_aLP","resolved","finish","clearInterval","interval","whenDeathListener","setInterval","_this2","uFn"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QAC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,MAAM9F,SAAQ,SAAUuH,GAC3B,OAAOD,cAAcC,MAGvBzR,KAAK8P,KAAK5F,SAAQ,SAAU2H,GAC1BA,EAAIzC,YAGCe,EAAanQ,KAAM","file":"syncState.umd.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 if(typeof exports === 'object')\n\t\texports[\"reduxStateSync\"] = factory();\n\telse\n\t\troot[\"reduxStateSync\"] = factory();\n})(window, function() {\nreturn "," \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 \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\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.l = 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// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 3);\n","/**\n * returns true if the given object is a promise\n */\nexport function isPromise(obj) {\n if (obj && typeof obj.then === 'function') {\n return true;\n } else {\n return false;\n }\n}\nexport function sleep(time) {\n if (!time) time = 0;\n return new Promise(function (res) {\n return setTimeout(res, time);\n });\n}\nexport function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/**\n * https://stackoverflow.com/a/8084248\n */\n\nexport function randomToken() {\n return Math.random().toString(36).substring(2);\n}\nvar lastMs = 0;\nvar additional = 0;\n/**\n * returns the current time in micro-seconds,\n * WARNING: This is a pseudo-function\n * Performance.now is not reliable in webworkers, so we just make sure to never return the same time.\n * This is enough in browsers, and this function will not be used in nodejs.\n * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.\n */\n\nexport function microSeconds() {\n var ms = new Date().getTime();\n\n if (ms === lastMs) {\n additional++;\n return ms * 1000 + additional;\n } else {\n lastMs = ms;\n additional = 0;\n return ms * 1000;\n }\n}\n/**\n * copied from the 'detect-node' npm module\n * We cannot use the module directly because it causes problems with rollup\n * @link https://github.com/iliakan/detect-node/blob/master/index.js\n */\n\nexport var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';","module.exports = false;\n\n","import { BroadcastChannel } from 'broadcast-channel';\n\nlet lastUuid = 0;\nexport const GET_INIT_STATE = '&_GET_INIT_STATE';\nexport const SEND_INIT_STATE = '&_SEND_INIT_STATE';\nexport const RECEIVE_INIT_STATE = '&_RECEIVE_INIT_STATE';\nexport const INIT_MESSAGE_LISTENER = '&_INIT_MESSAGE_LISTENER';\n\nconst defaultConfig = {\n channel: 'redux_state_sync',\n predicate: null,\n blacklist: [],\n whitelist: [],\n broadcastChannelOption: undefined,\n prepareState: state => state,\n receiveState: (prevState, nextState) => nextState,\n};\n\nconst getIniteState = () => ({ type: GET_INIT_STATE });\nconst sendIniteState = () => ({ type: SEND_INIT_STATE });\nconst receiveIniteState = state => ({ type: RECEIVE_INIT_STATE, payload: state });\nconst initListener = () => ({ type: INIT_MESSAGE_LISTENER });\n\nfunction s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n}\n\nfunction guid() {\n return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;\n}\n\n// generate current window unique id\nconst WINDOW_STATE_SYNC_ID = guid();\n// export for test\nexport function generateUuidForAction(action) {\n const stampedAction = action;\n stampedAction.$uuid = guid();\n stampedAction.$wuid = WINDOW_STATE_SYNC_ID;\n return stampedAction;\n}\n// export for test\nexport function isActionAllowed({ predicate, blacklist, whitelist }) {\n let allowed = () => true;\n\n if (predicate && typeof predicate === 'function') {\n allowed = predicate;\n } else if (Array.isArray(blacklist)) {\n allowed = action => blacklist.indexOf(action.type) < 0;\n } else if (Array.isArray(whitelist)) {\n allowed = action => whitelist.indexOf(action.type) >= 0;\n }\n return allowed;\n}\n// export for test\nexport function isActionSynced(action) {\n return !!action.$isSync;\n}\n// export for test\nexport function MessageListener({ channel, dispatch, allowed }) {\n let isSynced = false;\n const tabs = {};\n this.handleOnMessage = stampedAction => {\n // Ignore if this action is triggered by this window\n if (stampedAction.$wuid === WINDOW_STATE_SYNC_ID) {\n return;\n }\n // IE bug https://stackoverflow.com/questions/18265556/why-does-internet-explorer-fire-the-window-storage-event-on-the-window-that-st\n if (stampedAction.type === RECEIVE_INIT_STATE) {\n return;\n }\n // ignore other values that saved to localstorage.\n if (stampedAction.$uuid && stampedAction.$uuid !== lastUuid) {\n if (stampedAction.type === GET_INIT_STATE && !tabs[stampedAction.$wuid]) {\n tabs[stampedAction.$wuid] = true;\n dispatch(sendIniteState());\n } else if (stampedAction.type === SEND_INIT_STATE && !tabs[stampedAction.$wuid]) {\n if (!isSynced) {\n isSynced = true;\n dispatch(receiveIniteState(stampedAction.payload));\n }\n } else if (allowed(stampedAction)) {\n lastUuid = stampedAction.$uuid;\n dispatch(\n Object.assign(stampedAction, {\n $isSync: true,\n }),\n );\n }\n }\n };\n this.messageChannel = channel;\n this.messageChannel.onmessage = this.handleOnMessage;\n}\n\nexport const createStateSyncMiddleware = (config = defaultConfig) => {\n const allowed = isActionAllowed(config);\n const channel = new BroadcastChannel(config.channel, config.broadcastChannelOption);\n const prepareState = config.prepareState || defaultConfig.prepareState;\n let messageListener = null;\n\n return ({ getState, dispatch }) => next => action => {\n // create message receiver\n if (!messageListener) {\n messageListener = new MessageListener({ channel, dispatch, allowed });\n }\n // post messages\n if (action && !action.$uuid) {\n const stampedAction = generateUuidForAction(action);\n lastUuid = stampedAction.$uuid;\n try {\n if (action.type === SEND_INIT_STATE) {\n if (getState()) {\n stampedAction.payload = prepareState(getState());\n channel.postMessage(stampedAction);\n }\n return next(action);\n }\n if (allowed(stampedAction) || action.type === GET_INIT_STATE) {\n channel.postMessage(stampedAction);\n }\n } catch (e) {\n console.error(\"Your browser doesn't support cross tab communication\");\n }\n }\n return next(\n Object.assign(action, {\n $isSync: typeof action.$isSync === 'undefined' ? false : action.$isSync,\n }),\n );\n };\n};\n\n// eslint-disable-next-line max-len\nexport const createReduxStateSync = (appReducer, receiveState = defaultConfig.receiveState) => (state, action) => {\n let initState = state;\n if (action.type === RECEIVE_INIT_STATE) {\n initState = receiveState(state, action.payload);\n }\n return appReducer(initState, action);\n};\n\n// init state with other tab's state\nexport const withReduxStateSync = createReduxStateSync;\n\nexport const initStateWithPrevTab = ({ dispatch }) => {\n dispatch(getIniteState());\n};\n\n/*\nif don't dispath any action, the store.dispath will not be available for message listener.\ntherefor need to trigger an empty action to init the messageListener.\n\nhowever, if already using initStateWithPrevTab, this function will be redundant\n*/\nexport const initMessageListener = ({ dispatch }) => {\n dispatch(initListener());\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import { microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nexport var type = 'native';\nexport function create(channelName) {\n var state = {\n messagesCallback: null,\n bc: new BroadcastChannel(channelName),\n subFns: [] // subscriberFunctions\n\n };\n\n state.bc.onmessage = function (msg) {\n if (state.messagesCallback) {\n state.messagesCallback(msg.data);\n }\n };\n\n return state;\n}\nexport function close(channelState) {\n channelState.bc.close();\n channelState.subFns = [];\n}\nexport function postMessage(channelState, messageJson) {\n try {\n channelState.bc.postMessage(messageJson, false);\n return Promise.resolve();\n } catch (err) {\n return Promise.reject(err);\n }\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n /**\n * in the electron-renderer, isNode will be true even if we are in browser-context\n * so we also check if window is undefined\n */\n if (isNode && typeof window === 'undefined') return false;\n\n if (typeof BroadcastChannel === 'function') {\n if (BroadcastChannel._pubkey) {\n throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');\n }\n\n return true;\n } else return false;\n}\nexport function averageResponseTime() {\n return 150;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * this is a set which automatically forgets\n * a given entry when a new entry is set and the ttl\n * of the old one is over\n */\nvar ObliviousSet = /** @class */ (function () {\n function ObliviousSet(ttl) {\n this.ttl = ttl;\n this.set = new Set();\n this.timeMap = new Map();\n }\n ObliviousSet.prototype.has = function (value) {\n return this.set.has(value);\n };\n ObliviousSet.prototype.add = function (value) {\n var _this = this;\n this.timeMap.set(value, now());\n this.set.add(value);\n /**\n * When a new value is added,\n * start the cleanup at the next tick\n * to not block the cpu for more important stuff\n * that might happen.\n */\n setTimeout(function () {\n removeTooOldValues(_this);\n }, 0);\n };\n ObliviousSet.prototype.clear = function () {\n this.set.clear();\n this.timeMap.clear();\n };\n return ObliviousSet;\n}());\nexport { ObliviousSet };\n/**\n * Removes all entries from the set\n * where the TTL has expired\n */\nexport function removeTooOldValues(obliviousSet) {\n var olderThen = now() - obliviousSet.ttl;\n var iterator = obliviousSet.set[Symbol.iterator]();\n /**\n * Because we can assume the new values are added at the bottom,\n * we start from the top and stop as soon as we reach a non-too-old value.\n */\n while (true) {\n var value = iterator.next().value;\n if (!value) {\n return; // no more elements\n }\n var time = obliviousSet.timeMap.get(value);\n if (time < olderThen) {\n obliviousSet.timeMap.delete(value);\n obliviousSet.set.delete(value);\n }\n else {\n // We reached a value that is not old enough\n return;\n }\n }\n}\nexport function now() {\n return new Date().getTime();\n}\n//# sourceMappingURL=index.js.map","export function fillOptionsWithDefaults() {\n var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = JSON.parse(JSON.stringify(originalOptions)); // main\n\n if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; // indexed-db\n\n if (!options.idb) options.idb = {}; // after this time the messages get deleted\n\n if (!options.idb.ttl) options.idb.ttl = 1000 * 45;\n if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; // handles abrupt db onclose events.\n\n if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose; // localstorage\n\n if (!options.localstorage) options.localstorage = {};\n if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; // custom methods\n\n if (originalOptions.methods) options.methods = originalOptions.methods; // node\n\n if (!options.node) options.node = {};\n if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;\n\n if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;\n return options;\n}","/**\n * this method uses indexeddb to store the messages\n * There is currently no observerAPI for idb\n * @link https://github.com/w3c/IndexedDB/issues/51\n */\nimport { sleep, randomInt, randomToken, microSeconds as micro, isNode } from '../util.js';\nexport var microSeconds = micro;\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nvar DB_PREFIX = 'pubkey.broadcast-channel-0-';\nvar OBJECT_STORE_ID = 'messages';\nexport var type = 'idb';\nexport function getIdb() {\n if (typeof indexedDB !== 'undefined') return indexedDB;\n\n if (typeof window !== 'undefined') {\n if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;\n if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;\n if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;\n }\n\n return false;\n}\nexport function createDatabase(channelName) {\n var IndexedDB = getIdb(); // create table\n\n var dbName = DB_PREFIX + channelName;\n var openRequest = IndexedDB.open(dbName, 1);\n\n openRequest.onupgradeneeded = function (ev) {\n var db = ev.target.result;\n db.createObjectStore(OBJECT_STORE_ID, {\n keyPath: 'id',\n autoIncrement: true\n });\n };\n\n var dbPromise = new Promise(function (res, rej) {\n openRequest.onerror = function (ev) {\n return rej(ev);\n };\n\n openRequest.onsuccess = function () {\n res(openRequest.result);\n };\n });\n return dbPromise;\n}\n/**\n * writes the new message to the database\n * so other readers can find it\n */\n\nexport function writeMessage(db, readerUuid, messageJson) {\n var time = new Date().getTime();\n var writeObject = {\n uuid: readerUuid,\n time: time,\n data: messageJson\n };\n var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');\n return new Promise(function (res, rej) {\n transaction.oncomplete = function () {\n return res();\n };\n\n transaction.onerror = function (ev) {\n return rej(ev);\n };\n\n var objectStore = transaction.objectStore(OBJECT_STORE_ID);\n objectStore.add(writeObject);\n });\n}\nexport function getAllMessages(db) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n ret.push(cursor.value); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n res(ret);\n }\n };\n });\n}\nexport function getMessagesHigherThan(db, lastCursorId) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n\n function openCursor() {\n // Occasionally Safari will fail on IDBKeyRange.bound, this\n // catches that error, having it open the cursor to the first\n // item. When it gets data it will advance to the desired key.\n try {\n var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n return objectStore.openCursor(keyRangeValue);\n } catch (e) {\n return objectStore.openCursor();\n }\n }\n\n return new Promise(function (res) {\n openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n if (cursor.value.id < lastCursorId + 1) {\n cursor[\"continue\"](lastCursorId + 1);\n } else {\n ret.push(cursor.value);\n cursor[\"continue\"]();\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function removeMessageById(db, id) {\n var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)[\"delete\"](id);\n return new Promise(function (res) {\n request.onsuccess = function () {\n return res();\n };\n });\n}\nexport function getOldMessages(db, ttl) {\n var olderThen = new Date().getTime() - ttl;\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n var msgObk = cursor.value;\n\n if (msgObk.time < olderThen) {\n ret.push(msgObk); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n // no more old messages,\n res(ret);\n return;\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function cleanOldMessages(db, ttl) {\n return getOldMessages(db, ttl).then(function (tooOld) {\n return Promise.all(tooOld.map(function (msgObj) {\n return removeMessageById(db, msgObj.id);\n }));\n });\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n return createDatabase(channelName).then(function (db) {\n var state = {\n closed: false,\n lastCursorId: 0,\n channelName: channelName,\n options: options,\n uuid: randomToken(),\n\n /**\n * emittedMessagesIds\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n eMIs: new ObliviousSet(options.idb.ttl * 2),\n // ensures we do not read messages in parrallel\n writeBlockPromise: Promise.resolve(),\n messagesCallback: null,\n readQueuePromises: [],\n db: db\n };\n /**\n * Handle abrupt closes that do not originate from db.close().\n * This could happen, for example, if the underlying storage is\n * removed or if the user clears the database in the browser's\n * history preferences.\n */\n\n db.onclose = function () {\n state.closed = true;\n if (options.idb.onclose) options.idb.onclose();\n };\n /**\n * if service-workers are used,\n * we have no 'storage'-event if they post a message,\n * therefore we also have to set an interval\n */\n\n\n _readLoop(state);\n\n return state;\n });\n}\n\nfunction _readLoop(state) {\n if (state.closed) return;\n readNewMessages(state).then(function () {\n return sleep(state.options.idb.fallbackInterval);\n }).then(function () {\n return _readLoop(state);\n });\n}\n\nfunction _filterMessage(msgObj, state) {\n if (msgObj.uuid === state.uuid) return false; // send by own\n\n if (state.eMIs.has(msgObj.id)) return false; // already emitted\n\n if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback\n\n return true;\n}\n/**\n * reads all new messages from the database and emits them\n */\n\n\nfunction readNewMessages(state) {\n // channel already closed\n if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages\n\n if (!state.messagesCallback) return Promise.resolve();\n return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {\n var useMessages = newerMessages\n /**\n * there is a bug in iOS where the msgObj can be undefined some times\n * so we filter them out\n * @link https://github.com/pubkey/broadcast-channel/issues/19\n */\n .filter(function (msgObj) {\n return !!msgObj;\n }).map(function (msgObj) {\n if (msgObj.id > state.lastCursorId) {\n state.lastCursorId = msgObj.id;\n }\n\n return msgObj;\n }).filter(function (msgObj) {\n return _filterMessage(msgObj, state);\n }).sort(function (msgObjA, msgObjB) {\n return msgObjA.time - msgObjB.time;\n }); // sort by time\n\n useMessages.forEach(function (msgObj) {\n if (state.messagesCallback) {\n state.eMIs.add(msgObj.id);\n state.messagesCallback(msgObj.data);\n }\n });\n return Promise.resolve();\n });\n}\n\nexport function close(channelState) {\n channelState.closed = true;\n channelState.db.close();\n}\nexport function postMessage(channelState, messageJson) {\n channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {\n return writeMessage(channelState.db, channelState.uuid, messageJson);\n }).then(function () {\n if (randomInt(0, 10) === 0) {\n /* await (do not await) */\n cleanOldMessages(channelState.db, channelState.options.idb.ttl);\n }\n });\n return channelState.writeBlockPromise;\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n readNewMessages(channelState);\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var idb = getIdb();\n if (!idb) return false;\n return true;\n}\nexport function averageResponseTime(options) {\n return options.idb.fallbackInterval * 2;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * A localStorage-only method which uses localstorage and its 'storage'-event\n * This does not work inside of webworkers because they have no access to locastorage\n * This is basically implemented to support IE9 or your grandmothers toaster.\n * @link https://caniuse.com/#feat=namevalue-storage\n * @link https://caniuse.com/#feat=indexeddb\n */\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nimport { sleep, randomToken, microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nvar KEY_PREFIX = 'pubkey.broadcastChannel-';\nexport var type = 'localstorage';\n/**\n * copied from crosstab\n * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32\n */\n\nexport function getLocalStorage() {\n var localStorage;\n if (typeof window === 'undefined') return null;\n\n try {\n localStorage = window.localStorage;\n localStorage = window['ie8-eventlistener/storage'] || window.localStorage;\n } catch (e) {// New versions of Firefox throw a Security exception\n // if cookies are disabled. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153\n }\n\n return localStorage;\n}\nexport function storageKey(channelName) {\n return KEY_PREFIX + channelName;\n}\n/**\n* writes the new message to the storage\n* and fires the storage-event so other readers can find it\n*/\n\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n sleep().then(function () {\n var key = storageKey(channelState.channelName);\n var writeObj = {\n token: randomToken(),\n time: new Date().getTime(),\n data: messageJson,\n uuid: channelState.uuid\n };\n var value = JSON.stringify(writeObj);\n getLocalStorage().setItem(key, value);\n /**\n * StorageEvent does not fire the 'storage' event\n * in the window that changes the state of the local storage.\n * So we fire it manually\n */\n\n var ev = document.createEvent('Event');\n ev.initEvent('storage', true, true);\n ev.key = key;\n ev.newValue = value;\n window.dispatchEvent(ev);\n res();\n });\n });\n}\nexport function addStorageEventListener(channelName, fn) {\n var key = storageKey(channelName);\n\n var listener = function listener(ev) {\n if (ev.key === key) {\n fn(JSON.parse(ev.newValue));\n }\n };\n\n window.addEventListener('storage', listener);\n return listener;\n}\nexport function removeStorageEventListener(listener) {\n window.removeEventListener('storage', listener);\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n\n if (!canBeUsed()) {\n throw new Error('BroadcastChannel: localstorage cannot be used');\n }\n\n var uuid = randomToken();\n /**\n * eMIs\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n\n var eMIs = new ObliviousSet(options.localstorage.removeTimeout);\n var state = {\n channelName: channelName,\n uuid: uuid,\n eMIs: eMIs // emittedMessagesIds\n\n };\n state.listener = addStorageEventListener(channelName, function (msgObj) {\n if (!state.messagesCallback) return; // no listener\n\n if (msgObj.uuid === uuid) return; // own message\n\n if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted\n\n if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old\n\n eMIs.add(msgObj.token);\n state.messagesCallback(msgObj.data);\n });\n return state;\n}\nexport function close(channelState) {\n removeStorageEventListener(channelState.listener);\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var ls = getLocalStorage();\n if (!ls) return false;\n\n try {\n var key = '__broadcastchannel_check';\n ls.setItem(key, 'works');\n ls.removeItem(key);\n } catch (e) {\n // Safari 10 in private mode will not allow write access to local\n // storage and fail with a QuotaExceededError. See\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes\n return false;\n }\n\n return true;\n}\nexport function averageResponseTime() {\n var defaultTime = 120;\n var userAgent = navigator.userAgent.toLowerCase();\n\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n // safari is much slower so this time is higher\n return defaultTime * 2;\n }\n\n return defaultTime;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import { microSeconds as micro } from '../util';\nexport var microSeconds = micro;\nexport var type = 'simulate';\nvar SIMULATE_CHANNELS = new Set();\nexport function create(channelName) {\n var state = {\n name: channelName,\n messagesCallback: null\n };\n SIMULATE_CHANNELS.add(state);\n return state;\n}\nexport function close(channelState) {\n SIMULATE_CHANNELS[\"delete\"](channelState);\n}\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n return setTimeout(function () {\n var channelArray = Array.from(SIMULATE_CHANNELS);\n channelArray.filter(function (channel) {\n return channel.name === channelState.name;\n }).filter(function (channel) {\n return channel !== channelState;\n }).filter(function (channel) {\n return !!channel.messagesCallback;\n }).forEach(function (channel) {\n return channel.messagesCallback(messageJson);\n });\n res();\n }, 5);\n });\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n return true;\n}\nexport function averageResponseTime() {\n return 5;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import NativeMethod from './methods/native.js';\nimport IndexeDbMethod from './methods/indexed-db.js';\nimport LocalstorageMethod from './methods/localstorage.js';\nimport SimulateMethod from './methods/simulate.js';\nimport { isNode } from './util'; // order is important\n\nvar METHODS = [NativeMethod, // fastest\nIndexeDbMethod, LocalstorageMethod];\n/**\n * The NodeMethod is loaded lazy\n * so it will not get bundled in browser-builds\n */\n\nif (isNode) {\n /**\n * we use the non-transpiled code for nodejs\n * because it runs faster\n */\n var NodeMethod = require('../../src/methods/' + // use this hack so that browserify and others\n // do not import the node-method by default\n // when bundling.\n 'node.js');\n /**\n * this will be false for webpackbuilds\n * which will shim the node-method with an empty object {}\n */\n\n\n if (typeof NodeMethod.canBeUsed === 'function') {\n METHODS.push(NodeMethod);\n }\n}\n\nexport function chooseMethod(options) {\n var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen\n\n if (options.type) {\n if (options.type === 'simulate') {\n // only use simulate-method if directly chosen\n return SimulateMethod;\n }\n\n var ret = chooseMethods.find(function (m) {\n return m.type === options.type;\n });\n if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;\n }\n /**\n * if no webworker support is needed,\n * remove idb from the list so that localstorage is been chosen\n */\n\n\n if (!options.webWorkerSupport && !isNode) {\n chooseMethods = chooseMethods.filter(function (m) {\n return m.type !== 'idb';\n });\n }\n\n var useMethod = chooseMethods.find(function (method) {\n return method.canBeUsed();\n });\n if (!useMethod) throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(function (m) {\n return m.type;\n })));else return useMethod;\n}","import { isPromise } from './util.js';\nimport { chooseMethod } from './method-chooser.js';\nimport { fillOptionsWithDefaults } from './options.js';\nexport var BroadcastChannel = function BroadcastChannel(name, options) {\n this.name = name;\n\n if (ENFORCED_OPTIONS) {\n options = ENFORCED_OPTIONS;\n }\n\n this.options = fillOptionsWithDefaults(options);\n this.method = chooseMethod(this.options); // isListening\n\n this._iL = false;\n /**\n * _onMessageListener\n * setting onmessage twice,\n * will overwrite the first listener\n */\n\n this._onML = null;\n /**\n * _addEventListeners\n */\n\n this._addEL = {\n message: [],\n internal: []\n };\n /**\n * Unsend message promises\n * where the sending is still in progress\n * @type {Set}\n */\n\n this._uMP = new Set();\n /**\n * _beforeClose\n * array of promises that will be awaited\n * before the channel is closed\n */\n\n this._befC = [];\n /**\n * _preparePromise\n */\n\n this._prepP = null;\n\n _prepareChannel(this);\n}; // STATICS\n\n/**\n * used to identify if someone overwrites\n * window.BroadcastChannel with this\n * See methods/native.js\n */\n\nBroadcastChannel._pubkey = true;\n/**\n * clears the tmp-folder if is node\n * @return {Promise} true if has run, false if not node\n */\n\nexport function clearNodeFolder(options) {\n options = fillOptionsWithDefaults(options);\n var method = chooseMethod(options);\n\n if (method.type === 'node') {\n return method.clearNodeFolder().then(function () {\n return true;\n });\n } else {\n return Promise.resolve(false);\n }\n}\n/**\n * if set, this method is enforced,\n * no mather what the options are\n */\n\nvar ENFORCED_OPTIONS;\nexport function enforceOptions(options) {\n ENFORCED_OPTIONS = options;\n} // PROTOTYPE\n\nBroadcastChannel.prototype = {\n postMessage: function postMessage(msg) {\n if (this.closed) {\n throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');\n }\n\n return _post(this, 'message', msg);\n },\n postInternal: function postInternal(msg) {\n return _post(this, 'internal', msg);\n },\n\n set onmessage(fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _removeListenerObject(this, 'message', this._onML);\n\n if (fn && typeof fn === 'function') {\n this._onML = listenObj;\n\n _addListenerObject(this, 'message', listenObj);\n } else {\n this._onML = null;\n }\n },\n\n addEventListener: function addEventListener(type, fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _addListenerObject(this, type, listenObj);\n },\n removeEventListener: function removeEventListener(type, fn) {\n var obj = this._addEL[type].find(function (obj) {\n return obj.fn === fn;\n });\n\n _removeListenerObject(this, type, obj);\n },\n close: function close() {\n var _this = this;\n\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();\n this._onML = null;\n this._addEL.message = [];\n return awaitPrepare // wait until all current sending are processed\n .then(function () {\n return Promise.all(Array.from(_this._uMP));\n }) // run before-close hooks\n .then(function () {\n return Promise.all(_this._befC.map(function (fn) {\n return fn();\n }));\n }) // close the channel\n .then(function () {\n return _this.method.close(_this._state);\n });\n },\n\n get type() {\n return this.method.type;\n },\n\n get isClosed() {\n return this.closed;\n }\n\n};\n/**\n * Post a message over the channel\n * @returns {Promise} that resolved when the message sending is done\n */\n\nfunction _post(broadcastChannel, type, msg) {\n var time = broadcastChannel.method.microSeconds();\n var msgObj = {\n time: time,\n type: type,\n data: msg\n };\n var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();\n return awaitPrepare.then(function () {\n var sendPromise = broadcastChannel.method.postMessage(broadcastChannel._state, msgObj); // add/remove to unsend messages list\n\n broadcastChannel._uMP.add(sendPromise);\n\n sendPromise[\"catch\"]().then(function () {\n return broadcastChannel._uMP[\"delete\"](sendPromise);\n });\n return sendPromise;\n });\n}\n\nfunction _prepareChannel(channel) {\n var maybePromise = channel.method.create(channel.name, channel.options);\n\n if (isPromise(maybePromise)) {\n channel._prepP = maybePromise;\n maybePromise.then(function (s) {\n // used in tests to simulate slow runtime\n\n /*if (channel.options.prepareDelay) {\n await new Promise(res => setTimeout(res, this.options.prepareDelay));\n }*/\n channel._state = s;\n });\n } else {\n channel._state = maybePromise;\n }\n}\n\nfunction _hasMessageListeners(channel) {\n if (channel._addEL.message.length > 0) return true;\n if (channel._addEL.internal.length > 0) return true;\n return false;\n}\n\nfunction _addListenerObject(channel, type, obj) {\n channel._addEL[type].push(obj);\n\n _startListening(channel);\n}\n\nfunction _removeListenerObject(channel, type, obj) {\n channel._addEL[type] = channel._addEL[type].filter(function (o) {\n return o !== obj;\n });\n\n _stopListening(channel);\n}\n\nfunction _startListening(channel) {\n if (!channel._iL && _hasMessageListeners(channel)) {\n // someone is listening, start subscribing\n var listenerFn = function listenerFn(msgObj) {\n channel._addEL[msgObj.type].forEach(function (obj) {\n if (msgObj.time >= obj.time) {\n obj.fn(msgObj.data);\n }\n });\n };\n\n var time = channel.method.microSeconds();\n\n if (channel._prepP) {\n channel._prepP.then(function () {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n });\n } else {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n }\n }\n}\n\nfunction _stopListening(channel) {\n if (channel._iL && !_hasMessageListeners(channel)) {\n // noone is listening, stop subscribing\n channel._iL = false;\n var time = channel.method.microSeconds();\n channel.method.onMessage(channel._state, null, time);\n }\n}","/* global WorkerGlobalScope */\nfunction add(fn) {\n if (typeof WorkerGlobalScope === 'function' && self instanceof WorkerGlobalScope) {// this is run inside of a webworker\n } else {\n /**\n * if we are on react-native, there is no window.addEventListener\n * @link https://github.com/pubkey/unload/issues/6\n */\n if (typeof window.addEventListener !== 'function') return;\n /**\n * for normal browser-windows, we use the beforeunload-event\n */\n\n window.addEventListener('beforeunload', function () {\n fn();\n }, true);\n /**\n * for iframes, we have to use the unload-event\n * @link https://stackoverflow.com/q/47533670/3443137\n */\n\n window.addEventListener('unload', function () {\n fn();\n }, true);\n }\n /**\n * TODO add fallback for safari-mobile\n * @link https://stackoverflow.com/a/26193516/3443137\n */\n\n}\n\nexport default {\n add: add\n};","import isNode from 'detect-node';\nimport BrowserMethod from './browser.js';\nimport NodeMethod from './node.js';\nvar USE_METHOD = isNode ? NodeMethod : BrowserMethod;\nvar LISTENERS = new Set();\nvar startedListening = false;\n\nfunction startListening() {\n if (startedListening) return;\n startedListening = true;\n USE_METHOD.add(runAll);\n}\n\nexport function add(fn) {\n startListening();\n if (typeof fn !== 'function') throw new Error('Listener is no function');\n LISTENERS.add(fn);\n var addReturn = {\n remove: function remove() {\n return LISTENERS[\"delete\"](fn);\n },\n run: function run() {\n LISTENERS[\"delete\"](fn);\n return fn();\n }\n };\n return addReturn;\n}\nexport function runAll() {\n var promises = [];\n LISTENERS.forEach(function (fn) {\n promises.push(fn());\n LISTENERS[\"delete\"](fn);\n });\n return Promise.all(promises);\n}\nexport function removeAll() {\n LISTENERS.clear();\n}\nexport function getSize() {\n return LISTENERS.size;\n}\nexport default {\n add: add,\n runAll: runAll,\n removeAll: removeAll,\n getSize: getSize\n};","import { sleep, randomToken } from './util.js';\nimport unload from 'unload';\n\nvar LeaderElection = function LeaderElection(channel, options) {\n this._channel = channel;\n this._options = options;\n this.isLeader = false;\n this.isDead = false;\n this.token = randomToken();\n this._isApl = false; // _isApplying\n\n this._reApply = false; // things to clean up\n\n this._unl = []; // _unloads\n\n this._lstns = []; // _listeners\n\n this._invs = []; // _intervals\n\n this._dpL = function () {}; // onduplicate listener\n\n\n this._dpLC = false; // true when onduplicate called\n};\n\nLeaderElection.prototype = {\n applyOnce: function applyOnce() {\n var _this = this;\n\n if (this.isLeader) return Promise.resolve(false);\n if (this.isDead) return Promise.resolve(false); // do nothing if already running\n\n if (this._isApl) {\n this._reApply = true;\n return Promise.resolve(false);\n }\n\n this._isApl = true;\n var stopCriteria = false;\n var recieved = [];\n\n var handleMessage = function handleMessage(msg) {\n if (msg.context === 'leader' && msg.token != _this.token) {\n recieved.push(msg);\n\n if (msg.action === 'apply') {\n // other is applying\n if (msg.token > _this.token) {\n // other has higher token, stop applying\n stopCriteria = true;\n }\n }\n\n if (msg.action === 'tell') {\n // other is already leader\n stopCriteria = true;\n }\n }\n };\n\n this._channel.addEventListener('internal', handleMessage);\n\n var ret = _sendMessage(this, 'apply') // send out that this one is applying\n .then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this, 'apply');\n }).then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this);\n }).then(function () {\n return beLeader(_this);\n }) // no one disagreed -> this one is now leader\n .then(function () {\n return true;\n })[\"catch\"](function () {\n return false;\n }) // apply not successfull\n .then(function (success) {\n _this._channel.removeEventListener('internal', handleMessage);\n\n _this._isApl = false;\n\n if (!success && _this._reApply) {\n _this._reApply = false;\n return _this.applyOnce();\n } else return success;\n });\n\n return ret;\n },\n awaitLeadership: function awaitLeadership() {\n if (\n /* _awaitLeadershipPromise */\n !this._aLP) {\n this._aLP = _awaitLeadershipOnce(this);\n }\n\n return this._aLP;\n },\n\n set onduplicate(fn) {\n this._dpL = fn;\n },\n\n die: function die() {\n var _this2 = this;\n\n if (this.isDead) return;\n this.isDead = true;\n\n this._lstns.forEach(function (listener) {\n return _this2._channel.removeEventListener('internal', listener);\n });\n\n this._invs.forEach(function (interval) {\n return clearInterval(interval);\n });\n\n this._unl.forEach(function (uFn) {\n uFn.remove();\n });\n\n return _sendMessage(this, 'death');\n }\n};\n\nfunction _awaitLeadershipOnce(leaderElector) {\n if (leaderElector.isLeader) return Promise.resolve();\n return new Promise(function (res) {\n var resolved = false;\n\n function finish() {\n if (resolved) {\n return;\n }\n\n resolved = true;\n clearInterval(interval);\n\n leaderElector._channel.removeEventListener('internal', whenDeathListener);\n\n res(true);\n } // try once now\n\n\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n }); // try on fallbackInterval\n\n var interval = setInterval(function () {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n }, leaderElector._options.fallbackInterval);\n\n leaderElector._invs.push(interval); // try when other leader dies\n\n\n var whenDeathListener = function whenDeathListener(msg) {\n if (msg.context === 'leader' && msg.action === 'death') {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) finish();\n });\n }\n };\n\n leaderElector._channel.addEventListener('internal', whenDeathListener);\n\n leaderElector._lstns.push(whenDeathListener);\n });\n}\n/**\n * sends and internal message over the broadcast-channel\n */\n\n\nfunction _sendMessage(leaderElector, action) {\n var msgJson = {\n context: 'leader',\n action: action,\n token: leaderElector.token\n };\n return leaderElector._channel.postInternal(msgJson);\n}\n\nexport function beLeader(leaderElector) {\n leaderElector.isLeader = true;\n var unloadFn = unload.add(function () {\n return leaderElector.die();\n });\n\n leaderElector._unl.push(unloadFn);\n\n var isLeaderListener = function isLeaderListener(msg) {\n if (msg.context === 'leader' && msg.action === 'apply') {\n _sendMessage(leaderElector, 'tell');\n }\n\n if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) {\n /**\n * another instance is also leader!\n * This can happen on rare events\n * like when the CPU is at 100% for long time\n * or the tabs are open very long and the browser throttles them.\n * @link https://github.com/pubkey/broadcast-channel/issues/414\n * @link https://github.com/pubkey/broadcast-channel/issues/385\n */\n leaderElector._dpLC = true;\n\n leaderElector._dpL(); // message the lib user so the app can handle the problem\n\n\n _sendMessage(leaderElector, 'tell'); // ensure other leader also knows the problem\n\n }\n };\n\n leaderElector._channel.addEventListener('internal', isLeaderListener);\n\n leaderElector._lstns.push(isLeaderListener);\n\n return _sendMessage(leaderElector, 'tell');\n}\n\nfunction fillOptionsWithDefaults(options, channel) {\n if (!options) options = {};\n options = JSON.parse(JSON.stringify(options));\n\n if (!options.fallbackInterval) {\n options.fallbackInterval = 3000;\n }\n\n if (!options.responseTime) {\n options.responseTime = channel.method.averageResponseTime(channel.options);\n }\n\n return options;\n}\n\nexport function createLeaderElection(channel, options) {\n if (channel._leaderElector) {\n throw new Error('BroadcastChannel already has a leader-elector');\n }\n\n options = fillOptionsWithDefaults(options, channel);\n var elector = new LeaderElection(channel, options);\n\n channel._befC.push(function () {\n return elector.die();\n });\n\n channel._leaderElector = elector;\n return elector;\n}"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/syncState.umd.min.js b/dist/syncState.umd.min.js index 9efcdfd..7a59228 100644 --- a/dist/syncState.umd.min.js +++ b/dist/syncState.umd.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t,n){"use strict";(function(e){function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise((function(t){return setTimeout(t,e)}))}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(){return Math.random().toString(36).substring(2)}n.d(t,"b",(function(){return r})),n.d(t,"f",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"c",(function(){return c})),n.d(t,"a",(function(){return l}));var s=0,u=0;function c(){var e=(new Date).getTime();return e===s?1e3*e+ ++u:(s=e,u=0,1e3*e)}var l="[object process]"===Object.prototype.toString.call(void 0!==e?e:0)}).call(this,n(4))},function(e,t){e.exports=!1},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initMessageListener=t.initStateWithPrevTab=t.withReduxStateSync=t.createReduxStateSync=t.createStateSyncMiddleware=t.INIT_MESSAGE_LISTENER=t.RECEIVE_INIT_STATE=t.SEND_INIT_STATE=t.GET_INIT_STATE=void 0,t.generateUuidForAction=h,t.isActionAllowed=p,t.isActionSynced=function(e){return!!e.$isSync},t.MessageListener=m;var r=n(6),o=0,i=t.GET_INIT_STATE="&_GET_INIT_STATE",a=t.SEND_INIT_STATE="&_SEND_INIT_STATE",s=t.RECEIVE_INIT_STATE="&_RECEIVE_INIT_STATE",u=t.INIT_MESSAGE_LISTENER="&_INIT_MESSAGE_LISTENER",c={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:void 0,prepareState:function(e){return e},receiveState:function(e){return e}};function l(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function d(){return""+l()+l()+"-"+l()+"-"+l()+"-"+l()+"-"+l()+l()+l()}var f=d();function h(e){var t=e;return t.$uuid=d(),t.$wuid=f,t}function p(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e.type)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e.type)>=0}),o}function m(e){var t=e.channel,n=e.dispatch,r=e.allowed,u=!1,c={};this.handleOnMessage=function(e){var t;e.$wuid!==f&&(e.type!==s&&e.$uuid&&e.$uuid!==o&&(e.type!==i||c[e.$wuid]?e.type!==a||c[e.$wuid]?r(e)&&(o=e.$uuid,n(Object.assign(e,{$isSync:!0}))):u||(u=!0,n((t=e.payload,{type:s,payload:t}))):(c[e.$wuid]=!0,n({type:a}))))},this.messageChannel=t,this.messageChannel.onmessage=this.handleOnMessage}t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,t=p(e),n=new r.BroadcastChannel(e.channel,e.broadcastChannelOption),s=e.prepareState||c.prepareState,u=null;return function(e){var r=e.getState,c=e.dispatch;return function(e){return function(l){if(u||(u=new m({channel:n,dispatch:c,allowed:t})),l&&!l.$uuid){var d=h(l);o=d.$uuid;try{if(l.type===a)return r()&&(d.payload=s(r()),n.postMessage(d)),e(l);(t(d)||l.type===i)&&n.postMessage(d)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(Object.assign(l,{$isSync:void 0!==l.$isSync&&l.$isSync}))}}}};var v=t.createReduxStateSync=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.receiveState;return function(n,r){var o=n;return r.type===s&&(o=t(n,r.payload)),e(o,r)}};t.withReduxStateSync=v,t.initStateWithPrevTab=function(e){(0,e.dispatch)({type:i})},t.initMessageListener=function(e){(0,e.dispatch)({type:u})}},function(e,t){var n,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=s(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d1)for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=45e3),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=12e4),void 0===t.node.useFastPath&&(t.node.useFastPath=!0),t}var u=r.c;function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e,t){var n=e.transaction("messages").objectStore("messages"),r=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return n.openCursor(e)}catch(e){return n.openCursor()}}()).onsuccess=function(n){var o=n.target.result;o?o.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time0||e._addEL.internal.length>0}function O(e,t,n){e._addEL[t].push(n),function(e){if(!e._iL&&C(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},n=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,n)})):(e._iL=!0,e.method.onMessage(e._state,t,n))}}(e)}function x(e,t,n){e._addEL[t]=e._addEL[t].filter((function(e){return e!==n})),function(e){if(e._iL&&!C(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}k._pubkey=!0,k.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return M(this,"message",e)},postInternal:function(e){return M(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};x(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,O(this,"message",t)):this._onML=null},addEventListener:function(e,t){O(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){x(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}};var A=n(1),j=n.n(A);var N={add:function(e){if("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope);else{if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",(function(){e()}),!0),window.addEventListener("unload",(function(){e()}),!0)}}},B=n(2),D=n.n(B),R=j.a?D.a:N,$=new Set,G=!1;function F(){var e=[];return $.forEach((function(t){e.push(t()),$.delete(t)})),Promise.all(e)}var J={add:function(e){if(G||(G=!0,R.add(F)),"function"!=typeof e)throw new Error("Listener is no function");return $.add(e),{remove:function(){return $.delete(e)},run:function(){return $.delete(e),e()}}},runAll:F,removeAll:function(){$.clear()},getSize:function(){return $.size}},U=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Object(r.e)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function W(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}function V(e){e.isLeader=!0;var t=J.add((function(){return e.die()}));e._unl.push(t);var n=function(t){"leader"===t.context&&"apply"===t.action&&W(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),W(e,"tell"))};return e._channel.addEventListener("internal",n),e._lstns.push(n),W(e,"tell")}function z(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(t,e);var n=new U(e,t);return e._befC.push((function(){return n.die()})),e._leaderElector=n,n}U.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,n=[],o=function(r){"leader"===r.context&&r.token!=e.token&&(n.push(r),"apply"===r.action&&r.token>e.token&&(t=!0),"tell"===r.action&&(t=!0))};return this._channel.addEventListener("internal",o),W(this,"apply").then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e,"apply")})).then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e)})).then((function(){return V(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",o),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var n=!1;function r(){n||(n=!0,clearInterval(o),e._channel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&r()}));var o=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&r()}))}),e._options.fallbackInterval);e._invs.push(o);var i=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&r()}))};e._channel.addEventListener("internal",i),e._lstns.push(i)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),W(this,"death")}}}])})); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t,n){"use strict";(function(e){function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise((function(t){return setTimeout(t,e)}))}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(){return Math.random().toString(36).substring(2)}n.d(t,"b",(function(){return r})),n.d(t,"f",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"c",(function(){return c})),n.d(t,"a",(function(){return l}));var s=0,u=0;function c(){var e=(new Date).getTime();return e===s?1e3*e+ ++u:(s=e,u=0,1e3*e)}var l="[object process]"===Object.prototype.toString.call(void 0!==e?e:0)}).call(this,n(4))},function(e,t){e.exports=!1},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initMessageListener=t.initStateWithPrevTab=t.withReduxStateSync=t.createReduxStateSync=t.createStateSyncMiddleware=t.INIT_MESSAGE_LISTENER=t.RECEIVE_INIT_STATE=t.SEND_INIT_STATE=t.GET_INIT_STATE=void 0,t.generateUuidForAction=h,t.isActionAllowed=p,t.isActionSynced=function(e){return!!e.$isSync},t.MessageListener=m;var r=n(6),o=0,i=t.GET_INIT_STATE="&_GET_INIT_STATE",a=t.SEND_INIT_STATE="&_SEND_INIT_STATE",s=t.RECEIVE_INIT_STATE="&_RECEIVE_INIT_STATE",u=t.INIT_MESSAGE_LISTENER="&_INIT_MESSAGE_LISTENER",c={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:void 0,prepareState:function(e){return e},receiveState:function(e,t){return t}};function l(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function d(){return""+l()+l()+"-"+l()+"-"+l()+"-"+l()+"-"+l()+l()+l()}var f=d();function h(e){var t=e;return t.$uuid=d(),t.$wuid=f,t}function p(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e.type)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e.type)>=0}),o}function m(e){var t=e.channel,n=e.dispatch,r=e.allowed,u=!1,c={};this.handleOnMessage=function(e){var t;e.$wuid!==f&&(e.type!==s&&e.$uuid&&e.$uuid!==o&&(e.type!==i||c[e.$wuid]?e.type!==a||c[e.$wuid]?r(e)&&(o=e.$uuid,n(Object.assign(e,{$isSync:!0}))):u||(u=!0,n((t=e.payload,{type:s,payload:t}))):(c[e.$wuid]=!0,n({type:a}))))},this.messageChannel=t,this.messageChannel.onmessage=this.handleOnMessage}t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:c,t=p(e),n=new r.BroadcastChannel(e.channel,e.broadcastChannelOption),s=e.prepareState||c.prepareState,u=null;return function(e){var r=e.getState,c=e.dispatch;return function(e){return function(l){if(u||(u=new m({channel:n,dispatch:c,allowed:t})),l&&!l.$uuid){var d=h(l);o=d.$uuid;try{if(l.type===a)return r()&&(d.payload=s(r()),n.postMessage(d)),e(l);(t(d)||l.type===i)&&n.postMessage(d)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(Object.assign(l,{$isSync:void 0!==l.$isSync&&l.$isSync}))}}}};var v=t.createReduxStateSync=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.receiveState;return function(n,r){var o=n;return r.type===s&&(o=t(n,r.payload)),e(o,r)}};t.withReduxStateSync=v,t.initStateWithPrevTab=function(e){(0,e.dispatch)({type:i})},t.initMessageListener=function(e){(0,e.dispatch)({type:u})}},function(e,t){var n,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,c=[],l=!1,d=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=s(f);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d1)for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return void 0===t.webWorkerSupport&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=45e3),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&"function"==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=12e4),void 0===t.node.useFastPath&&(t.node.useFastPath=!0),t}var u=r.c;function c(){if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return!1}function l(e,t){var n=e.transaction("messages").objectStore("messages"),r=[];return new Promise((function(e){(function(){try{var e=IDBKeyRange.bound(t+1,1/0);return n.openCursor(e)}catch(e){return n.openCursor()}}()).onsuccess=function(n){var o=n.target.result;o?o.value.ide.lastCursorId&&(e.lastCursorId=t.id),t})).filter((function(t){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time0||e._addEL.internal.length>0}function O(e,t,n){e._addEL[t].push(n),function(e){if(!e._iL&&C(e)){var t=function(t){e._addEL[t.type].forEach((function(e){t.time>=e.time&&e.fn(t.data)}))},n=e.method.microSeconds();e._prepP?e._prepP.then((function(){e._iL=!0,e.method.onMessage(e._state,t,n)})):(e._iL=!0,e.method.onMessage(e._state,t,n))}}(e)}function x(e,t,n){e._addEL[t]=e._addEL[t].filter((function(e){return e!==n})),function(e){if(e._iL&&!C(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}(e)}k._pubkey=!0,k.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return M(this,"message",e)},postInternal:function(e){return M(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};x(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,O(this,"message",t)):this._onML=null},addEventListener:function(e,t){O(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){x(this,e,this._addEL[e].find((function(e){return e.fn===t})))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(e){return e()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}};var A=n(1),j=n.n(A);var N={add:function(e){if("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope);else{if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",(function(){e()}),!0),window.addEventListener("unload",(function(){e()}),!0)}}},B=n(2),D=n.n(B),R=j.a?D.a:N,$=new Set,G=!1;function F(){var e=[];return $.forEach((function(t){e.push(t()),$.delete(t)})),Promise.all(e)}var J={add:function(e){if(G||(G=!0,R.add(F)),"function"!=typeof e)throw new Error("Listener is no function");return $.add(e),{remove:function(){return $.delete(e)},run:function(){return $.delete(e),e()}}},runAll:F,removeAll:function(){$.clear()},getSize:function(){return $.size}},U=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Object(r.e)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[],this._dpL=function(){},this._dpLC=!1};function W(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}function V(e){e.isLeader=!0;var t=J.add((function(){return e.die()}));e._unl.push(t);var n=function(t){"leader"===t.context&&"apply"===t.action&&W(e,"tell"),"leader"!==t.context||"tell"!==t.action||e._dpLC||(e._dpLC=!0,e._dpL(),W(e,"tell"))};return e._channel.addEventListener("internal",n),e._lstns.push(n),W(e,"tell")}function z(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(t,e);var n=new U(e,t);return e._befC.push((function(){return n.die()})),e._leaderElector=n,n}U.prototype={applyOnce:function(){var e=this;if(this.isLeader)return Promise.resolve(!1);if(this.isDead)return Promise.resolve(!1);if(this._isApl)return this._reApply=!0,Promise.resolve(!1);this._isApl=!0;var t=!1,n=[],o=function(r){"leader"===r.context&&r.token!=e.token&&(n.push(r),"apply"===r.action&&r.token>e.token&&(t=!0),"tell"===r.action&&(t=!0))};return this._channel.addEventListener("internal",o),W(this,"apply").then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e,"apply")})).then((function(){return Object(r.f)(e._options.responseTime)})).then((function(){return t?Promise.reject(new Error):W(e)})).then((function(){return V(e)})).then((function(){return!0})).catch((function(){return!1})).then((function(t){return e._channel.removeEventListener("internal",o),e._isApl=!1,!t&&e._reApply?(e._reApply=!1,e.applyOnce()):t}))},awaitLeadership:function(){var e;return this._aLP||(this._aLP=(e=this).isLeader?Promise.resolve():new Promise((function(t){var n=!1;function r(){n||(n=!0,clearInterval(o),e._channel.removeEventListener("internal",i),t(!0))}e.applyOnce().then((function(){e.isLeader&&r()}));var o=setInterval((function(){e.applyOnce().then((function(){e.isLeader&&r()}))}),e._options.fallbackInterval);e._invs.push(o);var i=function(t){"leader"===t.context&&"death"===t.action&&e.applyOnce().then((function(){e.isLeader&&r()}))};e._channel.addEventListener("internal",i),e._lstns.push(i)}))),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var e=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach((function(t){return e._channel.removeEventListener("internal",t)})),this._invs.forEach((function(e){return clearInterval(e)})),this._unl.forEach((function(e){e.remove()})),W(this,"death")}}}])})); //# sourceMappingURL=syncState.umd.min.js.map \ No newline at end of file diff --git a/dist/syncState.umd.min.js.map b/dist/syncState.umd.min.js.map index 91b00ed..74b19c6 100644 --- a/dist/syncState.umd.min.js.map +++ b/dist/syncState.umd.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://reduxStateSync/webpack/universalModuleDefinition","webpack://reduxStateSync/webpack/bootstrap","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/util.js","webpack://reduxStateSync/./node_modules/detect-node/browser.js","webpack://reduxStateSync/./src/syncState.js","webpack://reduxStateSync/./node_modules/process/browser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/native.js","webpack://reduxStateSync/./node_modules/oblivious-set/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/options.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/indexed-db.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/localstorage.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/simulate.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/method-chooser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/broadcast-channel.js","webpack://reduxStateSync/./node_modules/unload/dist/es/browser.js","webpack://reduxStateSync/./node_modules/unload/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/leader-election.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","isPromise","obj","then","sleep","time","Promise","res","setTimeout","randomInt","min","max","Math","floor","random","randomToken","toString","substring","lastMs","additional","microSeconds","ms","Date","getTime","isNode","process","generateUuidForAction","isActionAllowed","isActionSynced","action","$isSync","MessageListener","lastUuid","GET_INIT_STATE","SEND_INIT_STATE","RECEIVE_INIT_STATE","INIT_MESSAGE_LISTENER","defaultConfig","channel","predicate","blacklist","whitelist","broadcastChannelOption","undefined","prepareState","state","receiveState","s4","guid","WINDOW_STATE_SYNC_ID","stampedAction","$uuid","$wuid","allowed","Array","isArray","indexOf","type","dispatch","isSynced","tabs","this","handleOnMessage","assign","payload","messageChannel","onmessage","createStateSyncMiddleware","config","BroadcastChannel","messageListener","getState","next","postMessage","e","console","error","createReduxStateSync","appReducer","initState","withReduxStateSync","initStateWithPrevTab","initMessageListener","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","Error","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","channelName","messagesCallback","bc","subFns","msg","data","close","channelState","onMessage","fn","messageJson","resolve","err","reject","canBeUsed","_pubkey","averageResponseTime","ObliviousSet","ttl","set","Set","timeMap","Map","has","add","_this","now","obliviousSet","olderThen","iterator","delete","removeTooOldValues","clear","fillOptionsWithDefaults","originalOptions","options","JSON","parse","stringify","webWorkerSupport","idb","fallbackInterval","onclose","localstorage","removeTimeout","methods","node","useFastPath","getIdb","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","getMessagesHigherThan","db","lastCursorId","objectStore","transaction","ret","keyRangeValue","IDBKeyRange","bound","Infinity","openCursor","onsuccess","ev","cursor","target","result","id","cleanOldMessages","msgObk","getOldMessages","tooOld","all","map","msgObj","request","removeMessageById","readNewMessages","closed","newerMessages","filter","uuid","eMIs","messagesCallbackTime","_filterMessage","sort","msgObjA","msgObjB","forEach","dbName","openRequest","open","onupgradeneeded","createObjectStore","keyPath","autoIncrement","rej","onerror","createDatabase","writeBlockPromise","readQueuePromises","_readLoop","readerUuid","writeObject","oncomplete","writeMessage","getLocalStorage","localStorage","storageKey","ls","setItem","removeItem","listener","newValue","addEventListener","addStorageEventListener","token","removeEventListener","writeObj","document","createEvent","initEvent","dispatchEvent","userAgent","navigator","toLowerCase","includes","defaultTime","SIMULATE_CHANNELS","from","METHODS","NodeMethod","chooseMethod","chooseMethods","Boolean","find","useMethod","method","ENFORCED_OPTIONS","maybePromise","_iL","_onML","_addEL","message","internal","_uMP","_befC","_prepP","_state","clearNodeFolder","enforceOptions","_post","broadcastChannel","sendPromise","_hasMessageListeners","_addListenerObject","listenerFn","_startListening","_removeListenerObject","_stopListening","postInternal","listenObj","awaitPrepare","WorkerGlobalScope","self","USE_METHOD","LISTENERS","startedListening","runAll","promises","remove","removeAll","getSize","size","_channel","_options","isLeader","isDead","_isApl","_reApply","_unl","_lstns","_invs","_dpL","_dpLC","_sendMessage","leaderElector","msgJson","context","beLeader","unloadFn","die","isLeaderListener","createLeaderElection","_leaderElector","responseTime","elector","applyOnce","stopCriteria","recieved","handleMessage","success","awaitLeadership","_aLP","resolved","finish","clearInterval","interval","whenDeathListener","setInterval","_this2","uFn"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAwB,eAAID,IAE5BD,EAAqB,eAAIC,IAR3B,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAU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A2B9M,GAC7B,WAAhBA,EAAI0L,SAAuC,UAAf1L,EAAI5G,QAClCoS,EAAcW,YAAYzU,MAAK,WACzB8T,EAAcV,UAAU6B,QAKlCnB,EAAcZ,SAAS5D,iBAAiB,WAAY8F,GAEpDtB,EAAcL,OAAO9M,KAAKyO,OA3EnB1R,KAAKqR,MAGd,gBAAgBpM,GACdjF,KAAKiQ,KAAOhL,GAGdwL,IAAK,WACH,IAAImB,EAAS5R,KAEb,IAAIA,KAAK2P,OAeT,OAdA3P,KAAK2P,QAAS,EAEd3P,KAAK+P,OAAO7F,SAAQ,SAAUwB,GAC5B,OAAOkG,EAAOpC,SAASzD,oBAAoB,WAAYL,MAGzD1L,KAAKgQ,MAAM9F,SAAQ,SAAUuH,GAC3B,OAAOD,cAAcC,MAGvBzR,KAAK8P,KAAK5F,SAAQ,SAAU2H,GAC1BA,EAAIzC,YAGCe,EAAanQ,KAAM","file":"syncState.umd.min.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 if(typeof exports === 'object')\n\t\texports[\"reduxStateSync\"] = factory();\n\telse\n\t\troot[\"reduxStateSync\"] = factory();\n})(window, function() {\nreturn "," \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 \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\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.l = 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// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 3);\n","/**\n * returns true if the given object is a promise\n */\nexport function isPromise(obj) {\n if (obj && typeof obj.then === 'function') {\n return true;\n } else {\n return false;\n }\n}\nexport function sleep(time) {\n if (!time) time = 0;\n return new Promise(function (res) {\n return setTimeout(res, time);\n });\n}\nexport function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/**\n * https://stackoverflow.com/a/8084248\n */\n\nexport function randomToken() {\n return Math.random().toString(36).substring(2);\n}\nvar lastMs = 0;\nvar additional = 0;\n/**\n * returns the current time in micro-seconds,\n * WARNING: This is a pseudo-function\n * Performance.now is not reliable in webworkers, so we just make sure to never return the same time.\n * This is enough in browsers, and this function will not be used in nodejs.\n * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.\n */\n\nexport function microSeconds() {\n var ms = new Date().getTime();\n\n if (ms === lastMs) {\n additional++;\n return ms * 1000 + additional;\n } else {\n lastMs = ms;\n additional = 0;\n return ms * 1000;\n }\n}\n/**\n * copied from the 'detect-node' npm module\n * We cannot use the module directly because it causes problems with rollup\n * @link https://github.com/iliakan/detect-node/blob/master/index.js\n */\n\nexport var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';","module.exports = false;\n\n","import { BroadcastChannel } from 'broadcast-channel';\n\nlet lastUuid = 0;\nexport const GET_INIT_STATE = '&_GET_INIT_STATE';\nexport const SEND_INIT_STATE = '&_SEND_INIT_STATE';\nexport const RECEIVE_INIT_STATE = '&_RECEIVE_INIT_STATE';\nexport const INIT_MESSAGE_LISTENER = '&_INIT_MESSAGE_LISTENER';\n\nconst defaultConfig = {\n channel: 'redux_state_sync',\n predicate: null,\n blacklist: [],\n whitelist: [],\n broadcastChannelOption: undefined,\n prepareState: state => state,\n receiveState: state => state,\n};\n\nconst getIniteState = () => ({ type: GET_INIT_STATE });\nconst sendIniteState = () => ({ type: SEND_INIT_STATE });\nconst receiveIniteState = state => ({ type: RECEIVE_INIT_STATE, payload: state });\nconst initListener = () => ({ type: INIT_MESSAGE_LISTENER });\n\nfunction s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n}\n\nfunction guid() {\n return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;\n}\n\n// generate current window unique id\nconst WINDOW_STATE_SYNC_ID = guid();\n// export for test\nexport function generateUuidForAction(action) {\n const stampedAction = action;\n stampedAction.$uuid = guid();\n stampedAction.$wuid = WINDOW_STATE_SYNC_ID;\n return stampedAction;\n}\n// export for test\nexport function isActionAllowed({ predicate, blacklist, whitelist }) {\n let allowed = () => true;\n\n if (predicate && typeof predicate === 'function') {\n allowed = predicate;\n } else if (Array.isArray(blacklist)) {\n allowed = action => blacklist.indexOf(action.type) < 0;\n } else if (Array.isArray(whitelist)) {\n allowed = action => whitelist.indexOf(action.type) >= 0;\n }\n return allowed;\n}\n// export for test\nexport function isActionSynced(action) {\n return !!action.$isSync;\n}\n// export for test\nexport function MessageListener({ channel, dispatch, allowed }) {\n let isSynced = false;\n const tabs = {};\n this.handleOnMessage = stampedAction => {\n // Ignore if this action is triggered by this window\n if (stampedAction.$wuid === WINDOW_STATE_SYNC_ID) {\n return;\n }\n // IE bug https://stackoverflow.com/questions/18265556/why-does-internet-explorer-fire-the-window-storage-event-on-the-window-that-st\n if (stampedAction.type === RECEIVE_INIT_STATE) {\n return;\n }\n // ignore other values that saved to localstorage.\n if (stampedAction.$uuid && stampedAction.$uuid !== lastUuid) {\n if (stampedAction.type === GET_INIT_STATE && !tabs[stampedAction.$wuid]) {\n tabs[stampedAction.$wuid] = true;\n dispatch(sendIniteState());\n } else if (stampedAction.type === SEND_INIT_STATE && !tabs[stampedAction.$wuid]) {\n if (!isSynced) {\n isSynced = true;\n dispatch(receiveIniteState(stampedAction.payload));\n }\n } else if (allowed(stampedAction)) {\n lastUuid = stampedAction.$uuid;\n dispatch(\n Object.assign(stampedAction, {\n $isSync: true,\n }),\n );\n }\n }\n };\n this.messageChannel = channel;\n this.messageChannel.onmessage = this.handleOnMessage;\n}\n\nexport const createStateSyncMiddleware = (config = defaultConfig) => {\n const allowed = isActionAllowed(config);\n const channel = new BroadcastChannel(config.channel, config.broadcastChannelOption);\n const prepareState = config.prepareState || defaultConfig.prepareState;\n let messageListener = null;\n\n return ({ getState, dispatch }) => next => action => {\n // create message receiver\n if (!messageListener) {\n messageListener = new MessageListener({ channel, dispatch, allowed });\n }\n // post messages\n if (action && !action.$uuid) {\n const stampedAction = generateUuidForAction(action);\n lastUuid = stampedAction.$uuid;\n try {\n if (action.type === SEND_INIT_STATE) {\n if (getState()) {\n stampedAction.payload = prepareState(getState());\n channel.postMessage(stampedAction);\n }\n return next(action);\n }\n if (allowed(stampedAction) || action.type === GET_INIT_STATE) {\n channel.postMessage(stampedAction);\n }\n } catch (e) {\n console.error(\"Your browser doesn't support cross tab communication\");\n }\n }\n return next(\n Object.assign(action, {\n $isSync: typeof action.$isSync === 'undefined' ? false : action.$isSync,\n }),\n );\n };\n};\n\n// eslint-disable-next-line max-len\nexport const createReduxStateSync = (appReducer, receiveState = defaultConfig.receiveState) => (state, action) => {\n let initState = state;\n if (action.type === RECEIVE_INIT_STATE) {\n initState = receiveState(state, action.payload);\n }\n return appReducer(initState, action);\n};\n\n// init state with other tab's state\nexport const withReduxStateSync = createReduxStateSync;\n\nexport const initStateWithPrevTab = ({ dispatch }) => {\n dispatch(getIniteState());\n};\n\n/*\nif don't dispath any action, the store.dispath will not be available for message listener.\ntherefor need to trigger an empty action to init the messageListener.\n\nhowever, if already using initStateWithPrevTab, this function will be redundant\n*/\nexport const initMessageListener = ({ dispatch }) => {\n dispatch(initListener());\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import { microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nexport var type = 'native';\nexport function create(channelName) {\n var state = {\n messagesCallback: null,\n bc: new BroadcastChannel(channelName),\n subFns: [] // subscriberFunctions\n\n };\n\n state.bc.onmessage = function (msg) {\n if (state.messagesCallback) {\n state.messagesCallback(msg.data);\n }\n };\n\n return state;\n}\nexport function close(channelState) {\n channelState.bc.close();\n channelState.subFns = [];\n}\nexport function postMessage(channelState, messageJson) {\n try {\n channelState.bc.postMessage(messageJson, false);\n return Promise.resolve();\n } catch (err) {\n return Promise.reject(err);\n }\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n /**\n * in the electron-renderer, isNode will be true even if we are in browser-context\n * so we also check if window is undefined\n */\n if (isNode && typeof window === 'undefined') return false;\n\n if (typeof BroadcastChannel === 'function') {\n if (BroadcastChannel._pubkey) {\n throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');\n }\n\n return true;\n } else return false;\n}\nexport function averageResponseTime() {\n return 150;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * this is a set which automatically forgets\n * a given entry when a new entry is set and the ttl\n * of the old one is over\n */\nvar ObliviousSet = /** @class */ (function () {\n function ObliviousSet(ttl) {\n this.ttl = ttl;\n this.set = new Set();\n this.timeMap = new Map();\n }\n ObliviousSet.prototype.has = function (value) {\n return this.set.has(value);\n };\n ObliviousSet.prototype.add = function (value) {\n var _this = this;\n this.timeMap.set(value, now());\n this.set.add(value);\n /**\n * When a new value is added,\n * start the cleanup at the next tick\n * to not block the cpu for more important stuff\n * that might happen.\n */\n setTimeout(function () {\n removeTooOldValues(_this);\n }, 0);\n };\n ObliviousSet.prototype.clear = function () {\n this.set.clear();\n this.timeMap.clear();\n };\n return ObliviousSet;\n}());\nexport { ObliviousSet };\n/**\n * Removes all entries from the set\n * where the TTL has expired\n */\nexport function removeTooOldValues(obliviousSet) {\n var olderThen = now() - obliviousSet.ttl;\n var iterator = obliviousSet.set[Symbol.iterator]();\n /**\n * Because we can assume the new values are added at the bottom,\n * we start from the top and stop as soon as we reach a non-too-old value.\n */\n while (true) {\n var value = iterator.next().value;\n if (!value) {\n return; // no more elements\n }\n var time = obliviousSet.timeMap.get(value);\n if (time < olderThen) {\n obliviousSet.timeMap.delete(value);\n obliviousSet.set.delete(value);\n }\n else {\n // We reached a value that is not old enough\n return;\n }\n }\n}\nexport function now() {\n return new Date().getTime();\n}\n//# sourceMappingURL=index.js.map","export function fillOptionsWithDefaults() {\n var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = JSON.parse(JSON.stringify(originalOptions)); // main\n\n if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; // indexed-db\n\n if (!options.idb) options.idb = {}; // after this time the messages get deleted\n\n if (!options.idb.ttl) options.idb.ttl = 1000 * 45;\n if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; // handles abrupt db onclose events.\n\n if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose; // localstorage\n\n if (!options.localstorage) options.localstorage = {};\n if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; // custom methods\n\n if (originalOptions.methods) options.methods = originalOptions.methods; // node\n\n if (!options.node) options.node = {};\n if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;\n\n if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;\n return options;\n}","/**\n * this method uses indexeddb to store the messages\n * There is currently no observerAPI for idb\n * @link https://github.com/w3c/IndexedDB/issues/51\n */\nimport { sleep, randomInt, randomToken, microSeconds as micro, isNode } from '../util.js';\nexport var microSeconds = micro;\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nvar DB_PREFIX = 'pubkey.broadcast-channel-0-';\nvar OBJECT_STORE_ID = 'messages';\nexport var type = 'idb';\nexport function getIdb() {\n if (typeof indexedDB !== 'undefined') return indexedDB;\n\n if (typeof window !== 'undefined') {\n if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;\n if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;\n if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;\n }\n\n return false;\n}\nexport function createDatabase(channelName) {\n var IndexedDB = getIdb(); // create table\n\n var dbName = DB_PREFIX + channelName;\n var openRequest = IndexedDB.open(dbName, 1);\n\n openRequest.onupgradeneeded = function (ev) {\n var db = ev.target.result;\n db.createObjectStore(OBJECT_STORE_ID, {\n keyPath: 'id',\n autoIncrement: true\n });\n };\n\n var dbPromise = new Promise(function (res, rej) {\n openRequest.onerror = function (ev) {\n return rej(ev);\n };\n\n openRequest.onsuccess = function () {\n res(openRequest.result);\n };\n });\n return dbPromise;\n}\n/**\n * writes the new message to the database\n * so other readers can find it\n */\n\nexport function writeMessage(db, readerUuid, messageJson) {\n var time = new Date().getTime();\n var writeObject = {\n uuid: readerUuid,\n time: time,\n data: messageJson\n };\n var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');\n return new Promise(function (res, rej) {\n transaction.oncomplete = function () {\n return res();\n };\n\n transaction.onerror = function (ev) {\n return rej(ev);\n };\n\n var objectStore = transaction.objectStore(OBJECT_STORE_ID);\n objectStore.add(writeObject);\n });\n}\nexport function getAllMessages(db) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n ret.push(cursor.value); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n res(ret);\n }\n };\n });\n}\nexport function getMessagesHigherThan(db, lastCursorId) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n\n function openCursor() {\n // Occasionally Safari will fail on IDBKeyRange.bound, this\n // catches that error, having it open the cursor to the first\n // item. When it gets data it will advance to the desired key.\n try {\n var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n return objectStore.openCursor(keyRangeValue);\n } catch (e) {\n return objectStore.openCursor();\n }\n }\n\n return new Promise(function (res) {\n openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n if (cursor.value.id < lastCursorId + 1) {\n cursor[\"continue\"](lastCursorId + 1);\n } else {\n ret.push(cursor.value);\n cursor[\"continue\"]();\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function removeMessageById(db, id) {\n var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)[\"delete\"](id);\n return new Promise(function (res) {\n request.onsuccess = function () {\n return res();\n };\n });\n}\nexport function getOldMessages(db, ttl) {\n var olderThen = new Date().getTime() - ttl;\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n var msgObk = cursor.value;\n\n if (msgObk.time < olderThen) {\n ret.push(msgObk); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n // no more old messages,\n res(ret);\n return;\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function cleanOldMessages(db, ttl) {\n return getOldMessages(db, ttl).then(function (tooOld) {\n return Promise.all(tooOld.map(function (msgObj) {\n return removeMessageById(db, msgObj.id);\n }));\n });\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n return createDatabase(channelName).then(function (db) {\n var state = {\n closed: false,\n lastCursorId: 0,\n channelName: channelName,\n options: options,\n uuid: randomToken(),\n\n /**\n * emittedMessagesIds\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n eMIs: new ObliviousSet(options.idb.ttl * 2),\n // ensures we do not read messages in parrallel\n writeBlockPromise: Promise.resolve(),\n messagesCallback: null,\n readQueuePromises: [],\n db: db\n };\n /**\n * Handle abrupt closes that do not originate from db.close().\n * This could happen, for example, if the underlying storage is\n * removed or if the user clears the database in the browser's\n * history preferences.\n */\n\n db.onclose = function () {\n state.closed = true;\n if (options.idb.onclose) options.idb.onclose();\n };\n /**\n * if service-workers are used,\n * we have no 'storage'-event if they post a message,\n * therefore we also have to set an interval\n */\n\n\n _readLoop(state);\n\n return state;\n });\n}\n\nfunction _readLoop(state) {\n if (state.closed) return;\n readNewMessages(state).then(function () {\n return sleep(state.options.idb.fallbackInterval);\n }).then(function () {\n return _readLoop(state);\n });\n}\n\nfunction _filterMessage(msgObj, state) {\n if (msgObj.uuid === state.uuid) return false; // send by own\n\n if (state.eMIs.has(msgObj.id)) return false; // already emitted\n\n if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback\n\n return true;\n}\n/**\n * reads all new messages from the database and emits them\n */\n\n\nfunction readNewMessages(state) {\n // channel already closed\n if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages\n\n if (!state.messagesCallback) return Promise.resolve();\n return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {\n var useMessages = newerMessages\n /**\n * there is a bug in iOS where the msgObj can be undefined some times\n * so we filter them out\n * @link https://github.com/pubkey/broadcast-channel/issues/19\n */\n .filter(function (msgObj) {\n return !!msgObj;\n }).map(function (msgObj) {\n if (msgObj.id > state.lastCursorId) {\n state.lastCursorId = msgObj.id;\n }\n\n return msgObj;\n }).filter(function (msgObj) {\n return _filterMessage(msgObj, state);\n }).sort(function (msgObjA, msgObjB) {\n return msgObjA.time - msgObjB.time;\n }); // sort by time\n\n useMessages.forEach(function (msgObj) {\n if (state.messagesCallback) {\n state.eMIs.add(msgObj.id);\n state.messagesCallback(msgObj.data);\n }\n });\n return Promise.resolve();\n });\n}\n\nexport function close(channelState) {\n channelState.closed = true;\n channelState.db.close();\n}\nexport function postMessage(channelState, messageJson) {\n channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {\n return writeMessage(channelState.db, channelState.uuid, messageJson);\n }).then(function () {\n if (randomInt(0, 10) === 0) {\n /* await (do not await) */\n cleanOldMessages(channelState.db, channelState.options.idb.ttl);\n }\n });\n return channelState.writeBlockPromise;\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n readNewMessages(channelState);\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var idb = getIdb();\n if (!idb) return false;\n return true;\n}\nexport function averageResponseTime(options) {\n return options.idb.fallbackInterval * 2;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * A localStorage-only method which uses localstorage and its 'storage'-event\n * This does not work inside of webworkers because they have no access to locastorage\n * This is basically implemented to support IE9 or your grandmothers toaster.\n * @link https://caniuse.com/#feat=namevalue-storage\n * @link https://caniuse.com/#feat=indexeddb\n */\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nimport { sleep, randomToken, microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nvar KEY_PREFIX = 'pubkey.broadcastChannel-';\nexport var type = 'localstorage';\n/**\n * copied from crosstab\n * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32\n */\n\nexport function getLocalStorage() {\n var localStorage;\n if (typeof window === 'undefined') return null;\n\n try {\n localStorage = window.localStorage;\n localStorage = window['ie8-eventlistener/storage'] || window.localStorage;\n } catch (e) {// New versions of Firefox throw a Security exception\n // if cookies are disabled. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153\n }\n\n return localStorage;\n}\nexport function storageKey(channelName) {\n return KEY_PREFIX + channelName;\n}\n/**\n* writes the new message to the storage\n* and fires the storage-event so other readers can find it\n*/\n\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n sleep().then(function () {\n var key = storageKey(channelState.channelName);\n var writeObj = {\n token: randomToken(),\n time: new Date().getTime(),\n data: messageJson,\n uuid: channelState.uuid\n };\n var value = JSON.stringify(writeObj);\n getLocalStorage().setItem(key, value);\n /**\n * StorageEvent does not fire the 'storage' event\n * in the window that changes the state of the local storage.\n * So we fire it manually\n */\n\n var ev = document.createEvent('Event');\n ev.initEvent('storage', true, true);\n ev.key = key;\n ev.newValue = value;\n window.dispatchEvent(ev);\n res();\n });\n });\n}\nexport function addStorageEventListener(channelName, fn) {\n var key = storageKey(channelName);\n\n var listener = function listener(ev) {\n if (ev.key === key) {\n fn(JSON.parse(ev.newValue));\n }\n };\n\n window.addEventListener('storage', listener);\n return listener;\n}\nexport function removeStorageEventListener(listener) {\n window.removeEventListener('storage', listener);\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n\n if (!canBeUsed()) {\n throw new Error('BroadcastChannel: localstorage cannot be used');\n }\n\n var uuid = randomToken();\n /**\n * eMIs\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n\n var eMIs = new ObliviousSet(options.localstorage.removeTimeout);\n var state = {\n channelName: channelName,\n uuid: uuid,\n eMIs: eMIs // emittedMessagesIds\n\n };\n state.listener = addStorageEventListener(channelName, function (msgObj) {\n if (!state.messagesCallback) return; // no listener\n\n if (msgObj.uuid === uuid) return; // own message\n\n if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted\n\n if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old\n\n eMIs.add(msgObj.token);\n state.messagesCallback(msgObj.data);\n });\n return state;\n}\nexport function close(channelState) {\n removeStorageEventListener(channelState.listener);\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var ls = getLocalStorage();\n if (!ls) return false;\n\n try {\n var key = '__broadcastchannel_check';\n ls.setItem(key, 'works');\n ls.removeItem(key);\n } catch (e) {\n // Safari 10 in private mode will not allow write access to local\n // storage and fail with a QuotaExceededError. See\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes\n return false;\n }\n\n return true;\n}\nexport function averageResponseTime() {\n var defaultTime = 120;\n var userAgent = navigator.userAgent.toLowerCase();\n\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n // safari is much slower so this time is higher\n return defaultTime * 2;\n }\n\n return defaultTime;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import { microSeconds as micro } from '../util';\nexport var microSeconds = micro;\nexport var type = 'simulate';\nvar SIMULATE_CHANNELS = new Set();\nexport function create(channelName) {\n var state = {\n name: channelName,\n messagesCallback: null\n };\n SIMULATE_CHANNELS.add(state);\n return state;\n}\nexport function close(channelState) {\n SIMULATE_CHANNELS[\"delete\"](channelState);\n}\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n return setTimeout(function () {\n var channelArray = Array.from(SIMULATE_CHANNELS);\n channelArray.filter(function (channel) {\n return channel.name === channelState.name;\n }).filter(function (channel) {\n return channel !== channelState;\n }).filter(function (channel) {\n return !!channel.messagesCallback;\n }).forEach(function (channel) {\n return channel.messagesCallback(messageJson);\n });\n res();\n }, 5);\n });\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n return true;\n}\nexport function averageResponseTime() {\n return 5;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import NativeMethod from './methods/native.js';\nimport IndexeDbMethod from './methods/indexed-db.js';\nimport LocalstorageMethod from './methods/localstorage.js';\nimport SimulateMethod from './methods/simulate.js';\nimport { isNode } from './util'; // order is important\n\nvar METHODS = [NativeMethod, // fastest\nIndexeDbMethod, LocalstorageMethod];\n/**\n * The NodeMethod is loaded lazy\n * so it will not get bundled in browser-builds\n */\n\nif (isNode) {\n /**\n * we use the non-transpiled code for nodejs\n * because it runs faster\n */\n var NodeMethod = require('../../src/methods/' + // use this hack so that browserify and others\n // do not import the node-method by default\n // when bundling.\n 'node.js');\n /**\n * this will be false for webpackbuilds\n * which will shim the node-method with an empty object {}\n */\n\n\n if (typeof NodeMethod.canBeUsed === 'function') {\n METHODS.push(NodeMethod);\n }\n}\n\nexport function chooseMethod(options) {\n var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen\n\n if (options.type) {\n if (options.type === 'simulate') {\n // only use simulate-method if directly chosen\n return SimulateMethod;\n }\n\n var ret = chooseMethods.find(function (m) {\n return m.type === options.type;\n });\n if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;\n }\n /**\n * if no webworker support is needed,\n * remove idb from the list so that localstorage is been chosen\n */\n\n\n if (!options.webWorkerSupport && !isNode) {\n chooseMethods = chooseMethods.filter(function (m) {\n return m.type !== 'idb';\n });\n }\n\n var useMethod = chooseMethods.find(function (method) {\n return method.canBeUsed();\n });\n if (!useMethod) throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(function (m) {\n return m.type;\n })));else return useMethod;\n}","import { isPromise } from './util.js';\nimport { chooseMethod } from './method-chooser.js';\nimport { fillOptionsWithDefaults } from './options.js';\nexport var BroadcastChannel = function BroadcastChannel(name, options) {\n this.name = name;\n\n if (ENFORCED_OPTIONS) {\n options = ENFORCED_OPTIONS;\n }\n\n this.options = fillOptionsWithDefaults(options);\n this.method = chooseMethod(this.options); // isListening\n\n this._iL = false;\n /**\n * _onMessageListener\n * setting onmessage twice,\n * will overwrite the first listener\n */\n\n this._onML = null;\n /**\n * _addEventListeners\n */\n\n this._addEL = {\n message: [],\n internal: []\n };\n /**\n * Unsend message promises\n * where the sending is still in progress\n * @type {Set}\n */\n\n this._uMP = new Set();\n /**\n * _beforeClose\n * array of promises that will be awaited\n * before the channel is closed\n */\n\n this._befC = [];\n /**\n * _preparePromise\n */\n\n this._prepP = null;\n\n _prepareChannel(this);\n}; // STATICS\n\n/**\n * used to identify if someone overwrites\n * window.BroadcastChannel with this\n * See methods/native.js\n */\n\nBroadcastChannel._pubkey = true;\n/**\n * clears the tmp-folder if is node\n * @return {Promise} true if has run, false if not node\n */\n\nexport function clearNodeFolder(options) {\n options = fillOptionsWithDefaults(options);\n var method = chooseMethod(options);\n\n if (method.type === 'node') {\n return method.clearNodeFolder().then(function () {\n return true;\n });\n } else {\n return Promise.resolve(false);\n }\n}\n/**\n * if set, this method is enforced,\n * no mather what the options are\n */\n\nvar ENFORCED_OPTIONS;\nexport function enforceOptions(options) {\n ENFORCED_OPTIONS = options;\n} // PROTOTYPE\n\nBroadcastChannel.prototype = {\n postMessage: function postMessage(msg) {\n if (this.closed) {\n throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');\n }\n\n return _post(this, 'message', msg);\n },\n postInternal: function postInternal(msg) {\n return _post(this, 'internal', msg);\n },\n\n set onmessage(fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _removeListenerObject(this, 'message', this._onML);\n\n if (fn && typeof fn === 'function') {\n this._onML = listenObj;\n\n _addListenerObject(this, 'message', listenObj);\n } else {\n this._onML = null;\n }\n },\n\n addEventListener: function addEventListener(type, fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _addListenerObject(this, type, listenObj);\n },\n removeEventListener: function removeEventListener(type, fn) {\n var obj = this._addEL[type].find(function (obj) {\n return obj.fn === fn;\n });\n\n _removeListenerObject(this, type, obj);\n },\n close: function close() {\n var _this = this;\n\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();\n this._onML = null;\n this._addEL.message = [];\n return awaitPrepare // wait until all current sending are processed\n .then(function () {\n return Promise.all(Array.from(_this._uMP));\n }) // run before-close hooks\n .then(function () {\n return Promise.all(_this._befC.map(function (fn) {\n return fn();\n }));\n }) // close the channel\n .then(function () {\n return _this.method.close(_this._state);\n });\n },\n\n get type() {\n return this.method.type;\n },\n\n get isClosed() {\n return this.closed;\n }\n\n};\n/**\n * Post a message over the channel\n * @returns {Promise} that resolved when the message sending is done\n */\n\nfunction _post(broadcastChannel, type, msg) {\n var time = broadcastChannel.method.microSeconds();\n var msgObj = {\n time: time,\n type: type,\n data: msg\n };\n var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();\n return awaitPrepare.then(function () {\n var sendPromise = broadcastChannel.method.postMessage(broadcastChannel._state, msgObj); // add/remove to unsend messages list\n\n broadcastChannel._uMP.add(sendPromise);\n\n sendPromise[\"catch\"]().then(function () {\n return broadcastChannel._uMP[\"delete\"](sendPromise);\n });\n return sendPromise;\n });\n}\n\nfunction _prepareChannel(channel) {\n var maybePromise = channel.method.create(channel.name, channel.options);\n\n if (isPromise(maybePromise)) {\n channel._prepP = maybePromise;\n maybePromise.then(function (s) {\n // used in tests to simulate slow runtime\n\n /*if (channel.options.prepareDelay) {\n await new Promise(res => setTimeout(res, this.options.prepareDelay));\n }*/\n channel._state = s;\n });\n } else {\n channel._state = maybePromise;\n }\n}\n\nfunction _hasMessageListeners(channel) {\n if (channel._addEL.message.length > 0) return true;\n if (channel._addEL.internal.length > 0) return true;\n return false;\n}\n\nfunction _addListenerObject(channel, type, obj) {\n channel._addEL[type].push(obj);\n\n _startListening(channel);\n}\n\nfunction _removeListenerObject(channel, type, obj) {\n channel._addEL[type] = channel._addEL[type].filter(function (o) {\n return o !== obj;\n });\n\n _stopListening(channel);\n}\n\nfunction _startListening(channel) {\n if (!channel._iL && _hasMessageListeners(channel)) {\n // someone is listening, start subscribing\n var listenerFn = function listenerFn(msgObj) {\n channel._addEL[msgObj.type].forEach(function (obj) {\n if (msgObj.time >= obj.time) {\n obj.fn(msgObj.data);\n }\n });\n };\n\n var time = channel.method.microSeconds();\n\n if (channel._prepP) {\n channel._prepP.then(function () {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n });\n } else {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n }\n }\n}\n\nfunction _stopListening(channel) {\n if (channel._iL && !_hasMessageListeners(channel)) {\n // noone is listening, stop subscribing\n channel._iL = false;\n var time = channel.method.microSeconds();\n channel.method.onMessage(channel._state, null, time);\n }\n}","/* global WorkerGlobalScope */\nfunction add(fn) {\n if (typeof WorkerGlobalScope === 'function' && self instanceof WorkerGlobalScope) {// this is run inside of a webworker\n } else {\n /**\n * if we are on react-native, there is no window.addEventListener\n * @link https://github.com/pubkey/unload/issues/6\n */\n if (typeof window.addEventListener !== 'function') return;\n /**\n * for normal browser-windows, we use the beforeunload-event\n */\n\n window.addEventListener('beforeunload', function () {\n fn();\n }, true);\n /**\n * for iframes, we have to use the unload-event\n * @link https://stackoverflow.com/q/47533670/3443137\n */\n\n window.addEventListener('unload', function () {\n fn();\n }, true);\n }\n /**\n * TODO add fallback for safari-mobile\n * @link https://stackoverflow.com/a/26193516/3443137\n */\n\n}\n\nexport default {\n add: add\n};","import isNode from 'detect-node';\nimport BrowserMethod from './browser.js';\nimport NodeMethod from './node.js';\nvar USE_METHOD = isNode ? NodeMethod : BrowserMethod;\nvar LISTENERS = new Set();\nvar startedListening = false;\n\nfunction startListening() {\n if (startedListening) return;\n startedListening = true;\n USE_METHOD.add(runAll);\n}\n\nexport function add(fn) {\n startListening();\n if (typeof fn !== 'function') throw new Error('Listener is no function');\n LISTENERS.add(fn);\n var addReturn = {\n remove: function remove() {\n return LISTENERS[\"delete\"](fn);\n },\n run: function run() {\n LISTENERS[\"delete\"](fn);\n return fn();\n }\n };\n return addReturn;\n}\nexport function runAll() {\n var promises = [];\n LISTENERS.forEach(function (fn) {\n promises.push(fn());\n LISTENERS[\"delete\"](fn);\n });\n return Promise.all(promises);\n}\nexport function removeAll() {\n LISTENERS.clear();\n}\nexport function getSize() {\n return LISTENERS.size;\n}\nexport default {\n add: add,\n runAll: runAll,\n removeAll: removeAll,\n getSize: getSize\n};","import { sleep, randomToken } from './util.js';\nimport unload from 'unload';\n\nvar LeaderElection = function LeaderElection(channel, options) {\n this._channel = channel;\n this._options = options;\n this.isLeader = false;\n this.isDead = false;\n this.token = randomToken();\n this._isApl = false; // _isApplying\n\n this._reApply = false; // things to clean up\n\n this._unl = []; // _unloads\n\n this._lstns = []; // _listeners\n\n this._invs = []; // _intervals\n\n this._dpL = function () {}; // onduplicate listener\n\n\n this._dpLC = false; // true when onduplicate called\n};\n\nLeaderElection.prototype = {\n applyOnce: function applyOnce() {\n var _this = this;\n\n if (this.isLeader) return Promise.resolve(false);\n if (this.isDead) return Promise.resolve(false); // do nothing if already running\n\n if (this._isApl) {\n this._reApply = true;\n return Promise.resolve(false);\n }\n\n this._isApl = true;\n var stopCriteria = false;\n var recieved = [];\n\n var handleMessage = function handleMessage(msg) {\n if (msg.context === 'leader' && msg.token != _this.token) {\n recieved.push(msg);\n\n if (msg.action === 'apply') {\n // other is applying\n if (msg.token > _this.token) {\n // other has higher token, stop applying\n stopCriteria = true;\n }\n }\n\n if (msg.action === 'tell') {\n // other is already leader\n stopCriteria = true;\n }\n }\n };\n\n this._channel.addEventListener('internal', handleMessage);\n\n var ret = _sendMessage(this, 'apply') // send out that this one is applying\n .then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this, 'apply');\n }).then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this);\n }).then(function () {\n return beLeader(_this);\n }) // no one disagreed -> this one is now leader\n .then(function () {\n return true;\n })[\"catch\"](function () {\n return false;\n }) // apply not successfull\n .then(function (success) {\n _this._channel.removeEventListener('internal', handleMessage);\n\n _this._isApl = false;\n\n if (!success && _this._reApply) {\n _this._reApply = false;\n return _this.applyOnce();\n } else return success;\n });\n\n return ret;\n },\n awaitLeadership: function awaitLeadership() {\n if (\n /* _awaitLeadershipPromise */\n !this._aLP) {\n this._aLP = _awaitLeadershipOnce(this);\n }\n\n return this._aLP;\n },\n\n set onduplicate(fn) {\n this._dpL = fn;\n },\n\n die: function die() {\n var _this2 = this;\n\n if (this.isDead) return;\n this.isDead = true;\n\n this._lstns.forEach(function (listener) {\n return _this2._channel.removeEventListener('internal', listener);\n });\n\n this._invs.forEach(function (interval) {\n return clearInterval(interval);\n });\n\n this._unl.forEach(function (uFn) {\n uFn.remove();\n });\n\n return _sendMessage(this, 'death');\n }\n};\n\nfunction _awaitLeadershipOnce(leaderElector) {\n if (leaderElector.isLeader) return Promise.resolve();\n return new Promise(function (res) {\n var resolved = false;\n\n function finish() {\n if (resolved) {\n return;\n }\n\n resolved = true;\n clearInterval(interval);\n\n leaderElector._channel.removeEventListener('internal', whenDeathListener);\n\n res(true);\n } // try once now\n\n\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n }); // try on fallbackInterval\n\n var interval = setInterval(function () {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n }, leaderElector._options.fallbackInterval);\n\n leaderElector._invs.push(interval); // try when other leader dies\n\n\n var whenDeathListener = function whenDeathListener(msg) {\n if (msg.context === 'leader' && msg.action === 'death') {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) finish();\n });\n }\n };\n\n leaderElector._channel.addEventListener('internal', whenDeathListener);\n\n leaderElector._lstns.push(whenDeathListener);\n });\n}\n/**\n * sends and internal message over the broadcast-channel\n */\n\n\nfunction _sendMessage(leaderElector, action) {\n var msgJson = {\n context: 'leader',\n action: action,\n token: leaderElector.token\n };\n return leaderElector._channel.postInternal(msgJson);\n}\n\nexport function beLeader(leaderElector) {\n leaderElector.isLeader = true;\n var unloadFn = unload.add(function () {\n return leaderElector.die();\n });\n\n leaderElector._unl.push(unloadFn);\n\n var isLeaderListener = function isLeaderListener(msg) {\n if (msg.context === 'leader' && msg.action === 'apply') {\n _sendMessage(leaderElector, 'tell');\n }\n\n if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) {\n /**\n * another instance is also leader!\n * This can happen on rare events\n * like when the CPU is at 100% for long time\n * or the tabs are open very long and the browser throttles them.\n * @link https://github.com/pubkey/broadcast-channel/issues/414\n * @link https://github.com/pubkey/broadcast-channel/issues/385\n */\n leaderElector._dpLC = true;\n\n leaderElector._dpL(); // message the lib user so the app can handle the problem\n\n\n _sendMessage(leaderElector, 'tell'); // ensure other leader also knows the problem\n\n }\n };\n\n leaderElector._channel.addEventListener('internal', isLeaderListener);\n\n leaderElector._lstns.push(isLeaderListener);\n\n return _sendMessage(leaderElector, 'tell');\n}\n\nfunction fillOptionsWithDefaults(options, channel) {\n if (!options) options = {};\n options = JSON.parse(JSON.stringify(options));\n\n if (!options.fallbackInterval) {\n options.fallbackInterval = 3000;\n }\n\n if (!options.responseTime) {\n options.responseTime = channel.method.averageResponseTime(channel.options);\n }\n\n return options;\n}\n\nexport function createLeaderElection(channel, options) {\n if (channel._leaderElector) {\n throw new Error('BroadcastChannel already has a leader-elector');\n }\n\n options = fillOptionsWithDefaults(options, channel);\n var elector = new LeaderElection(channel, options);\n\n channel._befC.push(function () {\n return elector.die();\n });\n\n channel._leaderElector = elector;\n return elector;\n}"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://reduxStateSync/webpack/universalModuleDefinition","webpack://reduxStateSync/webpack/bootstrap","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/util.js","webpack://reduxStateSync/./node_modules/detect-node/browser.js","webpack://reduxStateSync/./src/syncState.js","webpack://reduxStateSync/./node_modules/process/browser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/native.js","webpack://reduxStateSync/./node_modules/oblivious-set/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/options.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/indexed-db.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/localstorage.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/methods/simulate.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/method-chooser.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/broadcast-channel.js","webpack://reduxStateSync/./node_modules/unload/dist/es/browser.js","webpack://reduxStateSync/./node_modules/unload/dist/es/index.js","webpack://reduxStateSync/./node_modules/broadcast-channel/dist/es/leader-election.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","isPromise","obj","then","sleep","time","Promise","res","setTimeout","randomInt","min","max","Math","floor","random","randomToken","toString","substring","lastMs","additional","microSeconds","ms","Date","getTime","isNode","process","generateUuidForAction","isActionAllowed","isActionSynced","action","$isSync","MessageListener","lastUuid","GET_INIT_STATE","SEND_INIT_STATE","RECEIVE_INIT_STATE","INIT_MESSAGE_LISTENER","defaultConfig","channel","predicate","blacklist","whitelist","broadcastChannelOption","undefined","prepareState","state","receiveState","prevState","nextState","s4","guid","WINDOW_STATE_SYNC_ID","stampedAction","$uuid","$wuid","allowed","Array","isArray","indexOf","type","dispatch","isSynced","tabs","this","handleOnMessage","assign","payload","messageChannel","onmessage","createStateSyncMiddleware","config","BroadcastChannel","messageListener","getState","next","postMessage","e","console","error","createReduxStateSync","appReducer","initState","withReduxStateSync","initStateWithPrevTab","initMessageListener","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","Error","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","channelName","messagesCallback","bc","subFns","msg","data","close","channelState","onMessage","fn","messageJson","resolve","err","reject","canBeUsed","_pubkey","averageResponseTime","ObliviousSet","ttl","set","Set","timeMap","Map","has","add","_this","now","obliviousSet","olderThen","iterator","delete","removeTooOldValues","clear","fillOptionsWithDefaults","originalOptions","options","JSON","parse","stringify","webWorkerSupport","idb","fallbackInterval","onclose","localstorage","removeTimeout","methods","node","useFastPath","getIdb","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","getMessagesHigherThan","db","lastCursorId","objectStore","transaction","ret","keyRangeValue","IDBKeyRange","bound","Infinity","openCursor","onsuccess","ev","cursor","target","result","id","cleanOldMessages","msgObk","getOldMessages","tooOld","all","map","msgObj","request","removeMessageById","readNewMessages","closed","newerMessages","filter","uuid","eMIs","messagesCallbackTime","_filterMessage","sort","msgObjA","msgObjB","forEach","dbName","openRequest","open","onupgradeneeded","createObjectStore","keyPath","autoIncrement","rej","onerror","createDatabase","writeBlockPromise","readQueuePromises","_readLoop","readerUuid","writeObject","oncomplete","writeMessage","getLocalStorage","localStorage","storageKey","ls","setItem","removeItem","listener","newValue","addEventListener","addStorageEventListener","token","removeEventListener","writeObj","document","createEvent","initEvent","dispatchEvent","userAgent","navigator","toLowerCase","includes","defaultTime","SIMULATE_CHANNELS","from","METHODS","NodeMethod","chooseMethod","chooseMethods","Boolean","find","useMethod","method","ENFORCED_OPTIONS","maybePromise","_iL","_onML","_addEL","message","internal","_uMP","_befC","_prepP","_state","clearNodeFolder","enforceOptions","_post","broadcastChannel","sendPromise","_hasMessageListeners","_addListenerObject","listenerFn","_startListening","_removeListenerObject","_stopListening","postInternal","listenObj","awaitPrepare","WorkerGlobalScope","self","USE_METHOD","LISTENERS","startedListening","runAll","promises","remove","removeAll","getSize","size","_channel","_options","isLeader","isDead","_isApl","_reApply","_unl","_lstns","_invs","_dpL","_dpLC","_sendMessage","leaderElector","msgJson","context","beLeader","unloadFn","die","isLeaderListener","createLeaderElection","_leaderElector","responseTime","elector","applyOnce","stopCriteria","recieved","handleMessage","success","awaitLeadership","_aLP","resolved","finish","clearInterval","interval","whenDeathListener","setInterval","_this2","uFn"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAwB,eAAID,IAE5BD,EAAqB,eAAIC,IAR3B,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBX,OAAOC,eAAeU,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AAO9M,KAAKyO,OA3EnB1R,KAAKqR,MAGd,gBAAgBpM,GACdjF,KAAKiQ,KAAOhL,GAGdwL,IAAK,WACH,IAAImB,EAAS5R,KAEb,IAAIA,KAAK2P,OAeT,OAdA3P,KAAK2P,QAAS,EAEd3P,KAAK+P,OAAO7F,SAAQ,SAAUwB,GAC5B,OAAOkG,EAAOpC,SAASzD,oBAAoB,WAAYL,MAGzD1L,KAAKgQ,MAAM9F,SAAQ,SAAUuH,GAC3B,OAAOD,cAAcC,MAGvBzR,KAAK8P,KAAK5F,SAAQ,SAAU2H,GAC1BA,EAAIzC,YAGCe,EAAanQ,KAAM","file":"syncState.umd.min.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 if(typeof exports === 'object')\n\t\texports[\"reduxStateSync\"] = factory();\n\telse\n\t\troot[\"reduxStateSync\"] = factory();\n})(window, function() {\nreturn "," \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 \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\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.l = 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// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 3);\n","/**\n * returns true if the given object is a promise\n */\nexport function isPromise(obj) {\n if (obj && typeof obj.then === 'function') {\n return true;\n } else {\n return false;\n }\n}\nexport function sleep(time) {\n if (!time) time = 0;\n return new Promise(function (res) {\n return setTimeout(res, time);\n });\n}\nexport function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/**\n * https://stackoverflow.com/a/8084248\n */\n\nexport function randomToken() {\n return Math.random().toString(36).substring(2);\n}\nvar lastMs = 0;\nvar additional = 0;\n/**\n * returns the current time in micro-seconds,\n * WARNING: This is a pseudo-function\n * Performance.now is not reliable in webworkers, so we just make sure to never return the same time.\n * This is enough in browsers, and this function will not be used in nodejs.\n * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.\n */\n\nexport function microSeconds() {\n var ms = new Date().getTime();\n\n if (ms === lastMs) {\n additional++;\n return ms * 1000 + additional;\n } else {\n lastMs = ms;\n additional = 0;\n return ms * 1000;\n }\n}\n/**\n * copied from the 'detect-node' npm module\n * We cannot use the module directly because it causes problems with rollup\n * @link https://github.com/iliakan/detect-node/blob/master/index.js\n */\n\nexport var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';","module.exports = false;\n\n","import { BroadcastChannel } from 'broadcast-channel';\n\nlet lastUuid = 0;\nexport const GET_INIT_STATE = '&_GET_INIT_STATE';\nexport const SEND_INIT_STATE = '&_SEND_INIT_STATE';\nexport const RECEIVE_INIT_STATE = '&_RECEIVE_INIT_STATE';\nexport const INIT_MESSAGE_LISTENER = '&_INIT_MESSAGE_LISTENER';\n\nconst defaultConfig = {\n channel: 'redux_state_sync',\n predicate: null,\n blacklist: [],\n whitelist: [],\n broadcastChannelOption: undefined,\n prepareState: state => state,\n receiveState: (prevState, nextState) => nextState,\n};\n\nconst getIniteState = () => ({ type: GET_INIT_STATE });\nconst sendIniteState = () => ({ type: SEND_INIT_STATE });\nconst receiveIniteState = state => ({ type: RECEIVE_INIT_STATE, payload: state });\nconst initListener = () => ({ type: INIT_MESSAGE_LISTENER });\n\nfunction s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n}\n\nfunction guid() {\n return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;\n}\n\n// generate current window unique id\nconst WINDOW_STATE_SYNC_ID = guid();\n// export for test\nexport function generateUuidForAction(action) {\n const stampedAction = action;\n stampedAction.$uuid = guid();\n stampedAction.$wuid = WINDOW_STATE_SYNC_ID;\n return stampedAction;\n}\n// export for test\nexport function isActionAllowed({ predicate, blacklist, whitelist }) {\n let allowed = () => true;\n\n if (predicate && typeof predicate === 'function') {\n allowed = predicate;\n } else if (Array.isArray(blacklist)) {\n allowed = action => blacklist.indexOf(action.type) < 0;\n } else if (Array.isArray(whitelist)) {\n allowed = action => whitelist.indexOf(action.type) >= 0;\n }\n return allowed;\n}\n// export for test\nexport function isActionSynced(action) {\n return !!action.$isSync;\n}\n// export for test\nexport function MessageListener({ channel, dispatch, allowed }) {\n let isSynced = false;\n const tabs = {};\n this.handleOnMessage = stampedAction => {\n // Ignore if this action is triggered by this window\n if (stampedAction.$wuid === WINDOW_STATE_SYNC_ID) {\n return;\n }\n // IE bug https://stackoverflow.com/questions/18265556/why-does-internet-explorer-fire-the-window-storage-event-on-the-window-that-st\n if (stampedAction.type === RECEIVE_INIT_STATE) {\n return;\n }\n // ignore other values that saved to localstorage.\n if (stampedAction.$uuid && stampedAction.$uuid !== lastUuid) {\n if (stampedAction.type === GET_INIT_STATE && !tabs[stampedAction.$wuid]) {\n tabs[stampedAction.$wuid] = true;\n dispatch(sendIniteState());\n } else if (stampedAction.type === SEND_INIT_STATE && !tabs[stampedAction.$wuid]) {\n if (!isSynced) {\n isSynced = true;\n dispatch(receiveIniteState(stampedAction.payload));\n }\n } else if (allowed(stampedAction)) {\n lastUuid = stampedAction.$uuid;\n dispatch(\n Object.assign(stampedAction, {\n $isSync: true,\n }),\n );\n }\n }\n };\n this.messageChannel = channel;\n this.messageChannel.onmessage = this.handleOnMessage;\n}\n\nexport const createStateSyncMiddleware = (config = defaultConfig) => {\n const allowed = isActionAllowed(config);\n const channel = new BroadcastChannel(config.channel, config.broadcastChannelOption);\n const prepareState = config.prepareState || defaultConfig.prepareState;\n let messageListener = null;\n\n return ({ getState, dispatch }) => next => action => {\n // create message receiver\n if (!messageListener) {\n messageListener = new MessageListener({ channel, dispatch, allowed });\n }\n // post messages\n if (action && !action.$uuid) {\n const stampedAction = generateUuidForAction(action);\n lastUuid = stampedAction.$uuid;\n try {\n if (action.type === SEND_INIT_STATE) {\n if (getState()) {\n stampedAction.payload = prepareState(getState());\n channel.postMessage(stampedAction);\n }\n return next(action);\n }\n if (allowed(stampedAction) || action.type === GET_INIT_STATE) {\n channel.postMessage(stampedAction);\n }\n } catch (e) {\n console.error(\"Your browser doesn't support cross tab communication\");\n }\n }\n return next(\n Object.assign(action, {\n $isSync: typeof action.$isSync === 'undefined' ? false : action.$isSync,\n }),\n );\n };\n};\n\n// eslint-disable-next-line max-len\nexport const createReduxStateSync = (appReducer, receiveState = defaultConfig.receiveState) => (state, action) => {\n let initState = state;\n if (action.type === RECEIVE_INIT_STATE) {\n initState = receiveState(state, action.payload);\n }\n return appReducer(initState, action);\n};\n\n// init state with other tab's state\nexport const withReduxStateSync = createReduxStateSync;\n\nexport const initStateWithPrevTab = ({ dispatch }) => {\n dispatch(getIniteState());\n};\n\n/*\nif don't dispath any action, the store.dispath will not be available for message listener.\ntherefor need to trigger an empty action to init the messageListener.\n\nhowever, if already using initStateWithPrevTab, this function will be redundant\n*/\nexport const initMessageListener = ({ dispatch }) => {\n dispatch(initListener());\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import { microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nexport var type = 'native';\nexport function create(channelName) {\n var state = {\n messagesCallback: null,\n bc: new BroadcastChannel(channelName),\n subFns: [] // subscriberFunctions\n\n };\n\n state.bc.onmessage = function (msg) {\n if (state.messagesCallback) {\n state.messagesCallback(msg.data);\n }\n };\n\n return state;\n}\nexport function close(channelState) {\n channelState.bc.close();\n channelState.subFns = [];\n}\nexport function postMessage(channelState, messageJson) {\n try {\n channelState.bc.postMessage(messageJson, false);\n return Promise.resolve();\n } catch (err) {\n return Promise.reject(err);\n }\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n /**\n * in the electron-renderer, isNode will be true even if we are in browser-context\n * so we also check if window is undefined\n */\n if (isNode && typeof window === 'undefined') return false;\n\n if (typeof BroadcastChannel === 'function') {\n if (BroadcastChannel._pubkey) {\n throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');\n }\n\n return true;\n } else return false;\n}\nexport function averageResponseTime() {\n return 150;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * this is a set which automatically forgets\n * a given entry when a new entry is set and the ttl\n * of the old one is over\n */\nvar ObliviousSet = /** @class */ (function () {\n function ObliviousSet(ttl) {\n this.ttl = ttl;\n this.set = new Set();\n this.timeMap = new Map();\n }\n ObliviousSet.prototype.has = function (value) {\n return this.set.has(value);\n };\n ObliviousSet.prototype.add = function (value) {\n var _this = this;\n this.timeMap.set(value, now());\n this.set.add(value);\n /**\n * When a new value is added,\n * start the cleanup at the next tick\n * to not block the cpu for more important stuff\n * that might happen.\n */\n setTimeout(function () {\n removeTooOldValues(_this);\n }, 0);\n };\n ObliviousSet.prototype.clear = function () {\n this.set.clear();\n this.timeMap.clear();\n };\n return ObliviousSet;\n}());\nexport { ObliviousSet };\n/**\n * Removes all entries from the set\n * where the TTL has expired\n */\nexport function removeTooOldValues(obliviousSet) {\n var olderThen = now() - obliviousSet.ttl;\n var iterator = obliviousSet.set[Symbol.iterator]();\n /**\n * Because we can assume the new values are added at the bottom,\n * we start from the top and stop as soon as we reach a non-too-old value.\n */\n while (true) {\n var value = iterator.next().value;\n if (!value) {\n return; // no more elements\n }\n var time = obliviousSet.timeMap.get(value);\n if (time < olderThen) {\n obliviousSet.timeMap.delete(value);\n obliviousSet.set.delete(value);\n }\n else {\n // We reached a value that is not old enough\n return;\n }\n }\n}\nexport function now() {\n return new Date().getTime();\n}\n//# sourceMappingURL=index.js.map","export function fillOptionsWithDefaults() {\n var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = JSON.parse(JSON.stringify(originalOptions)); // main\n\n if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; // indexed-db\n\n if (!options.idb) options.idb = {}; // after this time the messages get deleted\n\n if (!options.idb.ttl) options.idb.ttl = 1000 * 45;\n if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; // handles abrupt db onclose events.\n\n if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose; // localstorage\n\n if (!options.localstorage) options.localstorage = {};\n if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; // custom methods\n\n if (originalOptions.methods) options.methods = originalOptions.methods; // node\n\n if (!options.node) options.node = {};\n if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;\n\n if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;\n return options;\n}","/**\n * this method uses indexeddb to store the messages\n * There is currently no observerAPI for idb\n * @link https://github.com/w3c/IndexedDB/issues/51\n */\nimport { sleep, randomInt, randomToken, microSeconds as micro, isNode } from '../util.js';\nexport var microSeconds = micro;\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nvar DB_PREFIX = 'pubkey.broadcast-channel-0-';\nvar OBJECT_STORE_ID = 'messages';\nexport var type = 'idb';\nexport function getIdb() {\n if (typeof indexedDB !== 'undefined') return indexedDB;\n\n if (typeof window !== 'undefined') {\n if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;\n if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;\n if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;\n }\n\n return false;\n}\nexport function createDatabase(channelName) {\n var IndexedDB = getIdb(); // create table\n\n var dbName = DB_PREFIX + channelName;\n var openRequest = IndexedDB.open(dbName, 1);\n\n openRequest.onupgradeneeded = function (ev) {\n var db = ev.target.result;\n db.createObjectStore(OBJECT_STORE_ID, {\n keyPath: 'id',\n autoIncrement: true\n });\n };\n\n var dbPromise = new Promise(function (res, rej) {\n openRequest.onerror = function (ev) {\n return rej(ev);\n };\n\n openRequest.onsuccess = function () {\n res(openRequest.result);\n };\n });\n return dbPromise;\n}\n/**\n * writes the new message to the database\n * so other readers can find it\n */\n\nexport function writeMessage(db, readerUuid, messageJson) {\n var time = new Date().getTime();\n var writeObject = {\n uuid: readerUuid,\n time: time,\n data: messageJson\n };\n var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');\n return new Promise(function (res, rej) {\n transaction.oncomplete = function () {\n return res();\n };\n\n transaction.onerror = function (ev) {\n return rej(ev);\n };\n\n var objectStore = transaction.objectStore(OBJECT_STORE_ID);\n objectStore.add(writeObject);\n });\n}\nexport function getAllMessages(db) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n ret.push(cursor.value); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n res(ret);\n }\n };\n });\n}\nexport function getMessagesHigherThan(db, lastCursorId) {\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n\n function openCursor() {\n // Occasionally Safari will fail on IDBKeyRange.bound, this\n // catches that error, having it open the cursor to the first\n // item. When it gets data it will advance to the desired key.\n try {\n var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n return objectStore.openCursor(keyRangeValue);\n } catch (e) {\n return objectStore.openCursor();\n }\n }\n\n return new Promise(function (res) {\n openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n if (cursor.value.id < lastCursorId + 1) {\n cursor[\"continue\"](lastCursorId + 1);\n } else {\n ret.push(cursor.value);\n cursor[\"continue\"]();\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function removeMessageById(db, id) {\n var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)[\"delete\"](id);\n return new Promise(function (res) {\n request.onsuccess = function () {\n return res();\n };\n });\n}\nexport function getOldMessages(db, ttl) {\n var olderThen = new Date().getTime() - ttl;\n var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n\n if (cursor) {\n var msgObk = cursor.value;\n\n if (msgObk.time < olderThen) {\n ret.push(msgObk); //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n\n cursor[\"continue\"]();\n } else {\n // no more old messages,\n res(ret);\n return;\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function cleanOldMessages(db, ttl) {\n return getOldMessages(db, ttl).then(function (tooOld) {\n return Promise.all(tooOld.map(function (msgObj) {\n return removeMessageById(db, msgObj.id);\n }));\n });\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n return createDatabase(channelName).then(function (db) {\n var state = {\n closed: false,\n lastCursorId: 0,\n channelName: channelName,\n options: options,\n uuid: randomToken(),\n\n /**\n * emittedMessagesIds\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n eMIs: new ObliviousSet(options.idb.ttl * 2),\n // ensures we do not read messages in parrallel\n writeBlockPromise: Promise.resolve(),\n messagesCallback: null,\n readQueuePromises: [],\n db: db\n };\n /**\n * Handle abrupt closes that do not originate from db.close().\n * This could happen, for example, if the underlying storage is\n * removed or if the user clears the database in the browser's\n * history preferences.\n */\n\n db.onclose = function () {\n state.closed = true;\n if (options.idb.onclose) options.idb.onclose();\n };\n /**\n * if service-workers are used,\n * we have no 'storage'-event if they post a message,\n * therefore we also have to set an interval\n */\n\n\n _readLoop(state);\n\n return state;\n });\n}\n\nfunction _readLoop(state) {\n if (state.closed) return;\n readNewMessages(state).then(function () {\n return sleep(state.options.idb.fallbackInterval);\n }).then(function () {\n return _readLoop(state);\n });\n}\n\nfunction _filterMessage(msgObj, state) {\n if (msgObj.uuid === state.uuid) return false; // send by own\n\n if (state.eMIs.has(msgObj.id)) return false; // already emitted\n\n if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback\n\n return true;\n}\n/**\n * reads all new messages from the database and emits them\n */\n\n\nfunction readNewMessages(state) {\n // channel already closed\n if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages\n\n if (!state.messagesCallback) return Promise.resolve();\n return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {\n var useMessages = newerMessages\n /**\n * there is a bug in iOS where the msgObj can be undefined some times\n * so we filter them out\n * @link https://github.com/pubkey/broadcast-channel/issues/19\n */\n .filter(function (msgObj) {\n return !!msgObj;\n }).map(function (msgObj) {\n if (msgObj.id > state.lastCursorId) {\n state.lastCursorId = msgObj.id;\n }\n\n return msgObj;\n }).filter(function (msgObj) {\n return _filterMessage(msgObj, state);\n }).sort(function (msgObjA, msgObjB) {\n return msgObjA.time - msgObjB.time;\n }); // sort by time\n\n useMessages.forEach(function (msgObj) {\n if (state.messagesCallback) {\n state.eMIs.add(msgObj.id);\n state.messagesCallback(msgObj.data);\n }\n });\n return Promise.resolve();\n });\n}\n\nexport function close(channelState) {\n channelState.closed = true;\n channelState.db.close();\n}\nexport function postMessage(channelState, messageJson) {\n channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {\n return writeMessage(channelState.db, channelState.uuid, messageJson);\n }).then(function () {\n if (randomInt(0, 10) === 0) {\n /* await (do not await) */\n cleanOldMessages(channelState.db, channelState.options.idb.ttl);\n }\n });\n return channelState.writeBlockPromise;\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n readNewMessages(channelState);\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var idb = getIdb();\n if (!idb) return false;\n return true;\n}\nexport function averageResponseTime(options) {\n return options.idb.fallbackInterval * 2;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","/**\n * A localStorage-only method which uses localstorage and its 'storage'-event\n * This does not work inside of webworkers because they have no access to locastorage\n * This is basically implemented to support IE9 or your grandmothers toaster.\n * @link https://caniuse.com/#feat=namevalue-storage\n * @link https://caniuse.com/#feat=indexeddb\n */\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options';\nimport { sleep, randomToken, microSeconds as micro, isNode } from '../util';\nexport var microSeconds = micro;\nvar KEY_PREFIX = 'pubkey.broadcastChannel-';\nexport var type = 'localstorage';\n/**\n * copied from crosstab\n * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32\n */\n\nexport function getLocalStorage() {\n var localStorage;\n if (typeof window === 'undefined') return null;\n\n try {\n localStorage = window.localStorage;\n localStorage = window['ie8-eventlistener/storage'] || window.localStorage;\n } catch (e) {// New versions of Firefox throw a Security exception\n // if cookies are disabled. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153\n }\n\n return localStorage;\n}\nexport function storageKey(channelName) {\n return KEY_PREFIX + channelName;\n}\n/**\n* writes the new message to the storage\n* and fires the storage-event so other readers can find it\n*/\n\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n sleep().then(function () {\n var key = storageKey(channelState.channelName);\n var writeObj = {\n token: randomToken(),\n time: new Date().getTime(),\n data: messageJson,\n uuid: channelState.uuid\n };\n var value = JSON.stringify(writeObj);\n getLocalStorage().setItem(key, value);\n /**\n * StorageEvent does not fire the 'storage' event\n * in the window that changes the state of the local storage.\n * So we fire it manually\n */\n\n var ev = document.createEvent('Event');\n ev.initEvent('storage', true, true);\n ev.key = key;\n ev.newValue = value;\n window.dispatchEvent(ev);\n res();\n });\n });\n}\nexport function addStorageEventListener(channelName, fn) {\n var key = storageKey(channelName);\n\n var listener = function listener(ev) {\n if (ev.key === key) {\n fn(JSON.parse(ev.newValue));\n }\n };\n\n window.addEventListener('storage', listener);\n return listener;\n}\nexport function removeStorageEventListener(listener) {\n window.removeEventListener('storage', listener);\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n\n if (!canBeUsed()) {\n throw new Error('BroadcastChannel: localstorage cannot be used');\n }\n\n var uuid = randomToken();\n /**\n * eMIs\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n\n var eMIs = new ObliviousSet(options.localstorage.removeTimeout);\n var state = {\n channelName: channelName,\n uuid: uuid,\n eMIs: eMIs // emittedMessagesIds\n\n };\n state.listener = addStorageEventListener(channelName, function (msgObj) {\n if (!state.messagesCallback) return; // no listener\n\n if (msgObj.uuid === uuid) return; // own message\n\n if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted\n\n if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old\n\n eMIs.add(msgObj.token);\n state.messagesCallback(msgObj.data);\n });\n return state;\n}\nexport function close(channelState) {\n removeStorageEventListener(channelState.listener);\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n if (isNode) return false;\n var ls = getLocalStorage();\n if (!ls) return false;\n\n try {\n var key = '__broadcastchannel_check';\n ls.setItem(key, 'works');\n ls.removeItem(key);\n } catch (e) {\n // Safari 10 in private mode will not allow write access to local\n // storage and fail with a QuotaExceededError. See\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes\n return false;\n }\n\n return true;\n}\nexport function averageResponseTime() {\n var defaultTime = 120;\n var userAgent = navigator.userAgent.toLowerCase();\n\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n // safari is much slower so this time is higher\n return defaultTime * 2;\n }\n\n return defaultTime;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import { microSeconds as micro } from '../util';\nexport var microSeconds = micro;\nexport var type = 'simulate';\nvar SIMULATE_CHANNELS = new Set();\nexport function create(channelName) {\n var state = {\n name: channelName,\n messagesCallback: null\n };\n SIMULATE_CHANNELS.add(state);\n return state;\n}\nexport function close(channelState) {\n SIMULATE_CHANNELS[\"delete\"](channelState);\n}\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n return setTimeout(function () {\n var channelArray = Array.from(SIMULATE_CHANNELS);\n channelArray.filter(function (channel) {\n return channel.name === channelState.name;\n }).filter(function (channel) {\n return channel !== channelState;\n }).filter(function (channel) {\n return !!channel.messagesCallback;\n }).forEach(function (channel) {\n return channel.messagesCallback(messageJson);\n });\n res();\n }, 5);\n });\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n return true;\n}\nexport function averageResponseTime() {\n return 5;\n}\nexport default {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};","import NativeMethod from './methods/native.js';\nimport IndexeDbMethod from './methods/indexed-db.js';\nimport LocalstorageMethod from './methods/localstorage.js';\nimport SimulateMethod from './methods/simulate.js';\nimport { isNode } from './util'; // order is important\n\nvar METHODS = [NativeMethod, // fastest\nIndexeDbMethod, LocalstorageMethod];\n/**\n * The NodeMethod is loaded lazy\n * so it will not get bundled in browser-builds\n */\n\nif (isNode) {\n /**\n * we use the non-transpiled code for nodejs\n * because it runs faster\n */\n var NodeMethod = require('../../src/methods/' + // use this hack so that browserify and others\n // do not import the node-method by default\n // when bundling.\n 'node.js');\n /**\n * this will be false for webpackbuilds\n * which will shim the node-method with an empty object {}\n */\n\n\n if (typeof NodeMethod.canBeUsed === 'function') {\n METHODS.push(NodeMethod);\n }\n}\n\nexport function chooseMethod(options) {\n var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen\n\n if (options.type) {\n if (options.type === 'simulate') {\n // only use simulate-method if directly chosen\n return SimulateMethod;\n }\n\n var ret = chooseMethods.find(function (m) {\n return m.type === options.type;\n });\n if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;\n }\n /**\n * if no webworker support is needed,\n * remove idb from the list so that localstorage is been chosen\n */\n\n\n if (!options.webWorkerSupport && !isNode) {\n chooseMethods = chooseMethods.filter(function (m) {\n return m.type !== 'idb';\n });\n }\n\n var useMethod = chooseMethods.find(function (method) {\n return method.canBeUsed();\n });\n if (!useMethod) throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(function (m) {\n return m.type;\n })));else return useMethod;\n}","import { isPromise } from './util.js';\nimport { chooseMethod } from './method-chooser.js';\nimport { fillOptionsWithDefaults } from './options.js';\nexport var BroadcastChannel = function BroadcastChannel(name, options) {\n this.name = name;\n\n if (ENFORCED_OPTIONS) {\n options = ENFORCED_OPTIONS;\n }\n\n this.options = fillOptionsWithDefaults(options);\n this.method = chooseMethod(this.options); // isListening\n\n this._iL = false;\n /**\n * _onMessageListener\n * setting onmessage twice,\n * will overwrite the first listener\n */\n\n this._onML = null;\n /**\n * _addEventListeners\n */\n\n this._addEL = {\n message: [],\n internal: []\n };\n /**\n * Unsend message promises\n * where the sending is still in progress\n * @type {Set}\n */\n\n this._uMP = new Set();\n /**\n * _beforeClose\n * array of promises that will be awaited\n * before the channel is closed\n */\n\n this._befC = [];\n /**\n * _preparePromise\n */\n\n this._prepP = null;\n\n _prepareChannel(this);\n}; // STATICS\n\n/**\n * used to identify if someone overwrites\n * window.BroadcastChannel with this\n * See methods/native.js\n */\n\nBroadcastChannel._pubkey = true;\n/**\n * clears the tmp-folder if is node\n * @return {Promise} true if has run, false if not node\n */\n\nexport function clearNodeFolder(options) {\n options = fillOptionsWithDefaults(options);\n var method = chooseMethod(options);\n\n if (method.type === 'node') {\n return method.clearNodeFolder().then(function () {\n return true;\n });\n } else {\n return Promise.resolve(false);\n }\n}\n/**\n * if set, this method is enforced,\n * no mather what the options are\n */\n\nvar ENFORCED_OPTIONS;\nexport function enforceOptions(options) {\n ENFORCED_OPTIONS = options;\n} // PROTOTYPE\n\nBroadcastChannel.prototype = {\n postMessage: function postMessage(msg) {\n if (this.closed) {\n throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');\n }\n\n return _post(this, 'message', msg);\n },\n postInternal: function postInternal(msg) {\n return _post(this, 'internal', msg);\n },\n\n set onmessage(fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _removeListenerObject(this, 'message', this._onML);\n\n if (fn && typeof fn === 'function') {\n this._onML = listenObj;\n\n _addListenerObject(this, 'message', listenObj);\n } else {\n this._onML = null;\n }\n },\n\n addEventListener: function addEventListener(type, fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n\n _addListenerObject(this, type, listenObj);\n },\n removeEventListener: function removeEventListener(type, fn) {\n var obj = this._addEL[type].find(function (obj) {\n return obj.fn === fn;\n });\n\n _removeListenerObject(this, type, obj);\n },\n close: function close() {\n var _this = this;\n\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();\n this._onML = null;\n this._addEL.message = [];\n return awaitPrepare // wait until all current sending are processed\n .then(function () {\n return Promise.all(Array.from(_this._uMP));\n }) // run before-close hooks\n .then(function () {\n return Promise.all(_this._befC.map(function (fn) {\n return fn();\n }));\n }) // close the channel\n .then(function () {\n return _this.method.close(_this._state);\n });\n },\n\n get type() {\n return this.method.type;\n },\n\n get isClosed() {\n return this.closed;\n }\n\n};\n/**\n * Post a message over the channel\n * @returns {Promise} that resolved when the message sending is done\n */\n\nfunction _post(broadcastChannel, type, msg) {\n var time = broadcastChannel.method.microSeconds();\n var msgObj = {\n time: time,\n type: type,\n data: msg\n };\n var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();\n return awaitPrepare.then(function () {\n var sendPromise = broadcastChannel.method.postMessage(broadcastChannel._state, msgObj); // add/remove to unsend messages list\n\n broadcastChannel._uMP.add(sendPromise);\n\n sendPromise[\"catch\"]().then(function () {\n return broadcastChannel._uMP[\"delete\"](sendPromise);\n });\n return sendPromise;\n });\n}\n\nfunction _prepareChannel(channel) {\n var maybePromise = channel.method.create(channel.name, channel.options);\n\n if (isPromise(maybePromise)) {\n channel._prepP = maybePromise;\n maybePromise.then(function (s) {\n // used in tests to simulate slow runtime\n\n /*if (channel.options.prepareDelay) {\n await new Promise(res => setTimeout(res, this.options.prepareDelay));\n }*/\n channel._state = s;\n });\n } else {\n channel._state = maybePromise;\n }\n}\n\nfunction _hasMessageListeners(channel) {\n if (channel._addEL.message.length > 0) return true;\n if (channel._addEL.internal.length > 0) return true;\n return false;\n}\n\nfunction _addListenerObject(channel, type, obj) {\n channel._addEL[type].push(obj);\n\n _startListening(channel);\n}\n\nfunction _removeListenerObject(channel, type, obj) {\n channel._addEL[type] = channel._addEL[type].filter(function (o) {\n return o !== obj;\n });\n\n _stopListening(channel);\n}\n\nfunction _startListening(channel) {\n if (!channel._iL && _hasMessageListeners(channel)) {\n // someone is listening, start subscribing\n var listenerFn = function listenerFn(msgObj) {\n channel._addEL[msgObj.type].forEach(function (obj) {\n if (msgObj.time >= obj.time) {\n obj.fn(msgObj.data);\n }\n });\n };\n\n var time = channel.method.microSeconds();\n\n if (channel._prepP) {\n channel._prepP.then(function () {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n });\n } else {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n }\n }\n}\n\nfunction _stopListening(channel) {\n if (channel._iL && !_hasMessageListeners(channel)) {\n // noone is listening, stop subscribing\n channel._iL = false;\n var time = channel.method.microSeconds();\n channel.method.onMessage(channel._state, null, time);\n }\n}","/* global WorkerGlobalScope */\nfunction add(fn) {\n if (typeof WorkerGlobalScope === 'function' && self instanceof WorkerGlobalScope) {// this is run inside of a webworker\n } else {\n /**\n * if we are on react-native, there is no window.addEventListener\n * @link https://github.com/pubkey/unload/issues/6\n */\n if (typeof window.addEventListener !== 'function') return;\n /**\n * for normal browser-windows, we use the beforeunload-event\n */\n\n window.addEventListener('beforeunload', function () {\n fn();\n }, true);\n /**\n * for iframes, we have to use the unload-event\n * @link https://stackoverflow.com/q/47533670/3443137\n */\n\n window.addEventListener('unload', function () {\n fn();\n }, true);\n }\n /**\n * TODO add fallback for safari-mobile\n * @link https://stackoverflow.com/a/26193516/3443137\n */\n\n}\n\nexport default {\n add: add\n};","import isNode from 'detect-node';\nimport BrowserMethod from './browser.js';\nimport NodeMethod from './node.js';\nvar USE_METHOD = isNode ? NodeMethod : BrowserMethod;\nvar LISTENERS = new Set();\nvar startedListening = false;\n\nfunction startListening() {\n if (startedListening) return;\n startedListening = true;\n USE_METHOD.add(runAll);\n}\n\nexport function add(fn) {\n startListening();\n if (typeof fn !== 'function') throw new Error('Listener is no function');\n LISTENERS.add(fn);\n var addReturn = {\n remove: function remove() {\n return LISTENERS[\"delete\"](fn);\n },\n run: function run() {\n LISTENERS[\"delete\"](fn);\n return fn();\n }\n };\n return addReturn;\n}\nexport function runAll() {\n var promises = [];\n LISTENERS.forEach(function (fn) {\n promises.push(fn());\n LISTENERS[\"delete\"](fn);\n });\n return Promise.all(promises);\n}\nexport function removeAll() {\n LISTENERS.clear();\n}\nexport function getSize() {\n return LISTENERS.size;\n}\nexport default {\n add: add,\n runAll: runAll,\n removeAll: removeAll,\n getSize: getSize\n};","import { sleep, randomToken } from './util.js';\nimport unload from 'unload';\n\nvar LeaderElection = function LeaderElection(channel, options) {\n this._channel = channel;\n this._options = options;\n this.isLeader = false;\n this.isDead = false;\n this.token = randomToken();\n this._isApl = false; // _isApplying\n\n this._reApply = false; // things to clean up\n\n this._unl = []; // _unloads\n\n this._lstns = []; // _listeners\n\n this._invs = []; // _intervals\n\n this._dpL = function () {}; // onduplicate listener\n\n\n this._dpLC = false; // true when onduplicate called\n};\n\nLeaderElection.prototype = {\n applyOnce: function applyOnce() {\n var _this = this;\n\n if (this.isLeader) return Promise.resolve(false);\n if (this.isDead) return Promise.resolve(false); // do nothing if already running\n\n if (this._isApl) {\n this._reApply = true;\n return Promise.resolve(false);\n }\n\n this._isApl = true;\n var stopCriteria = false;\n var recieved = [];\n\n var handleMessage = function handleMessage(msg) {\n if (msg.context === 'leader' && msg.token != _this.token) {\n recieved.push(msg);\n\n if (msg.action === 'apply') {\n // other is applying\n if (msg.token > _this.token) {\n // other has higher token, stop applying\n stopCriteria = true;\n }\n }\n\n if (msg.action === 'tell') {\n // other is already leader\n stopCriteria = true;\n }\n }\n };\n\n this._channel.addEventListener('internal', handleMessage);\n\n var ret = _sendMessage(this, 'apply') // send out that this one is applying\n .then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this, 'apply');\n }).then(function () {\n return sleep(_this._options.responseTime);\n }) // let others time to respond\n .then(function () {\n if (stopCriteria) return Promise.reject(new Error());else return _sendMessage(_this);\n }).then(function () {\n return beLeader(_this);\n }) // no one disagreed -> this one is now leader\n .then(function () {\n return true;\n })[\"catch\"](function () {\n return false;\n }) // apply not successfull\n .then(function (success) {\n _this._channel.removeEventListener('internal', handleMessage);\n\n _this._isApl = false;\n\n if (!success && _this._reApply) {\n _this._reApply = false;\n return _this.applyOnce();\n } else return success;\n });\n\n return ret;\n },\n awaitLeadership: function awaitLeadership() {\n if (\n /* _awaitLeadershipPromise */\n !this._aLP) {\n this._aLP = _awaitLeadershipOnce(this);\n }\n\n return this._aLP;\n },\n\n set onduplicate(fn) {\n this._dpL = fn;\n },\n\n die: function die() {\n var _this2 = this;\n\n if (this.isDead) return;\n this.isDead = true;\n\n this._lstns.forEach(function (listener) {\n return _this2._channel.removeEventListener('internal', listener);\n });\n\n this._invs.forEach(function (interval) {\n return clearInterval(interval);\n });\n\n this._unl.forEach(function (uFn) {\n uFn.remove();\n });\n\n return _sendMessage(this, 'death');\n }\n};\n\nfunction _awaitLeadershipOnce(leaderElector) {\n if (leaderElector.isLeader) return Promise.resolve();\n return new Promise(function (res) {\n var resolved = false;\n\n function finish() {\n if (resolved) {\n return;\n }\n\n resolved = true;\n clearInterval(interval);\n\n leaderElector._channel.removeEventListener('internal', whenDeathListener);\n\n res(true);\n } // try once now\n\n\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n }); // try on fallbackInterval\n\n var interval = setInterval(function () {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n }, leaderElector._options.fallbackInterval);\n\n leaderElector._invs.push(interval); // try when other leader dies\n\n\n var whenDeathListener = function whenDeathListener(msg) {\n if (msg.context === 'leader' && msg.action === 'death') {\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) finish();\n });\n }\n };\n\n leaderElector._channel.addEventListener('internal', whenDeathListener);\n\n leaderElector._lstns.push(whenDeathListener);\n });\n}\n/**\n * sends and internal message over the broadcast-channel\n */\n\n\nfunction _sendMessage(leaderElector, action) {\n var msgJson = {\n context: 'leader',\n action: action,\n token: leaderElector.token\n };\n return leaderElector._channel.postInternal(msgJson);\n}\n\nexport function beLeader(leaderElector) {\n leaderElector.isLeader = true;\n var unloadFn = unload.add(function () {\n return leaderElector.die();\n });\n\n leaderElector._unl.push(unloadFn);\n\n var isLeaderListener = function isLeaderListener(msg) {\n if (msg.context === 'leader' && msg.action === 'apply') {\n _sendMessage(leaderElector, 'tell');\n }\n\n if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) {\n /**\n * another instance is also leader!\n * This can happen on rare events\n * like when the CPU is at 100% for long time\n * or the tabs are open very long and the browser throttles them.\n * @link https://github.com/pubkey/broadcast-channel/issues/414\n * @link https://github.com/pubkey/broadcast-channel/issues/385\n */\n leaderElector._dpLC = true;\n\n leaderElector._dpL(); // message the lib user so the app can handle the problem\n\n\n _sendMessage(leaderElector, 'tell'); // ensure other leader also knows the problem\n\n }\n };\n\n leaderElector._channel.addEventListener('internal', isLeaderListener);\n\n leaderElector._lstns.push(isLeaderListener);\n\n return _sendMessage(leaderElector, 'tell');\n}\n\nfunction fillOptionsWithDefaults(options, channel) {\n if (!options) options = {};\n options = JSON.parse(JSON.stringify(options));\n\n if (!options.fallbackInterval) {\n options.fallbackInterval = 3000;\n }\n\n if (!options.responseTime) {\n options.responseTime = channel.method.averageResponseTime(channel.options);\n }\n\n return options;\n}\n\nexport function createLeaderElection(channel, options) {\n if (channel._leaderElector) {\n throw new Error('BroadcastChannel already has a leader-elector');\n }\n\n options = fillOptionsWithDefaults(options, channel);\n var elector = new LeaderElection(channel, options);\n\n channel._befC.push(function () {\n return elector.die();\n });\n\n channel._leaderElector = elector;\n return elector;\n}"],"sourceRoot":""} \ No newline at end of file diff --git a/src/syncState.js b/src/syncState.js index fb12c30..b3b4148 100644 --- a/src/syncState.js +++ b/src/syncState.js @@ -13,7 +13,7 @@ const defaultConfig = { whitelist: [], broadcastChannelOption: undefined, prepareState: state => state, - receiveState: state => state, + receiveState: (prevState, nextState) => nextState, }; const getIniteState = () => ({ type: GET_INIT_STATE });