Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

broadcast-channel

Package Overview
Dependencies
Maintainers
1
Versions
98
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

broadcast-channel - npm Package Compare versions

Comparing version 2.3.4 to 3.0.0

dist/es/broadcast-channel.js

8

dist/es/browserify.index.js

@@ -1,6 +0,6 @@

var BroadcastChannel = require('./index.es5.js');
var module = require('./index.es5.js');
var LeaderElection = require('./leader-election/index.es5.js');
var BroadcastChannel = module.BroadcastChannel;
var createLeaderElection = module.createLeaderElection;
window['BroadcastChannel2'] = BroadcastChannel;
window['LeaderElection'] = LeaderElection;
window['createLeaderElection'] = createLeaderElection;

@@ -9,3 +9,8 @@ /**

*/
import BroadcastChannel from './index.js';
module.exports = BroadcastChannel;
import { BroadcastChannel, createLeaderElection, clearNodeFolder, enforceOptions } from './index.js';
module.exports = {
BroadcastChannel: BroadcastChannel,
createLeaderElection: createLeaderElection,
clearNodeFolder: clearNodeFolder,
enforceOptions: enforceOptions
};

@@ -1,239 +0,2 @@

import { isPromise } from './util.js';
import { chooseMethod } from './method-chooser.js';
import { fillOptionsWithDefaults } from './options.js';
var BroadcastChannel = function BroadcastChannel(name, options) {
this.name = name;
if (ENFORCED_OPTIONS) {
options = ENFORCED_OPTIONS;
}
this.options = fillOptionsWithDefaults(options);
this.method = chooseMethod(this.options); // isListening
this._iL = false;
/**
* _onMessageListener
* setting onmessage twice,
* will overwrite the first listener
*/
this._onML = null;
/**
* _addEventListeners
*/
this._addEL = {
message: [],
internal: []
};
/**
* _beforeClose
* array of promises that will be awaited
* before the channel is closed
*/
this._befC = [];
/**
* _preparePromise
*/
this._prepP = null;
_prepareChannel(this);
}; // STATICS
/**
* used to identify if someone overwrites
* window.BroadcastChannel with this
* See methods/native.js
*/
BroadcastChannel._pubkey = true;
/**
* clears the tmp-folder if is node
* @return {Promise<boolean>} true if has run, false if not node
*/
BroadcastChannel.clearNodeFolder = function (options) {
options = fillOptionsWithDefaults(options);
var method = chooseMethod(options);
if (method.type === 'node') {
return method.clearNodeFolder().then(function () {
return true;
});
} else {
return Promise.resolve(false);
}
};
/**
* if set, this method is enforced,
* no mather what the options are
*/
var ENFORCED_OPTIONS;
BroadcastChannel.enforceOptions = function (options) {
ENFORCED_OPTIONS = options;
}; // PROTOTYPE
BroadcastChannel.prototype = {
postMessage: function postMessage(msg) {
if (this.closed) {
throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');
}
return _post(this, 'message', msg);
},
postInternal: function postInternal(msg) {
return _post(this, 'internal', msg);
},
set onmessage(fn) {
var time = this.method.microSeconds();
var listenObj = {
time: time,
fn: fn
};
_removeListenerObject(this, 'message', this._onML);
if (fn && typeof fn === 'function') {
this._onML = listenObj;
_addListenerObject(this, 'message', listenObj);
} else {
this._onML = null;
}
},
addEventListener: function addEventListener(type, fn) {
var time = this.method.microSeconds();
var listenObj = {
time: time,
fn: fn
};
_addListenerObject(this, type, listenObj);
},
removeEventListener: function removeEventListener(type, fn) {
var obj = this._addEL[type].find(function (obj) {
return obj.fn === fn;
});
_removeListenerObject(this, type, obj);
},
close: function close() {
var _this = this;
if (this.closed) return;
this.closed = true;
var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();
this._onML = null;
this._addEL.message = [];
return awaitPrepare.then(function () {
return Promise.all(_this._befC.map(function (fn) {
return fn();
}));
}).then(function () {
return _this.method.close(_this._state);
});
},
get type() {
return this.method.type;
}
};
function _post(broadcastChannel, type, msg) {
var time = broadcastChannel.method.microSeconds();
var msgObj = {
time: time,
type: type,
data: msg
};
var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();
return awaitPrepare.then(function () {
return broadcastChannel.method.postMessage(broadcastChannel._state, msgObj);
});
}
function _prepareChannel(channel) {
var maybePromise = channel.method.create(channel.name, channel.options);
if (isPromise(maybePromise)) {
channel._prepP = maybePromise;
maybePromise.then(function (s) {
// used in tests to simulate slow runtime
/*if (channel.options.prepareDelay) {
await new Promise(res => setTimeout(res, this.options.prepareDelay));
}*/
channel._state = s;
});
} else {
channel._state = maybePromise;
}
}
function _hasMessageListeners(channel) {
if (channel._addEL.message.length > 0) return true;
if (channel._addEL.internal.length > 0) return true;
return false;
}
function _addListenerObject(channel, type, obj) {
channel._addEL[type].push(obj);
_startListening(channel);
}
function _removeListenerObject(channel, type, obj) {
channel._addEL[type] = channel._addEL[type].filter(function (o) {
return o !== obj;
});
_stopListening(channel);
}
function _startListening(channel) {
if (!channel._iL && _hasMessageListeners(channel)) {
// someone is listening, start subscribing
var listenerFn = function listenerFn(msgObj) {
channel._addEL[msgObj.type].forEach(function (obj) {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
};
var time = channel.method.microSeconds();
if (channel._prepP) {
channel._prepP.then(function () {
channel._iL = true;
channel.method.onMessage(channel._state, listenerFn, time);
});
} else {
channel._iL = true;
channel.method.onMessage(channel._state, listenerFn, time);
}
}
}
function _stopListening(channel) {
if (channel._iL && !_hasMessageListeners(channel)) {
// noone is listening, stop subscribing
channel._iL = false;
var time = channel.method.microSeconds();
channel.method.onMessage(channel._state, null, time);
}
}
export default BroadcastChannel;
export { BroadcastChannel, clearNodeFolder, enforceOptions } from './broadcast-channel';
export { createLeaderElection } from './leader-election';

@@ -154,3 +154,3 @@ /**

options: options,
uuid: randomToken(10),
uuid: randomToken(),

@@ -157,0 +157,0 @@ /**

@@ -46,3 +46,3 @@ /**

var writeObj = {
token: randomToken(10),
token: randomToken(),
time: new Date().getTime(),

@@ -91,3 +91,3 @@ data: messageJson,

var uuid = randomToken(10);
var uuid = randomToken();
/**

@@ -94,0 +94,0 @@ * eMIs

@@ -494,3 +494,3 @@ import _regeneratorRuntime from "@babel/runtime/regenerator";

};
var token = randomToken(12);
var token = randomToken();
var fileName = time + '_' + readerUuid + '_' + token + '.json';

@@ -703,3 +703,3 @@ var msgPath = path.join(paths.messages, fileName);

ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
uuid = randomToken(10);
uuid = randomToken();
state = {

@@ -706,0 +706,0 @@ time: time,

@@ -21,15 +21,7 @@ /**

/**
* https://stackoverflow.com/a/1349426/3443137
* https://stackoverflow.com/a/8084248
*/
export function randomToken(length) {
if (!length) length = 5;
var text = '';
var possible = 'abcdefghijklmnopqrstuvwxzy0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
export function randomToken() {
return Math.random().toString(36).substring(2);
}

@@ -36,0 +28,0 @@ var lastMs = 0;

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var BroadcastChannel = require('./index.es5.js');
var LeaderElection = require('./leader-election/index.es5.js');
window['BroadcastChannel2'] = BroadcastChannel;
window['LeaderElection'] = LeaderElection;
},{"./index.es5.js":2,"./leader-election/index.es5.js":4}],2:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _index = _interopRequireDefault(require("./index.js"));
/**
* because babel can only export on default-attribute,
* we use this for the non-module-build
* this ensures that users do not have to use
* var BroadcastChannel = require('broadcast-channel').default;
* but
* var BroadcastChannel = require('broadcast-channel');
*/
module.exports = _index["default"];
},{"./index.js":3,"@babel/runtime/helpers/interopRequireDefault":14}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.clearNodeFolder = clearNodeFolder;
exports.enforceOptions = enforceOptions;
exports.BroadcastChannel = void 0;

@@ -89,2 +66,3 @@ var _util = require("./util.js");

exports.BroadcastChannel = BroadcastChannel;
BroadcastChannel._pubkey = true;

@@ -96,3 +74,3 @@ /**

BroadcastChannel.clearNodeFolder = function (options) {
function clearNodeFolder(options) {
options = (0, _options.fillOptionsWithDefaults)(options);

@@ -108,3 +86,3 @@ var method = (0, _methodChooser.chooseMethod)(options);

}
};
}
/**

@@ -118,5 +96,5 @@ * if set, this method is enforced,

BroadcastChannel.enforceOptions = function (options) {
function enforceOptions(options) {
ENFORCED_OPTIONS = options;
}; // PROTOTYPE
} // PROTOTYPE

@@ -277,20 +255,67 @@

}
},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(require,module,exports){
"use strict";
var _default = BroadcastChannel;
exports["default"] = _default;
},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],4:[function(require,module,exports){
var _module = require('./index.es5.js');
var BroadcastChannel = _module.BroadcastChannel;
var createLeaderElection = _module.createLeaderElection;
window['BroadcastChannel2'] = BroadcastChannel;
window['createLeaderElection'] = createLeaderElection;
},{"./index.es5.js":3}],3:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _index = require("./index.js");
var _index = _interopRequireDefault(require("./index.js"));
/**
* because babel can only export on default-attribute,
* we use this for the non-module-build
* this ensures that users do not have to use
* var BroadcastChannel = require('broadcast-channel').default;
* but
* var BroadcastChannel = require('broadcast-channel');
*/
module.exports = _index["default"];
},{"./index.js":5,"@babel/runtime/helpers/interopRequireDefault":14}],5:[function(require,module,exports){
module.exports = {
BroadcastChannel: _index.BroadcastChannel,
createLeaderElection: _index.createLeaderElection,
clearNodeFolder: _index.clearNodeFolder,
enforceOptions: _index.enforceOptions
};
},{"./index.js":4}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "BroadcastChannel", {
enumerable: true,
get: function get() {
return _broadcastChannel.BroadcastChannel;
}
});
Object.defineProperty(exports, "clearNodeFolder", {
enumerable: true,
get: function get() {
return _broadcastChannel.clearNodeFolder;
}
});
Object.defineProperty(exports, "enforceOptions", {
enumerable: true,
get: function get() {
return _broadcastChannel.enforceOptions;
}
});
Object.defineProperty(exports, "createLeaderElection", {
enumerable: true,
get: function get() {
return _leaderElection.createLeaderElection;
}
});
var _broadcastChannel = require("./broadcast-channel");
var _leaderElection = require("./leader-election");
},{"./broadcast-channel":1,"./leader-election":5}],5:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

@@ -301,6 +326,5 @@

});
exports.create = create;
exports["default"] = void 0;
exports.createLeaderElection = createLeaderElection;
var _util = require("../util.js");
var _util = require("./util.js");

@@ -314,3 +338,3 @@ var _unload = _interopRequireDefault(require("unload"));

this.isDead = false;
this.token = (0, _util.randomToken)(10);
this.token = (0, _util.randomToken)();
this._isApl = false; // _isApplying

@@ -520,3 +544,3 @@

function create(channel, options) {
function createLeaderElection(channel, options) {
if (channel._leaderElector) {

@@ -536,8 +560,3 @@ throw new Error('BroadcastChannel already has a leader-elector');

}
var _default = {
create: create
};
exports["default"] = _default;
},{"../util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,"unload":19}],6:[function(require,module,exports){
},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,"unload":19}],6:[function(require,module,exports){
"use strict";

@@ -814,3 +833,3 @@

options: options,
uuid: (0, _util.randomToken)(10),
uuid: (0, _util.randomToken)(),

@@ -1018,3 +1037,3 @@ /**

var writeObj = {
token: (0, _util.randomToken)(10),
token: (0, _util.randomToken)(),
time: new Date().getTime(),

@@ -1066,3 +1085,3 @@ data: messageJson,

var uuid = (0, _util.randomToken)(10);
var uuid = (0, _util.randomToken)();
/**

@@ -1421,16 +1440,8 @@ * eMIs

/**
* https://stackoverflow.com/a/1349426/3443137
* https://stackoverflow.com/a/8084248
*/
function randomToken(length) {
if (!length) length = 5;
var text = '';
var possible = 'abcdefghijklmnopqrstuvwxzy0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
function randomToken() {
return Math.random().toString(36).substring(2);
}

@@ -1784,2 +1795,2 @@

exports["default"] = _default;
},{"./browser.js":18,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":14,"detect-node":16}]},{},[1]);
},{"./browser.js":18,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":14,"detect-node":16}]},{},[2]);

@@ -1,1 +0,1 @@

!function i(s,a,u){function c(t,e){if(!a[t]){if(!s[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var o=a[t]={exports:{}};s[t][0].call(o.exports,function(e){return c(s[t][1][e]||e)},o,o.exports,i,s,a,u)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;e<u.length;e++)c(u[e]);return c}({1:[function(e,t,n){"use strict";var r=e("./index.es5.js"),o=e("./leader-election/index.es5.js");window.BroadcastChannel2=r,window.LeaderElection=o},{"./index.es5.js":2,"./leader-election/index.es5.js":4}],2:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault")(e("./index.js"));t.exports=r.default},{"./index.js":3,"@babel/runtime/helpers/interopRequireDefault":14}],3:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;function r(e,t){this.name=e,o&&(t=o),this.options=(0,a.fillOptionsWithDefaults)(t),this.method=(0,s.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._befC=[],this._prepP=null,function(t){var e=t.method.create(t.name,t.options);(0,i.isPromise)(e)?(t._prepP=e).then(function(e){t._state=e}):t._state=e}(this)}var o,i=e("./util.js"),s=e("./method-chooser.js"),a=e("./options.js");function u(e,t,n){var r={time:e.method.microSeconds(),type:t,data:n};return(e._prepP?e._prepP:Promise.resolve()).then(function(){return e.method.postMessage(e._state,r)})}function c(e){return 0<e._addEL.message.length||0<e._addEL.internal.length}function l(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 d(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)}r._pubkey=!0,r.clearNodeFolder=function(e){e=(0,a.fillOptionsWithDefaults)(e);var t=(0,s.chooseMethod)(e);return"node"===t.type?t.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},r.enforceOptions=function(e){o=e},r.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return u(this,"message",e)},postInternal:function(e){return u(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};d(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,l(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();l(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});d(this,e,n)},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(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}};var f=r;n.default=f},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],4:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault")(e("./index.js"));t.exports=r.default},{"./index.js":5,"@babel/runtime/helpers/interopRequireDefault":14}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.create=u,n.default=void 0;var i=e("../util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(10),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}function u(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 o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n}o.prototype={applyOnce:function(){var t=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);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);function n(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")}return t._channel.addEventListener("internal",n),t._lstns.push(n),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){return this._aLP||(this._aLP=function(i){return i.isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})}(this)),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}};var c={create:u};n.default=c},{"../util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,c).filter(Boolean);if(t.type){if("simulate"===t.type)return a.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||u.isNode||(e=e.filter(function(e){return"idb"!==e.type}));var r=e.find(function(e){return e.canBeUsed()});{if(r)return r;throw new Error("No useable methode found:"+JSON.stringify(c.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),s=r(e("./methods/localstorage.js")),a=r(e("./methods/simulate.js")),u=e("./util"),c=[o.default,i.default,s.default];if(u.isNode){var l=e("../../src/methods/node.js");"function"==typeof l.canBeUsed&&c.push(l)}},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=l,n.createDatabase=d,n.writeMessage=f,n.getAllMessages=function(e){var t=e.transaction(c).objectStore(c),r=[];return new Promise(function(n){t.openCursor().onsuccess=function(e){var t=e.target.result;t?(r.push(t.value),t.continue()):n(r)}})},n.getMessagesHigherThen=h,n.removeMessageById=p,n.getOldMessages=m,n.cleanOldMessages=v,n.create=b,n.close=w,n.postMessage=_,n.onMessage=y,n.canBeUsed=k,n.averageResponseTime=M,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),a=o.microSeconds;n.microSeconds=a;var u="pubkey.broadcast-channel-0-",c="messages";function l(){return"undefined"!=typeof indexedDB?indexedDB:void 0!==window.mozIndexedDB?window.mozIndexedDB:void 0!==window.webkitIndexedDB?window.webkitIndexedDB:void 0!==window.msIndexedDB&&window.msIndexedDB}function d(e){var t=l(),n=u+e,r=t.open(n,1);return r.onupgradeneeded=function(e){e.target.result.createObjectStore(c,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){r.onerror=function(e){return t(e)},r.onsuccess=function(){e(r.result)}})}function f(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([c],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(c).add(r)})}function h(e,t){var r=e.transaction(c).objectStore(c),o=[],i=IDBKeyRange.bound(t+1,1/0);return new Promise(function(n){r.openCursor(i).onsuccess=function(e){var t=e.target.result;t?(o.push(t.value),t.continue()):n(o)}})}function p(e,t){var n=e.transaction([c],"readwrite").objectStore(c).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function m(e,t){var o=(new Date).getTime()-t,n=e.transaction(c).objectStore(c),i=[];return new Promise(function(r){n.openCursor().onsuccess=function(e){var t=e.target.result;if(t){var n=t.value;if(!(n.time<o))return void r(i);i.push(n),t.continue()}else r(i)}})}function v(t,e){return m(t,e).then(function(e){return Promise.all(e.map(function(e){return p(t,e.id)}))})}function b(n,r){return r=(0,s.fillOptionsWithDefaults)(r),d(n).then(function(e){var t={closed:!1,lastCursorId:0,channelName:n,options:r,uuid:(0,o.randomToken)(10),eMIs:new i.default(2*r.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:e};return function e(t){if(t.closed)return;return g(t).then(function(){return(0,o.sleep)(t.options.idb.fallbackInterval)}).then(function(){return e(t)})}(t),t})}function g(t){return t.closed?Promise.resolve():t.messagesCallback?h(t.db,t.lastCursorId).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return e.id>t.lastCursorId&&(t.lastCursorId=e.id),e}).filter(function(e){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time<t.messagesCallbackTime))}(e,t)}).sort(function(e,t){return e.time-t.time}).forEach(function(e){t.messagesCallback&&(t.eMIs.add(e.id),t.messagesCallback(e.data))}),Promise.resolve()}):Promise.resolve()}function w(e){e.closed=!0,e.db.close()}function _(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return f(e.db,e.uuid,t)}).then(function(){0===(0,o.randomInt)(0,10)&&v(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function y(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,g(e)}function k(){return!o.isNode&&!!l()}function M(e){return 2*e.idb.fallbackInterval}var P={create:b,close:w,onMessage:y,postMessage:_,canBeUsed:k,type:n.type="idb",averageResponseTime:M,microSeconds:a};n.default=P},{"../oblivious-set":11,"../options":12,"../util.js":13,"@babel/runtime/helpers/interopRequireDefault":14}],8:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getLocalStorage=l,n.storageKey=d,n.postMessage=f,n.addStorageEventListener=h,n.removeStorageEventListener=p,n.create=m,n.close=v,n.onMessage=b,n.canBeUsed=g,n.averageResponseTime=w,n.default=n.type=n.microSeconds=void 0;var i=r(e("../oblivious-set")),s=e("../options"),a=e("../util"),o=a.microSeconds;n.microSeconds=o;var u="pubkey.broadcastChannel-",c="localstorage";function l(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function d(e){return u+e}function f(i,s){return new Promise(function(o){(0,a.sleep)().then(function(){var e=d(i.channelName),t={token:(0,a.randomToken)(10),time:(new Date).getTime(),data:s,uuid:i.uuid},n=JSON.stringify(t);l().setItem(e,n);var r=document.createEvent("Event");r.initEvent("storage",!0,!0),r.key=e,r.newValue=n,window.dispatchEvent(r),o()})})}function h(e,t){function n(e){e.key===r&&t(JSON.parse(e.newValue))}var r=d(e);return window.addEventListener("storage",n),n}function p(e){window.removeEventListener("storage",e)}function m(e,t){if(t=(0,s.fillOptionsWithDefaults)(t),!g())throw new Error("BroadcastChannel: localstorage cannot be used");var n=(0,a.randomToken)(10),r=new i.default(t.localstorage.removeTimeout),o={channelName:e,uuid:n,eMIs:r};return o.listener=h(e,function(e){o.messagesCallback&&e.uuid!==n&&e.token&&!r.has(e.token)&&(e.data.time&&e.data.time<o.messagesCallbackTime||(r.add(e.token),o.messagesCallback(e.data)))}),o}function v(e){p(e.listener)}function b(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function g(){if(a.isNode)return!1;var e=l();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch(e){return!1}return!0}function w(){return 120}var _={create:m,close:v,onMessage:b,postMessage:f,canBeUsed:g,type:n.type=c,averageResponseTime:w,microSeconds:o};n.default=_},{"../oblivious-set":11,"../options":12,"../util":13,"@babel/runtime/helpers/interopRequireDefault":14}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=i,n.close=s,n.postMessage=a,n.onMessage=u,n.canBeUsed=c,n.averageResponseTime=l,n.default=n.type=n.microSeconds=void 0;var r=e("../util"),o=r.microSeconds;n.microSeconds=o;function i(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function s(e){e.bc.close(),e.subFns=[]}function a(e,t){e.bc.postMessage(t,!1)}function u(e,t){e.messagesCallback=t}function c(){if(r.isNode&&"undefined"==typeof window)return!1;if("function"!=typeof BroadcastChannel)return!1;if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}function l(){return 150}var d={create:i,close:s,onMessage:u,postMessage:a,canBeUsed:c,type:n.type="native",averageResponseTime:l,microSeconds:o};n.default=d},{"../util":13}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=s,n.close=a,n.postMessage=u,n.onMessage=c,n.canBeUsed=l,n.averageResponseTime=d,n.default=n.type=n.microSeconds=void 0;var r=e("../util").microSeconds;n.microSeconds=r;var o="simulate";n.type=o;var i=new Set;function s(e){var t={name:e,messagesCallback:null};return i.add(t),t}function a(e){i.delete(e)}function u(t,n){return new Promise(function(e){return setTimeout(function(){Array.from(i).filter(function(e){return e.name===t.name}).filter(function(e){return e!==t}).filter(function(e){return!!e.messagesCallback}).forEach(function(e){return e.messagesCallback(n)}),e()},5)})}function c(e,t){e.messagesCallback=t}function l(){return!0}function d(){return 5}var f={create:s,close:a,onMessage:c,postMessage:u,canBeUsed:l,type:o,averageResponseTime:d,microSeconds:r};n.default=f},{"../util":13}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;function s(){return(new Date).getTime()}function r(r){var o=new Set,i=new Map;this.has=o.has.bind(o),this.add=function(e){i.set(e,s()),o.add(e),function(){var e=s()-r,t=o[Symbol.iterator]();for(;;){var n=t.next().value;if(!n)return;if(!(i.get(n)<e))return;i.delete(n),o.delete(n)}}()},this.clear=function(){o.clear(),i.clear()}}n.default=r},{}],12:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.fillOptionsWithDefaults=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));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);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);return t}},{}],13:[function(e,t,o){(function(e){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.isPromise=function(e){return!(!e||"function"!=typeof e.then)},o.sleep=function(t){t=t||0;return new Promise(function(e){return setTimeout(e,t)})},o.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},o.randomToken=function(e){e=e||5;for(var t="",n="abcdefghijklmnopqrstuvwxzy0123456789",r=0;r<e;r++)t+=n.charAt(Math.floor(Math.random()*n.length));return t},o.microSeconds=function(){var e=(new Date).getTime();return e===t?1e3*e+ ++n:(n=0,1e3*(t=e))},o.isNode=void 0;var t=0,n=0;var r="[object process]"===Object.prototype.toString.call(void 0!==e?e:0);o.isNode=r}).call(this,e("_process"))},{_process:17}],14:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}}},{}],15:[function(e,t,n){},{}],16:[function(e,t,n){t.exports=!1},{}],17:[function(e,t,n){var r,o,i=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(t){if(r===setTimeout)return setTimeout(t,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(e){o=a}}();var c,l=[],d=!1,f=-1;function h(){d&&c&&(d=!1,c.length?l=c.concat(l):f=-1,l.length&&p())}function p(){if(!d){var e=u(h);d=!0;for(var t=l.length;t;){for(c=l,l=[];++f<t;)c&&c[f].run();f=-1,t=l.length}c=null,d=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===a||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(e){try{return o.call(null,t)}catch(e){return o.call(this,t)}}}(e)}}function m(e,t){this.fun=e,this.array=t}function v(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new m(e,t)),1!==l.length||d||u(p)},m.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=v,i.addListener=v,i.once=v,i.off=v,i.removeListener=v,i.removeAllListeners=v,i.emit=v,i.prependListener=v,i.prependOnceListener=v,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],18:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r={add:function(e){if(!("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope)){if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0)}}};n.default=r},{}],19:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.add=l,n.runAll=d,n.removeAll=f,n.getSize=h,n.default=void 0;var o=r(e("detect-node")),i=r(e("./browser.js")),s=r(e("./node.js")),a=o.default?s.default:i.default,u=new Set,c=!1;function l(e){if(c||(c=!0,a.add(d)),"function"!=typeof e)throw new Error("Listener is no function");return u.add(e),{remove:function(){return u.delete(e)},run:function(){return u.delete(e),e()}}}function d(){var t=[];return u.forEach(function(e){t.push(e()),u.delete(e)}),Promise.all(t)}function f(){u.clear()}function h(){return u.size}var p={add:l,runAll:d,removeAll:f,getSize:h};n.default=p},{"./browser.js":18,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":14,"detect-node":16}]},{},[1]);
!function i(s,a,u){function c(t,e){if(!a[t]){if(!s[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var o=a[t]={exports:{}};s[t][0].call(o.exports,function(e){return c(s[t][1][e]||e)},o,o.exports,i,s,a,u)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;e<u.length;e++)c(u[e]);return c}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.clearNodeFolder=function(e){e=(0,a.fillOptionsWithDefaults)(e);var t=(0,s.chooseMethod)(e);return"node"===t.type?t.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},n.enforceOptions=function(e){o=e},n.BroadcastChannel=void 0;function r(e,t){this.name=e,o&&(t=o),this.options=(0,a.fillOptionsWithDefaults)(t),this.method=(0,s.chooseMethod)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._befC=[],this._prepP=null,function(t){var e=t.method.create(t.name,t.options);(0,i.isPromise)(e)?(t._prepP=e).then(function(e){t._state=e}):t._state=e}(this)}var o,i=e("./util.js"),s=e("./method-chooser.js"),a=e("./options.js");function u(e,t,n){var r={time:e.method.microSeconds(),type:t,data:n};return(e._prepP?e._prepP:Promise.resolve()).then(function(){return e.method.postMessage(e._state,r)})}function c(e){return 0<e._addEL.message.length||0<e._addEL.internal.length}function l(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 d(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)}(n.BroadcastChannel=r)._pubkey=!0,r.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return u(this,"message",e)},postInternal:function(e){return u(this,"internal",e)},set onmessage(e){var t={time:this.method.microSeconds(),fn:e};d(this,"message",this._onML),e&&"function"==typeof e?(this._onML=t,l(this,"message",t)):this._onML=null},addEventListener:function(e,t){var n=this.method.microSeconds();l(this,e,{time:n,fn:t})},removeEventListener:function(e,t){var n=this._addEL[e].find(function(e){return e.fn===t});d(this,e,n)},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(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}}},{"./method-chooser.js":6,"./options.js":12,"./util.js":13}],2:[function(e,t,n){"use strict";var r=e("./index.es5.js"),o=r.BroadcastChannel,i=r.createLeaderElection;window.BroadcastChannel2=o,window.createLeaderElection=i},{"./index.es5.js":3}],3:[function(e,t,n){"use strict";var r=e("./index.js");t.exports={BroadcastChannel:r.BroadcastChannel,createLeaderElection:r.createLeaderElection,clearNodeFolder:r.clearNodeFolder,enforceOptions:r.enforceOptions}},{"./index.js":4}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BroadcastChannel",{enumerable:!0,get:function(){return r.BroadcastChannel}}),Object.defineProperty(n,"clearNodeFolder",{enumerable:!0,get:function(){return r.clearNodeFolder}}),Object.defineProperty(n,"enforceOptions",{enumerable:!0,get:function(){return r.enforceOptions}}),Object.defineProperty(n,"createLeaderElection",{enumerable:!0,get:function(){return o.createLeaderElection}});var r=e("./broadcast-channel"),o=e("./leader-election")},{"./broadcast-channel":1,"./leader-election":5}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.createLeaderElection=function(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=function(e,t){e=e||{};(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3);e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options));return e}(t,e);var n=new o(e,t);return e._befC.push(function(){return n.die()}),e._leaderElector=n};var i=e("./util.js"),s=r(e("unload")),o=function(e,t){this._channel=e,this._options=t,this.isLeader=!1,this.isDead=!1,this.token=(0,i.randomToken)(),this._isApl=!1,this._reApply=!1,this._unl=[],this._lstns=[],this._invs=[]};function a(e,t){var n={context:"leader",action:t,token:e.token};return e._channel.postInternal(n)}o.prototype={applyOnce:function(){var t=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);function n(e){"leader"===e.context&&e.token!=t.token&&(o.push(e),"apply"===e.action&&e.token>t.token&&(r=!0),"tell"===e.action&&(r=!0))}var r=!(this._isApl=!0),o=[];return this._channel.addEventListener("internal",n),a(this,"apply").then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t,"apply")}).then(function(){return(0,i.sleep)(t._options.responseTime)}).then(function(){return r?Promise.reject(new Error):a(t)}).then(function(){return function(t){t.isLeader=!0;var e=s.default.add(function(){return t.die()});t._unl.push(e);function n(e){"leader"===e.context&&"apply"===e.action&&a(t,"tell")}return t._channel.addEventListener("internal",n),t._lstns.push(n),a(t,"tell")}(t)}).then(function(){return!0}).catch(function(){return!1}).then(function(e){return t._channel.removeEventListener("internal",n),t._isApl=!1,!e&&t._reApply?(t._reApply=!1,t.applyOnce()):e})},awaitLeadership:function(){return this._aLP||(this._aLP=function(i){return i.isLeader?Promise.resolve():new Promise(function(e){function t(){n||(n=!0,clearInterval(r),i._channel.removeEventListener("internal",o),e(!0))}var n=!1;i.applyOnce().then(function(){i.isLeader&&t()});var r=setInterval(function(){i.applyOnce().then(function(){i.isLeader&&t()})},i._options.fallbackInterval);i._invs.push(r);var o=function(e){"leader"===e.context&&"death"===e.action&&i.applyOnce().then(function(){i.isLeader&&t()})};i._channel.addEventListener("internal",o),i._lstns.push(o)})}(this)),this._aLP},die:function(){var t=this;if(!this.isDead)return this.isDead=!0,this._lstns.forEach(function(e){return t._channel.removeEventListener("internal",e)}),this._invs.forEach(function(e){return clearInterval(e)}),this._unl.forEach(function(e){e.remove()}),a(this,"death")}}},{"./util.js":13,"@babel/runtime/helpers/interopRequireDefault":14,unload:19}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.chooseMethod=function(t){var e=[].concat(t.methods,c).filter(Boolean);if(t.type){if("simulate"===t.type)return a.default;var n=e.find(function(e){return e.type===t.type});if(n)return n;throw new Error("method-type "+t.type+" not found")}t.webWorkerSupport||u.isNode||(e=e.filter(function(e){return"idb"!==e.type}));var r=e.find(function(e){return e.canBeUsed()});{if(r)return r;throw new Error("No useable methode found:"+JSON.stringify(c.map(function(e){return e.type})))}};var o=r(e("./methods/native.js")),i=r(e("./methods/indexed-db.js")),s=r(e("./methods/localstorage.js")),a=r(e("./methods/simulate.js")),u=e("./util"),c=[o.default,i.default,s.default];if(u.isNode){var l=e("../../src/methods/node.js");"function"==typeof l.canBeUsed&&c.push(l)}},{"./methods/indexed-db.js":7,"./methods/localstorage.js":8,"./methods/native.js":9,"./methods/simulate.js":10,"./util":13,"@babel/runtime/helpers/interopRequireDefault":14}],7:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getIdb=l,n.createDatabase=d,n.writeMessage=f,n.getAllMessages=function(e){var t=e.transaction(c).objectStore(c),r=[];return new Promise(function(n){t.openCursor().onsuccess=function(e){var t=e.target.result;t?(r.push(t.value),t.continue()):n(r)}})},n.getMessagesHigherThen=h,n.removeMessageById=p,n.getOldMessages=m,n.cleanOldMessages=v,n.create=b,n.close=w,n.postMessage=_,n.onMessage=y,n.canBeUsed=k,n.averageResponseTime=P,n.default=n.type=n.microSeconds=void 0;var o=e("../util.js"),i=r(e("../oblivious-set")),s=e("../options"),a=o.microSeconds;n.microSeconds=a;var u="pubkey.broadcast-channel-0-",c="messages";function l(){return"undefined"!=typeof indexedDB?indexedDB:void 0!==window.mozIndexedDB?window.mozIndexedDB:void 0!==window.webkitIndexedDB?window.webkitIndexedDB:void 0!==window.msIndexedDB&&window.msIndexedDB}function d(e){var t=l(),n=u+e,r=t.open(n,1);return r.onupgradeneeded=function(e){e.target.result.createObjectStore(c,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){r.onerror=function(e){return t(e)},r.onsuccess=function(){e(r.result)}})}function f(e,t,n){var r={uuid:t,time:(new Date).getTime(),data:n},o=e.transaction([c],"readwrite");return new Promise(function(e,t){o.oncomplete=function(){return e()},o.onerror=function(e){return t(e)},o.objectStore(c).add(r)})}function h(e,t){var r=e.transaction(c).objectStore(c),o=[],i=IDBKeyRange.bound(t+1,1/0);return new Promise(function(n){r.openCursor(i).onsuccess=function(e){var t=e.target.result;t?(o.push(t.value),t.continue()):n(o)}})}function p(e,t){var n=e.transaction([c],"readwrite").objectStore(c).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function m(e,t){var o=(new Date).getTime()-t,n=e.transaction(c).objectStore(c),i=[];return new Promise(function(r){n.openCursor().onsuccess=function(e){var t=e.target.result;if(t){var n=t.value;if(!(n.time<o))return void r(i);i.push(n),t.continue()}else r(i)}})}function v(t,e){return m(t,e).then(function(e){return Promise.all(e.map(function(e){return p(t,e.id)}))})}function b(n,r){return r=(0,s.fillOptionsWithDefaults)(r),d(n).then(function(e){var t={closed:!1,lastCursorId:0,channelName:n,options:r,uuid:(0,o.randomToken)(),eMIs:new i.default(2*r.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:e};return function e(t){if(t.closed)return;return g(t).then(function(){return(0,o.sleep)(t.options.idb.fallbackInterval)}).then(function(){return e(t)})}(t),t})}function g(t){return t.closed?Promise.resolve():t.messagesCallback?h(t.db,t.lastCursorId).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return e.id>t.lastCursorId&&(t.lastCursorId=e.id),e}).filter(function(e){return function(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time<t.messagesCallbackTime))}(e,t)}).sort(function(e,t){return e.time-t.time}).forEach(function(e){t.messagesCallback&&(t.eMIs.add(e.id),t.messagesCallback(e.data))}),Promise.resolve()}):Promise.resolve()}function w(e){e.closed=!0,e.db.close()}function _(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return f(e.db,e.uuid,t)}).then(function(){0===(0,o.randomInt)(0,10)&&v(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function y(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,g(e)}function k(){return!o.isNode&&!!l()}function P(e){return 2*e.idb.fallbackInterval}var L={create:b,close:w,onMessage:y,postMessage:_,canBeUsed:k,type:n.type="idb",averageResponseTime:P,microSeconds:a};n.default=L},{"../oblivious-set":11,"../options":12,"../util.js":13,"@babel/runtime/helpers/interopRequireDefault":14}],8:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.getLocalStorage=l,n.storageKey=d,n.postMessage=f,n.addStorageEventListener=h,n.removeStorageEventListener=p,n.create=m,n.close=v,n.onMessage=b,n.canBeUsed=g,n.averageResponseTime=w,n.default=n.type=n.microSeconds=void 0;var i=r(e("../oblivious-set")),s=e("../options"),a=e("../util"),o=a.microSeconds;n.microSeconds=o;var u="pubkey.broadcastChannel-",c="localstorage";function l(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function d(e){return u+e}function f(i,s){return new Promise(function(o){(0,a.sleep)().then(function(){var e=d(i.channelName),t={token:(0,a.randomToken)(),time:(new Date).getTime(),data:s,uuid:i.uuid},n=JSON.stringify(t);l().setItem(e,n);var r=document.createEvent("Event");r.initEvent("storage",!0,!0),r.key=e,r.newValue=n,window.dispatchEvent(r),o()})})}function h(e,t){function n(e){e.key===r&&t(JSON.parse(e.newValue))}var r=d(e);return window.addEventListener("storage",n),n}function p(e){window.removeEventListener("storage",e)}function m(e,t){if(t=(0,s.fillOptionsWithDefaults)(t),!g())throw new Error("BroadcastChannel: localstorage cannot be used");var n=(0,a.randomToken)(),r=new i.default(t.localstorage.removeTimeout),o={channelName:e,uuid:n,eMIs:r};return o.listener=h(e,function(e){o.messagesCallback&&e.uuid!==n&&e.token&&!r.has(e.token)&&(e.data.time&&e.data.time<o.messagesCallbackTime||(r.add(e.token),o.messagesCallback(e.data)))}),o}function v(e){p(e.listener)}function b(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function g(){if(a.isNode)return!1;var e=l();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch(e){return!1}return!0}function w(){return 120}var _={create:m,close:v,onMessage:b,postMessage:f,canBeUsed:g,type:n.type=c,averageResponseTime:w,microSeconds:o};n.default=_},{"../oblivious-set":11,"../options":12,"../util":13,"@babel/runtime/helpers/interopRequireDefault":14}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=i,n.close=s,n.postMessage=a,n.onMessage=u,n.canBeUsed=c,n.averageResponseTime=l,n.default=n.type=n.microSeconds=void 0;var r=e("../util"),o=r.microSeconds;n.microSeconds=o;function i(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function s(e){e.bc.close(),e.subFns=[]}function a(e,t){e.bc.postMessage(t,!1)}function u(e,t){e.messagesCallback=t}function c(){if(r.isNode&&"undefined"==typeof window)return!1;if("function"!=typeof BroadcastChannel)return!1;if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}function l(){return 150}var d={create:i,close:s,onMessage:u,postMessage:a,canBeUsed:c,type:n.type="native",averageResponseTime:l,microSeconds:o};n.default=d},{"../util":13}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.create=s,n.close=a,n.postMessage=u,n.onMessage=c,n.canBeUsed=l,n.averageResponseTime=d,n.default=n.type=n.microSeconds=void 0;var r=e("../util").microSeconds;n.microSeconds=r;var o="simulate";n.type=o;var i=new Set;function s(e){var t={name:e,messagesCallback:null};return i.add(t),t}function a(e){i.delete(e)}function u(t,n){return new Promise(function(e){return setTimeout(function(){Array.from(i).filter(function(e){return e.name===t.name}).filter(function(e){return e!==t}).filter(function(e){return!!e.messagesCallback}).forEach(function(e){return e.messagesCallback(n)}),e()},5)})}function c(e,t){e.messagesCallback=t}function l(){return!0}function d(){return 5}var f={create:s,close:a,onMessage:c,postMessage:u,canBeUsed:l,type:o,averageResponseTime:d,microSeconds:r};n.default=f},{"../util":13}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;function s(){return(new Date).getTime()}function r(r){var o=new Set,i=new Map;this.has=o.has.bind(o),this.add=function(e){i.set(e,s()),o.add(e),function(){var e=s()-r,t=o[Symbol.iterator]();for(;;){var n=t.next().value;if(!n)return;if(!(i.get(n)<e))return;i.delete(n),o.delete(n)}}()},this.clear=function(){o.clear(),i.clear()}}n.default=r},{}],12:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.fillOptionsWithDefaults=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=JSON.parse(JSON.stringify(e));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);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);return t}},{}],13:[function(e,t,o){(function(e){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.isPromise=function(e){return!(!e||"function"!=typeof e.then)},o.sleep=function(t){t=t||0;return new Promise(function(e){return setTimeout(e,t)})},o.randomInt=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)},o.randomToken=function(){return Math.random().toString(36).substring(2)},o.microSeconds=function(){var e=(new Date).getTime();return e===t?1e3*e+ ++n:(n=0,1e3*(t=e))},o.isNode=void 0;var t=0,n=0;var r="[object process]"===Object.prototype.toString.call(void 0!==e?e:0);o.isNode=r}).call(this,e("_process"))},{_process:17}],14:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}}},{}],15:[function(e,t,n){},{}],16:[function(e,t,n){t.exports=!1},{}],17:[function(e,t,n){var r,o,i=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(t){if(r===setTimeout)return setTimeout(t,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(e){o=a}}();var c,l=[],d=!1,f=-1;function h(){d&&c&&(d=!1,c.length?l=c.concat(l):f=-1,l.length&&p())}function p(){if(!d){var e=u(h);d=!0;for(var t=l.length;t;){for(c=l,l=[];++f<t;)c&&c[f].run();f=-1,t=l.length}c=null,d=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===a||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(e){try{return o.call(null,t)}catch(e){return o.call(this,t)}}}(e)}}function m(e,t){this.fun=e,this.array=t}function v(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new m(e,t)),1!==l.length||d||u(p)},m.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=v,i.addListener=v,i.once=v,i.off=v,i.removeListener=v,i.removeAllListeners=v,i.emit=v,i.prependListener=v,i.prependOnceListener=v,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],18:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r={add:function(e){if(!("function"==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope)){if("function"!=typeof window.addEventListener)return;window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0)}}};n.default=r},{}],19:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.add=l,n.runAll=d,n.removeAll=f,n.getSize=h,n.default=void 0;var o=r(e("detect-node")),i=r(e("./browser.js")),s=r(e("./node.js")),a=o.default?s.default:i.default,u=new Set,c=!1;function l(e){if(c||(c=!0,a.add(d)),"function"!=typeof e)throw new Error("Listener is no function");return u.add(e),{remove:function(){return u.delete(e)},run:function(){return u.delete(e),e()}}}function d(){var t=[];return u.forEach(function(e){t.push(e()),u.delete(e)}),Promise.all(t)}function f(){u.clear()}function h(){return u.size}var p={add:l,runAll:d,removeAll:f,getSize:h};n.default=p},{"./browser.js":18,"./node.js":15,"@babel/runtime/helpers/interopRequireDefault":14,"detect-node":16}]},{},[2]);
"use strict";
var BroadcastChannel = require('./index.es5.js');
var _module = require('./index.es5.js');
var LeaderElection = require('./leader-election/index.es5.js');
var BroadcastChannel = _module.BroadcastChannel;
var createLeaderElection = _module.createLeaderElection;
window['BroadcastChannel2'] = BroadcastChannel;
window['LeaderElection'] = LeaderElection;
window['createLeaderElection'] = createLeaderElection;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _index = require("./index.js");
var _index = _interopRequireDefault(require("./index.js"));
/**

@@ -15,2 +13,7 @@ * because babel can only export on default-attribute,

*/
module.exports = _index["default"];
module.exports = {
BroadcastChannel: _index.BroadcastChannel,
createLeaderElection: _index.createLeaderElection,
clearNodeFolder: _index.clearNodeFolder,
enforceOptions: _index.enforceOptions
};

@@ -6,245 +6,29 @@ "use strict";

});
exports["default"] = void 0;
var _util = require("./util.js");
var _methodChooser = require("./method-chooser.js");
var _options = require("./options.js");
var BroadcastChannel = function BroadcastChannel(name, options) {
this.name = name;
if (ENFORCED_OPTIONS) {
options = ENFORCED_OPTIONS;
Object.defineProperty(exports, "BroadcastChannel", {
enumerable: true,
get: function get() {
return _broadcastChannel.BroadcastChannel;
}
this.options = (0, _options.fillOptionsWithDefaults)(options);
this.method = (0, _methodChooser.chooseMethod)(this.options); // isListening
this._iL = false;
/**
* _onMessageListener
* setting onmessage twice,
* will overwrite the first listener
*/
this._onML = null;
/**
* _addEventListeners
*/
this._addEL = {
message: [],
internal: []
};
/**
* _beforeClose
* array of promises that will be awaited
* before the channel is closed
*/
this._befC = [];
/**
* _preparePromise
*/
this._prepP = null;
_prepareChannel(this);
}; // STATICS
/**
* used to identify if someone overwrites
* window.BroadcastChannel with this
* See methods/native.js
*/
BroadcastChannel._pubkey = true;
/**
* clears the tmp-folder if is node
* @return {Promise<boolean>} true if has run, false if not node
*/
BroadcastChannel.clearNodeFolder = function (options) {
options = (0, _options.fillOptionsWithDefaults)(options);
var method = (0, _methodChooser.chooseMethod)(options);
if (method.type === 'node') {
return method.clearNodeFolder().then(function () {
return true;
});
} else {
return Promise.resolve(false);
});
Object.defineProperty(exports, "clearNodeFolder", {
enumerable: true,
get: function get() {
return _broadcastChannel.clearNodeFolder;
}
};
/**
* if set, this method is enforced,
* no mather what the options are
*/
var ENFORCED_OPTIONS;
BroadcastChannel.enforceOptions = function (options) {
ENFORCED_OPTIONS = options;
}; // PROTOTYPE
BroadcastChannel.prototype = {
postMessage: function postMessage(msg) {
if (this.closed) {
throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');
}
return _post(this, 'message', msg);
},
postInternal: function postInternal(msg) {
return _post(this, 'internal', msg);
},
set onmessage(fn) {
var time = this.method.microSeconds();
var listenObj = {
time: time,
fn: fn
};
_removeListenerObject(this, 'message', this._onML);
if (fn && typeof fn === 'function') {
this._onML = listenObj;
_addListenerObject(this, 'message', listenObj);
} else {
this._onML = null;
}
},
addEventListener: function addEventListener(type, fn) {
var time = this.method.microSeconds();
var listenObj = {
time: time,
fn: fn
};
_addListenerObject(this, type, listenObj);
},
removeEventListener: function removeEventListener(type, fn) {
var obj = this._addEL[type].find(function (obj) {
return obj.fn === fn;
});
_removeListenerObject(this, type, obj);
},
close: function close() {
var _this = this;
if (this.closed) return;
this.closed = true;
var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();
this._onML = null;
this._addEL.message = [];
return awaitPrepare.then(function () {
return Promise.all(_this._befC.map(function (fn) {
return fn();
}));
}).then(function () {
return _this.method.close(_this._state);
});
},
get type() {
return this.method.type;
});
Object.defineProperty(exports, "enforceOptions", {
enumerable: true,
get: function get() {
return _broadcastChannel.enforceOptions;
}
};
function _post(broadcastChannel, type, msg) {
var time = broadcastChannel.method.microSeconds();
var msgObj = {
time: time,
type: type,
data: msg
};
var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();
return awaitPrepare.then(function () {
return broadcastChannel.method.postMessage(broadcastChannel._state, msgObj);
});
}
function _prepareChannel(channel) {
var maybePromise = channel.method.create(channel.name, channel.options);
if ((0, _util.isPromise)(maybePromise)) {
channel._prepP = maybePromise;
maybePromise.then(function (s) {
// used in tests to simulate slow runtime
/*if (channel.options.prepareDelay) {
await new Promise(res => setTimeout(res, this.options.prepareDelay));
}*/
channel._state = s;
});
} else {
channel._state = maybePromise;
});
Object.defineProperty(exports, "createLeaderElection", {
enumerable: true,
get: function get() {
return _leaderElection.createLeaderElection;
}
}
});
function _hasMessageListeners(channel) {
if (channel._addEL.message.length > 0) return true;
if (channel._addEL.internal.length > 0) return true;
return false;
}
var _broadcastChannel = require("./broadcast-channel");
function _addListenerObject(channel, type, obj) {
channel._addEL[type].push(obj);
_startListening(channel);
}
function _removeListenerObject(channel, type, obj) {
channel._addEL[type] = channel._addEL[type].filter(function (o) {
return o !== obj;
});
_stopListening(channel);
}
function _startListening(channel) {
if (!channel._iL && _hasMessageListeners(channel)) {
// someone is listening, start subscribing
var listenerFn = function listenerFn(msgObj) {
channel._addEL[msgObj.type].forEach(function (obj) {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
};
var time = channel.method.microSeconds();
if (channel._prepP) {
channel._prepP.then(function () {
channel._iL = true;
channel.method.onMessage(channel._state, listenerFn, time);
});
} else {
channel._iL = true;
channel.method.onMessage(channel._state, listenerFn, time);
}
}
}
function _stopListening(channel) {
if (channel._iL && !_hasMessageListeners(channel)) {
// noone is listening, stop subscribing
channel._iL = false;
var time = channel.method.microSeconds();
channel.method.onMessage(channel._state, null, time);
}
}
var _default = BroadcastChannel;
exports["default"] = _default;
var _leaderElection = require("./leader-election");

@@ -191,3 +191,3 @@ "use strict";

options: options,
uuid: (0, _util.randomToken)(10),
uuid: (0, _util.randomToken)(),

@@ -194,0 +194,0 @@ /**

@@ -73,3 +73,3 @@ "use strict";

var writeObj = {
token: (0, _util.randomToken)(10),
token: (0, _util.randomToken)(),
time: new Date().getTime(),

@@ -121,3 +121,3 @@ data: messageJson,

var uuid = (0, _util.randomToken)(10);
var uuid = (0, _util.randomToken)();
/**

@@ -124,0 +124,0 @@ * eMIs

@@ -499,3 +499,3 @@ "use strict";

};
var token = randomToken(12);
var token = randomToken();
var fileName = time + '_' + readerUuid + '_' + token + '.json';

@@ -708,3 +708,3 @@ var msgPath = path.join(paths.messages, fileName);

ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
uuid = randomToken(10);
uuid = randomToken();
state = {

@@ -711,0 +711,0 @@ time: time,

@@ -35,16 +35,8 @@ "use strict";

/**
* https://stackoverflow.com/a/1349426/3443137
* https://stackoverflow.com/a/8084248
*/
function randomToken(length) {
if (!length) length = 5;
var text = '';
var possible = 'abcdefghijklmnopqrstuvwxzy0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
function randomToken() {
return Math.random().toString(36).substring(2);
}

@@ -51,0 +43,0 @@

{
"name": "broadcast-channel",
"version": "2.3.4",
"version": "3.0.0",
"description": "A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers and NodeJs",

@@ -30,9 +30,10 @@ "homepage": "https://github.com/pubkey/broadcast-channel#readme",

"module": "./dist/es/index.js",
"types": "index.d.ts",
"sideEffects": false,
"types": "./types/index.d.ts",
"scripts": {
"test:all": "echo \"RUN ALL:\" && npm run test:node && npm run test:browser && npm run test:e2e",
"test": "echo \"RUN ALL:\" && npm run test:node && npm run test:browser && npm run test:e2e",
"test:node": "npm run build && mocha ./test/index.test.js -b --timeout 6000 --exit",
"test:node:loop": "npm run test:node && npm run test:node:loop",
"test:browser": "npm run build && karma start ./config/karma.conf.js --single-run",
"test:e2e": "concurrently \"npm run docs:serve\" \"sleep 20 && testcafe -b && testcafe -c 1 all test/e2e.test.js\" --kill-others --success first",
"test:e2e": "concurrently \"npm run docs:serve\" \"sleep 20 && testcafe -b && testcafe all test/e2e.test.js\" --kill-others --success first",
"test:typings": "npm run build && mocha ./test/typings.test.js -b --timeout 12000 --exit",

@@ -66,3 +67,3 @@ "test:performance": "npm run build && mocha ./test/performance.test.js -b --timeout 24000 --exit",

"dependencies": {
"@babel/runtime": "^7.6.2",
"@babel/runtime": "^7.7.2",
"detect-node": "^2.0.4",

@@ -72,8 +73,8 @@ "js-sha3": "0.8.0",

"nano-time": "1.0.0",
"rimraf": "2.6.3",
"rimraf": "3.0.0",
"unload": "2.2.0"
},
"devDependencies": {
"@babel/cli": "7.6.2",
"@babel/core": "7.6.2",
"@babel/cli": "7.7.0",
"@babel/core": "7.7.2",
"@babel/plugin-check-constants": "7.0.0-beta.38",

@@ -84,5 +85,5 @@ "@babel/plugin-proposal-object-rest-spread": "7.6.2",

"@babel/plugin-transform-runtime": "7.6.2",
"@babel/polyfill": "7.6.0",
"@babel/preset-env": "7.6.2",
"@babel/types": "7.6.1",
"@babel/polyfill": "7.7.0",
"@babel/preset-env": "7.7.1",
"@babel/types": "7.7.2",
"@types/core-js": "2.5.2",

@@ -94,7 +95,7 @@ "assert": "2.0.0",

"clone": "2.1.2",
"concurrently": "4.1.1",
"concurrently": "5.0.0",
"convert-hrtime": "3.0.0",
"copyfiles": "2.1.1",
"cross-env": "5.2.0",
"eslint": "5.16.0",
"cross-env": "6.0.3",
"eslint": "6.6.0",
"gzip-size-cli": "3.0.0",

@@ -114,18 +115,17 @@ "http-server": "0.11.1",

"karma-safari-launcher": "1.0.0",
"mocha": "6.2.0",
"node": "11.13.0",
"mocha": "6.2.2",
"node": "13.1.0",
"pre-commit": "1.2.2",
"random-int": "2.0.0",
"random-int": "2.0.1",
"random-token": "0.0.8",
"rollup": "1.21.4",
"rollup": "1.27.0",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-uglify": "^6.0.2",
"rollup-plugin-uglify": "6.0.3",
"testcafe": "1.6.1",
"testcafe-hammerhead": "14.11.0",
"ts-node": "7.0.1",
"typescript": "3.6.3",
"uglifyjs-webpack-plugin": "2.2.0",
"ts-node": "8.5.0",
"typescript": "3.7.2",
"watchify": "3.11.1",
"webpack": "4.41.0",
"webpack-cli": "3.3.6"
"webpack": "4.41.2",
"webpack-cli": "3.3.10"
},

@@ -132,0 +132,0 @@ "browser": {

@@ -41,3 +41,3 @@

```js
const BroadcastChannel = require('broadcast-channel');
const { BroadcastChannel } = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');

@@ -50,3 +50,3 @@ channel.postMessage('I am not alone');

```js
const BroadcastChannel = require('broadcast-channel');
const { BroadcastChannel } = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');

@@ -61,3 +61,3 @@ channel.onmessage = msg => console.dir(msg);

```js
const BroadcastChannel = require('broadcast-channel');
const { BroadcastChannel } = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');

@@ -91,3 +91,3 @@

```typescript
import BroadcastChannel from 'broadcast-channel';
import { BroadcastChannel } from 'broadcast-channel';
declare type Message = {

@@ -107,6 +107,6 @@ foo: string;

```typescript
import BroadcastChannel from 'broadcast-channel';
import { enforceOptions } from 'broadcast-channel';
// enforce this config for all channels
BroadcastChannel.enforceOptions({
enforceOptions({
type: 'simulate'

@@ -116,3 +116,3 @@ });

// reset the enforcement
BroadcastChannel.enforceOptions(null);
enforceOptions(null);
```

@@ -126,5 +126,6 @@

```typescript
import { clearNodeFolder } from 'broadcast-channel';
// jest
beforeAll(async () => {
const hasRun = await BroadcastChannel.clearNodeFolder();
const hasRun = await clearNodeFolder();
console.log(hasRun); // > true on NodeJs, false on Browsers

@@ -135,5 +136,6 @@ })

```typescript
import { clearNodeFolder } from 'broadcast-channel';
// mocha
before(async () => {
const hasRun = await BroadcastChannel.clearNodeFolder();
const hasRun = await clearNodeFolder();
console.log(hasRun); // > true on NodeJs, false on Browsers

@@ -170,6 +172,8 @@ })

```js
const BroadcastChannel = require('broadcast-channel');
const LeaderElection = require('broadcast-channel/leader-election');
const {
BroadcastChannel,
createLeaderElection
} = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');
const elector = LeaderElection.create(channel);
const elector = createLeaderElection(channel);
```

@@ -180,4 +184,4 @@

```js
const LeaderElection = require('broadcast-channel/leader-election');
const elector = LeaderElection.create(channel);
const { createLeaderElection } = require('broadcast-channel');
const elector = createLeaderElection(channel);
elector.awaitLeadership().then(()=> {

@@ -191,4 +195,4 @@ console.log('this tab is now leader');

```js
const LeaderElection = require('broadcast-channel/leader-election');
const elector = LeaderElection.create(channel, {
const { createLeaderElection } = require('broadcast-channel');
const elector = createLeaderElection(channel, {
fallbackInterval: 2000, // optional configuration for how often will renegotiation for leader occur

@@ -205,3 +209,3 @@ responseTime: 1000, // optional configuration for how long will instances have to respond

```js
const elector = LeaderElection.create(channel);
const elector = createLeaderElection(channel);
await elector.die();

@@ -208,0 +212,0 @@ ```

@@ -1,5 +0,6 @@

const BroadcastChannel = require('./index.es5.js');
const LeaderElection = require('./leader-election/index.es5.js');
const module = require('./index.es5.js');
const BroadcastChannel = module.BroadcastChannel;
const createLeaderElection = module.createLeaderElection;
window['BroadcastChannel2'] = BroadcastChannel;
window['LeaderElection'] = LeaderElection;
window['createLeaderElection'] = createLeaderElection;

@@ -10,4 +10,14 @@ /**

import BroadcastChannel from './index.js';
import {
BroadcastChannel,
createLeaderElection,
clearNodeFolder,
enforceOptions
} from './index.js';
module.exports = BroadcastChannel;
module.exports = {
BroadcastChannel,
createLeaderElection,
clearNodeFolder,
enforceOptions
};

@@ -1,249 +0,8 @@

import {
isPromise
} from './util.js';
import {
chooseMethod
} from './method-chooser.js';
import {
fillOptionsWithDefaults
} from './options.js';
const BroadcastChannel = function (name, options) {
this.name = name;
if (ENFORCED_OPTIONS) {
options = ENFORCED_OPTIONS;
}
this.options = fillOptionsWithDefaults(options);
this.method = chooseMethod(this.options);
// isListening
this._iL = false;
/**
* _onMessageListener
* setting onmessage twice,
* will overwrite the first listener
*/
this._onML = null;
/**
* _addEventListeners
*/
this._addEL = {
message: [],
internal: []
};
/**
* _beforeClose
* array of promises that will be awaited
* before the channel is closed
*/
this._befC = [];
/**
* _preparePromise
*/
this._prepP = null;
_prepareChannel(this);
};
// STATICS
/**
* used to identify if someone overwrites
* window.BroadcastChannel with this
* See methods/native.js
*/
BroadcastChannel._pubkey = true;
/**
* clears the tmp-folder if is node
* @return {Promise<boolean>} true if has run, false if not node
*/
BroadcastChannel.clearNodeFolder = function (options) {
options = fillOptionsWithDefaults(options);
const method = chooseMethod(options);
if (method.type === 'node') {
return method.clearNodeFolder().then(() => true);
} else {
return Promise.resolve(false);
}
};
/**
* if set, this method is enforced,
* no mather what the options are
*/
let ENFORCED_OPTIONS;
BroadcastChannel.enforceOptions = function (options) {
ENFORCED_OPTIONS = options;
};
// PROTOTYPE
BroadcastChannel.prototype = {
postMessage(msg) {
if (this.closed) {
throw new Error(
'BroadcastChannel.postMessage(): ' +
'Cannot post message after channel has closed'
);
}
return _post(this, 'message', msg);
},
postInternal(msg) {
return _post(this, 'internal', msg);
},
set onmessage(fn) {
const time = this.method.microSeconds();
const listenObj = {
time,
fn
};
_removeListenerObject(this, 'message', this._onML);
if (fn && typeof fn === 'function') {
this._onML = listenObj;
_addListenerObject(this, 'message', listenObj);
} else {
this._onML = null;
}
},
addEventListener(type, fn) {
const time = this.method.microSeconds();
const listenObj = {
time,
fn
};
_addListenerObject(this, type, listenObj);
},
removeEventListener(type, fn) {
const obj = this._addEL[type].find(obj => obj.fn === fn);
_removeListenerObject(this, type, obj);
},
close() {
if (this.closed) return;
this.closed = true;
const awaitPrepare = this._prepP ? this._prepP : Promise.resolve();
this._onML = null;
this._addEL.message = [];
return awaitPrepare
.then(() => Promise.all(this._befC.map(fn => fn())))
.then(() => {
return this.method.close(
this._state
);
});
},
get type() {
return this.method.type;
}
};
function _post(broadcastChannel, type, msg) {
const time = broadcastChannel.method.microSeconds();
const msgObj = {
time,
type,
data: msg
};
const awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();
return awaitPrepare.then(() => {
return broadcastChannel.method.postMessage(
broadcastChannel._state,
msgObj
);
});
}
function _prepareChannel(channel) {
const maybePromise = channel.method.create(channel.name, channel.options);
if (isPromise(maybePromise)) {
channel._prepP = maybePromise;
maybePromise.then(s => {
// used in tests to simulate slow runtime
/*if (channel.options.prepareDelay) {
await new Promise(res => setTimeout(res, this.options.prepareDelay));
}*/
channel._state = s;
});
} else {
channel._state = maybePromise;
}
}
function _hasMessageListeners(channel) {
if (channel._addEL.message.length > 0) return true;
if (channel._addEL.internal.length > 0) return true;
return false;
}
function _addListenerObject(channel, type, obj) {
channel._addEL[type].push(obj);
_startListening(channel);
}
function _removeListenerObject(channel, type, obj) {
channel._addEL[type] = channel._addEL[type].filter(o => o !== obj);
_stopListening(channel);
}
function _startListening(channel) {
if (!channel._iL && _hasMessageListeners(channel)) {
// someone is listening, start subscribing
const listenerFn = msgObj => {
channel._addEL[msgObj.type].forEach(obj => {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
};
const time = channel.method.microSeconds();
if (channel._prepP) {
channel._prepP.then(() => {
channel._iL = true;
channel.method.onMessage(
channel._state,
listenerFn,
time
);
});
} else {
channel._iL = true;
channel.method.onMessage(
channel._state,
listenerFn,
time
);
}
}
}
function _stopListening(channel) {
if (channel._iL && !_hasMessageListeners(channel)) {
// noone is listening, stop subscribing
channel._iL = false;
const time = channel.method.microSeconds();
channel.method.onMessage(
channel._state,
null,
time
);
}
}
export default BroadcastChannel;
export {
BroadcastChannel,
clearNodeFolder,
enforceOptions
} from './broadcast-channel';
export {
createLeaderElection
} from './leader-election';

@@ -169,3 +169,3 @@ /**

options,
uuid: randomToken(10),
uuid: randomToken(),
/**

@@ -172,0 +172,0 @@ * emittedMessagesIds

@@ -59,3 +59,3 @@ /**

const writeObj = {
token: randomToken(10),
token: randomToken(),
time: new Date().getTime(),

@@ -104,3 +104,3 @@ data: messageJson,

const uuid = randomToken(10);
const uuid = randomToken();

@@ -107,0 +107,0 @@ /**

@@ -207,4 +207,4 @@ /**

.createServer(stream => {
stream.on('end', function() {});
stream.on('data', function(msg) {
stream.on('end', function () { });
stream.on('data', function (msg) {
emitter.emit('data', msg.toString());

@@ -262,3 +262,3 @@ });

const token = randomToken(12);
const token = randomToken();
const fileName = time + '_' + readerUuid + '_' + token + '.json';

@@ -353,4 +353,4 @@

messageObjects
.filter(obj => (obj.time / 1000) < olderThen)
.map(obj => unlink(obj.path).catch(() => null))
.filter(obj => (obj.time / 1000) < olderThen)
.map(obj => unlink(obj.path).catch(() => null))
);

@@ -372,3 +372,3 @@ }

const ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
const uuid = randomToken(10);
const uuid = randomToken();

@@ -473,5 +473,5 @@ const state = {

useMessages
.map(
msgObj => readMessage(msgObj).then(content => msgObj.content = content)
)
.map(
msgObj => readMessage(msgObj).then(content => msgObj.content = content)
)
);

@@ -502,3 +502,3 @@

await channelState.otherReaderClients[readerUuid].destroy();
} catch (err) {}
} catch (err) { }
delete channelState.otherReaderClients[readerUuid];

@@ -510,19 +510,19 @@ });

otherReaders
.filter(readerUuid => readerUuid !== channelState.uuid) // not own
.filter(readerUuid => !channelState.otherReaderClients[readerUuid]) // not already has client
.map(async (readerUuid) => {
try {
if (channelState.closed) return;
.filter(readerUuid => readerUuid !== channelState.uuid) // not own
.filter(readerUuid => !channelState.otherReaderClients[readerUuid]) // not already has client
.map(async (readerUuid) => {
try {
const client = await openClientConnection(channelState.channelName, readerUuid);
channelState.otherReaderClients[readerUuid] = client;
if (channelState.closed) return;
try {
const client = await openClientConnection(channelState.channelName, readerUuid);
channelState.otherReaderClients[readerUuid] = client;
} catch (err) {
// this can throw when the cleanup of another channel was interrupted
// or the socket-file does not exits yet
}
} catch (err) {
// this can throw when the cleanup of another channel was interrupted
// or the socket-file does not exits yet
// this might throw if the other channel is closed at the same time when this one is running refresh
// so we do not throw an error
}
} catch (err) {
// this might throw if the other channel is closed at the same time when this one is running refresh
// so we do not throw an error
}
})
})
);

@@ -557,8 +557,8 @@ });

Object.values(channelState.otherReaderClients)
.filter(client => client.writable) // client might have closed in between
.map(client => {
return new Promise(res => {
client.write(pingStr, res);
});
})
.filter(client => client.writable) // client might have closed in between
.map(client => {
return new Promise(res => {
client.write(pingStr, res);
});
})
);

@@ -638,3 +638,3 @@

fs.unlinkSync(channelState.infoFilePath);
} catch (err) {}
} catch (err) { }
}

@@ -641,0 +641,0 @@ }

@@ -23,13 +23,6 @@ /**

/**
* https://stackoverflow.com/a/1349426/3443137
* https://stackoverflow.com/a/8084248
*/
export function randomToken(length) {
if (!length) length = 5;
let text = '';
const possible = 'abcdefghijklmnopqrstuvwxzy0123456789';
for (let i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
export function randomToken() {
return Math.random().toString(36).substring(2);
}

@@ -36,0 +29,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc