UNPKG

@toruslabs/broadcast-channel

Version:

A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers

1,393 lines (1,379 loc) 568 kB
"use strict"; var BroadcastChannel = (() => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod2) => function __require() { return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); // node_modules/loglevel/lib/loglevel.js var require_loglevel = __commonJS({ "node_modules/loglevel/lib/loglevel.js"(exports, module) { (function(root, definition) { "use strict"; if (typeof define === "function" && define.amd) { define(definition); } else if (typeof module === "object" && module.exports) { module.exports = definition(); } else { root.log = definition(); } })(exports, function() { "use strict"; var noop = function() { }; var undefinedType = "undefined"; var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent); var logMethods = [ "trace", "debug", "info", "warn", "error" ]; var _loggersByName = {}; var defaultLogger = null; function bindMethod(obj, methodName) { var method = obj[methodName]; if (typeof method.bind === "function") { return method.bind(obj); } else { try { return Function.prototype.bind.call(method, obj); } catch (e) { return function() { return Function.prototype.apply.apply(method, [obj, arguments]); }; } } } function traceForIE() { if (console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { Function.prototype.apply.apply(console.log, [console, arguments]); } } if (console.trace) console.trace(); } function realMethod(methodName) { if (methodName === "debug") { methodName = "log"; } if (typeof console === undefinedType) { return false; } else if (methodName === "trace" && isIE) { return traceForIE; } else if (console[methodName] !== void 0) { return bindMethod(console, methodName); } else if (console.log !== void 0) { return bindMethod(console, "log"); } else { return noop; } } function replaceLoggingMethods() { var level = this.getLevel(); for (var i = 0; i < logMethods.length; i++) { var methodName = logMethods[i]; this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name); } this.log = this.debug; if (typeof console === undefinedType && level < this.levels.SILENT) { return "No console available for logging"; } } function enableLoggingWhenConsoleArrives(methodName) { return function() { if (typeof console !== undefinedType) { replaceLoggingMethods.call(this); this[methodName].apply(this, arguments); } }; } function defaultMethodFactory(methodName, _level, _loggerName) { return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments); } function Logger(name, factory) { var self2 = this; var inheritedLevel; var defaultLevel; var userLevel; var storageKey = "loglevel"; if (typeof name === "string") { storageKey += ":" + name; } else if (typeof name === "symbol") { storageKey = void 0; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || "silent").toUpperCase(); if (typeof window === undefinedType || !storageKey) return; try { window.localStorage[storageKey] = levelName; return; } catch (ignore) { } try { window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";"; } catch (ignore) { } } function getPersistedLevel() { var storedLevel; if (typeof window === undefinedType || !storageKey) return; try { storedLevel = window.localStorage[storageKey]; } catch (ignore) { } if (typeof storedLevel === undefinedType) { try { var cookie = window.document.cookie; var cookieName = encodeURIComponent(storageKey); var location2 = cookie.indexOf(cookieName + "="); if (location2 !== -1) { storedLevel = /^([^;]+)/.exec( cookie.slice(location2 + cookieName.length + 1) )[1]; } } catch (ignore) { } } if (self2.levels[storedLevel] === void 0) { storedLevel = void 0; } return storedLevel; } function clearPersistedLevel() { if (typeof window === undefinedType || !storageKey) return; try { window.localStorage.removeItem(storageKey); } catch (ignore) { } try { window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; } catch (ignore) { } } function normalizeLevel(input) { var level = input; if (typeof level === "string" && self2.levels[level.toUpperCase()] !== void 0) { level = self2.levels[level.toUpperCase()]; } if (typeof level === "number" && level >= 0 && level <= self2.levels.SILENT) { return level; } else { throw new TypeError("log.setLevel() called with invalid level: " + input); } } self2.name = name; self2.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5 }; self2.methodFactory = factory || defaultMethodFactory; self2.getLevel = function() { if (userLevel != null) { return userLevel; } else if (defaultLevel != null) { return defaultLevel; } else { return inheritedLevel; } }; self2.setLevel = function(level, persist) { userLevel = normalizeLevel(level); if (persist !== false) { persistLevelIfPossible(userLevel); } return replaceLoggingMethods.call(self2); }; self2.setDefaultLevel = function(level) { defaultLevel = normalizeLevel(level); if (!getPersistedLevel()) { self2.setLevel(level, false); } }; self2.resetLevel = function() { userLevel = null; clearPersistedLevel(); replaceLoggingMethods.call(self2); }; self2.enableAll = function(persist) { self2.setLevel(self2.levels.TRACE, persist); }; self2.disableAll = function(persist) { self2.setLevel(self2.levels.SILENT, persist); }; self2.rebuild = function() { if (defaultLogger !== self2) { inheritedLevel = normalizeLevel(defaultLogger.getLevel()); } replaceLoggingMethods.call(self2); if (defaultLogger === self2) { for (var childName in _loggersByName) { _loggersByName[childName].rebuild(); } } }; inheritedLevel = normalizeLevel( defaultLogger ? defaultLogger.getLevel() : "WARN" ); var initialLevel = getPersistedLevel(); if (initialLevel != null) { userLevel = normalizeLevel(initialLevel); } replaceLoggingMethods.call(self2); } defaultLogger = new Logger(); defaultLogger.getLogger = function getLogger(name) { if (typeof name !== "symbol" && typeof name !== "string" || name === "") { throw new TypeError("You must supply a name when creating a logger."); } var logger = _loggersByName[name]; if (!logger) { logger = _loggersByName[name] = new Logger( name, defaultLogger.methodFactory ); } return logger; }; var _log = typeof window !== undefinedType ? window.log : void 0; defaultLogger.noConflict = function() { if (typeof window !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; defaultLogger["default"] = defaultLogger; return defaultLogger; }); } }); // dist/lib.cjs/util.js var require_util = __commonJS({ "dist/lib.cjs/util.js"(exports) { "use strict"; var loglevel = require_loglevel(); function isPromise(obj) { if (obj && typeof obj.then === "function") { return true; } return false; } Promise.resolve(false); Promise.resolve(true); var PROMISE_RESOLVED_VOID = Promise.resolve(); function sleep(time, resolveWith) { if (!time) time = 0; return new Promise((resolve) => { setTimeout(() => resolve(resolveWith), time); }); } function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } function generateRandomId() { return Math.random().toString(36).substring(2); } var lastMs = 0; function microSeconds() { let ret = Date.now() * 1e3; if (ret <= lastMs) { ret = lastMs + 1; } lastMs = ret; return ret; } var log = loglevel.getLogger("broadcast-channel"); log.setLevel("error"); exports.PROMISE_RESOLVED_VOID = PROMISE_RESOLVED_VOID; exports.generateRandomId = generateRandomId; exports.isPromise = isPromise; exports.log = log; exports.microSeconds = microSeconds; exports.randomInt = randomInt; exports.sleep = sleep; } }); // node_modules/oblivious-set/dist/cjs/src/index.js var require_src = __commonJS({ "node_modules/oblivious-set/dist/cjs/src/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.now = exports.removeTooOldValues = exports.ObliviousSet = void 0; var ObliviousSet = class { ttl; map = /* @__PURE__ */ new Map(); /** * Creating calls to setTimeout() is expensive, * so we only do that if there is not timeout already open. */ _to = false; constructor(ttl) { this.ttl = ttl; } has(value) { const valueTime = this.map.get(value); if (typeof valueTime === "undefined") { return false; } if (valueTime < now() - this.ttl) { this.map.delete(value); return false; } return true; } add(value) { this.map.delete(value); this.map.set(value, now()); if (!this._to) { this._to = true; setTimeout(() => { this._to = false; removeTooOldValues(this); }, 0); } } clear() { this.map.clear(); } }; exports.ObliviousSet = ObliviousSet; function removeTooOldValues(obliviousSet) { const olderThen = now() - obliviousSet.ttl; const iterator = obliviousSet.map[Symbol.iterator](); while (true) { const next = iterator.next().value; if (!next) { break; } const value = next[0]; const time = next[1]; if (time < olderThen) { obliviousSet.map.delete(value); } else { break; } } } exports.removeTooOldValues = removeTooOldValues; function now() { return Date.now(); } exports.now = now; } }); // node_modules/oblivious-set/dist/cjs/src/index.es5.js var require_index_es5 = __commonJS({ "node_modules/oblivious-set/dist/cjs/src/index.es5.js"(exports, module) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod2) { if (mod2 && mod2.__esModule) return mod2; var result = {}; if (mod2 != null) { for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k); } __setModuleDefault(result, mod2); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var pkg = __importStar(require_src()); module.exports = pkg; } }); // node_modules/@toruslabs/constants/dist/lib.cjs/constants.js var require_constants = __commonJS({ "node_modules/@toruslabs/constants/dist/lib.cjs/constants.js"(exports) { "use strict"; var TORUS_LEGACY_NETWORK = { MAINNET: "mainnet", TESTNET: "testnet", CYAN: "cyan", AQUA: "aqua", CELESTE: "celeste" }; var TORUS_SAPPHIRE_NETWORK = { SAPPHIRE_DEVNET: "sapphire_devnet", SAPPHIRE_MAINNET: "sapphire_mainnet" }; var BUILD_ENV = { PRODUCTION: "production", DEVELOPMENT: "development", STAGING: "staging", TESTING: "testing" }; var LEGACY_NETWORKS_ROUTE_MAP = { [TORUS_LEGACY_NETWORK.AQUA]: { networkIdentifier: "aqua", networkMigratedTo: TORUS_SAPPHIRE_NETWORK.SAPPHIRE_MAINNET }, [TORUS_LEGACY_NETWORK.CELESTE]: { networkIdentifier: "celeste", networkMigratedTo: TORUS_SAPPHIRE_NETWORK.SAPPHIRE_MAINNET }, [TORUS_LEGACY_NETWORK.CYAN]: { networkIdentifier: "cyan", networkMigratedTo: TORUS_SAPPHIRE_NETWORK.SAPPHIRE_MAINNET }, [TORUS_LEGACY_NETWORK.MAINNET]: { networkIdentifier: "mainnet", networkMigratedTo: TORUS_SAPPHIRE_NETWORK.SAPPHIRE_MAINNET }, [TORUS_LEGACY_NETWORK.TESTNET]: { networkIdentifier: "teal", networkMigratedTo: TORUS_SAPPHIRE_NETWORK.SAPPHIRE_DEVNET } }; var CITADEL_SERVER_MAP = { [BUILD_ENV.PRODUCTION]: "https://api.web3auth.io/citadel-service", [BUILD_ENV.DEVELOPMENT]: "https://api-develop.web3auth.io/citadel-service", [BUILD_ENV.STAGING]: "https://api.web3auth.io/citadel-service", [BUILD_ENV.TESTING]: "https://api-develop.web3auth.io/citadel-service" }; var LEGACY_METADATA_MAP = { [BUILD_ENV.PRODUCTION]: "https://api.web3auth.io/metadata-service", [BUILD_ENV.DEVELOPMENT]: "https://api-develop.web3auth.io/metadata-service", [BUILD_ENV.STAGING]: "https://api.web3auth.io/metadata-service", [BUILD_ENV.TESTING]: "https://api-develop.web3auth.io/metadata-service" }; var FND_SERVER_MAP = { [BUILD_ENV.PRODUCTION]: "https://api.web3auth.io/fnd-service", [BUILD_ENV.DEVELOPMENT]: "https://api-develop.web3auth.io/fnd-service", [BUILD_ENV.STAGING]: "https://api.web3auth.io/fnd-service", [BUILD_ENV.TESTING]: "https://api-develop.web3auth.io/fnd-service" }; var STORAGE_SERVER_MAP = { [BUILD_ENV.PRODUCTION]: "https://api.web3auth.io/session-service", [BUILD_ENV.DEVELOPMENT]: "https://api-develop.web3auth.io/session-service", [BUILD_ENV.STAGING]: "https://api.web3auth.io/session-service", [BUILD_ENV.TESTING]: "https://api-develop.web3auth.io/session-service" }; var STORAGE_SERVER_SOCKET_URL_MAP = { [BUILD_ENV.PRODUCTION]: "https://session.web3auth.io", [BUILD_ENV.DEVELOPMENT]: "https://develop-session.web3auth.io", [BUILD_ENV.STAGING]: "https://session.web3auth.io", [BUILD_ENV.TESTING]: "https://develop-session.web3auth.io" }; var KEY_TYPE = { SECP256K1: "secp256k1", ED25519: "ed25519" }; var SIG_TYPE = { ECDSA_SECP256K1: "ecdsa-secp256k1", ED25519: "ed25519", BIP340: "bip340" }; exports.BUILD_ENV = BUILD_ENV; exports.CITADEL_SERVER_MAP = CITADEL_SERVER_MAP; exports.FND_SERVER_MAP = FND_SERVER_MAP; exports.KEY_TYPE = KEY_TYPE; exports.LEGACY_METADATA_MAP = LEGACY_METADATA_MAP; exports.LEGACY_NETWORKS_ROUTE_MAP = LEGACY_NETWORKS_ROUTE_MAP; exports.SIG_TYPE = SIG_TYPE; exports.STORAGE_SERVER_MAP = STORAGE_SERVER_MAP; exports.STORAGE_SERVER_SOCKET_URL_MAP = STORAGE_SERVER_SOCKET_URL_MAP; exports.TORUS_LEGACY_NETWORK = TORUS_LEGACY_NETWORK; exports.TORUS_SAPPHIRE_NETWORK = TORUS_SAPPHIRE_NETWORK; } }); // node_modules/@toruslabs/constants/dist/lib.cjs/interfaces.js var require_interfaces = __commonJS({ "node_modules/@toruslabs/constants/dist/lib.cjs/interfaces.js"(exports) { "use strict"; var abi = [{ inputs: [{ internalType: "string", name: "_verifier", type: "string" }, { internalType: "bytes32", name: "hashedVerifierId", type: "bytes32" }], name: "getNodeSet", outputs: [{ internalType: "uint256", name: "currentEpoch", type: "uint256" }, { internalType: "string[]", name: "torusNodeEndpoints", type: "string[]" }, { internalType: "uint256[]", name: "torusNodePubX", type: "uint256[]" }, { internalType: "uint256[]", name: "torusNodePubY", type: "uint256[]" }, { internalType: "uint256[]", name: "torusIndexes", type: "uint256[]" }], stateMutability: "view", type: "function" }]; exports.abi = abi; } }); // node_modules/@toruslabs/constants/dist/lib.cjs/index.js var require_lib = __commonJS({ "node_modules/@toruslabs/constants/dist/lib.cjs/index.js"(exports) { "use strict"; var constants = require_constants(); var interfaces = require_interfaces(); exports.BUILD_ENV = constants.BUILD_ENV; exports.CITADEL_SERVER_MAP = constants.CITADEL_SERVER_MAP; exports.FND_SERVER_MAP = constants.FND_SERVER_MAP; exports.KEY_TYPE = constants.KEY_TYPE; exports.LEGACY_METADATA_MAP = constants.LEGACY_METADATA_MAP; exports.LEGACY_NETWORKS_ROUTE_MAP = constants.LEGACY_NETWORKS_ROUTE_MAP; exports.SIG_TYPE = constants.SIG_TYPE; exports.STORAGE_SERVER_MAP = constants.STORAGE_SERVER_MAP; exports.STORAGE_SERVER_SOCKET_URL_MAP = constants.STORAGE_SERVER_SOCKET_URL_MAP; exports.TORUS_LEGACY_NETWORK = constants.TORUS_LEGACY_NETWORK; exports.TORUS_SAPPHIRE_NETWORK = constants.TORUS_SAPPHIRE_NETWORK; exports.abi = interfaces.abi; } }); // dist/lib.cjs/options.js var require_options = __commonJS({ "dist/lib.cjs/options.js"(exports) { "use strict"; var constants = require_lib(); function fillOptionsWithDefaults(originalOptions = {}) { const options = JSON.parse(JSON.stringify(originalOptions)); if (typeof options.webWorkerSupport === "undefined") options.webWorkerSupport = true; if (!options.idb) options.idb = {}; if (!options.idb.ttl) options.idb.ttl = 1e3 * 45; if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; if (originalOptions.idb && typeof originalOptions.idb.onclose === "function") options.idb.onclose = originalOptions.idb.onclose; if (!options.localstorage) options.localstorage = {}; if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1e3 * 60; if (!options.server) options.server = {}; if (!options.server.build_env) options.server.build_env = constants.BUILD_ENV.PRODUCTION; if (!options.server.api_url) options.server.api_url = `${constants.STORAGE_SERVER_MAP[options.server.build_env]}/v2`; if (!options.server.socket_url) options.server.socket_url = `${constants.STORAGE_SERVER_SOCKET_URL_MAP[options.server.build_env]}`; if (!options.server.removeTimeout) options.server.removeTimeout = 1e3 * 60 * 5; if (originalOptions.methods) options.methods = originalOptions.methods; return options; } exports.fillOptionsWithDefaults = fillOptionsWithDefaults; } }); // dist/lib.cjs/methods/indexed-db.js var require_indexed_db = __commonJS({ "dist/lib.cjs/methods/indexed-db.js"(exports) { "use strict"; var util = require_util(); var obliviousSet = require_index_es5(); var options = require_options(); var microSeconds = util.microSeconds; var DB_PREFIX = "pubkey.broadcast-channel-0-"; var OBJECT_STORE_ID = "messages"; var TRANSACTION_SETTINGS = { durability: "relaxed" }; var type = "idb"; function getIdb() { if (typeof indexedDB !== "undefined") return indexedDB; if (typeof window !== "undefined") { const extWindow = window; if (typeof extWindow.mozIndexedDB !== "undefined") return extWindow.mozIndexedDB; if (typeof extWindow.webkitIndexedDB !== "undefined") return extWindow.webkitIndexedDB; if (typeof extWindow.msIndexedDB !== "undefined") return extWindow.msIndexedDB; } return false; } function commitIndexedDBTransaction(tx) { if (tx.commit) { tx.commit(); } } function createDatabase(channelName) { const IndexedDB = getIdb(); if (!IndexedDB) return Promise.reject(new Error("IndexedDB not available")); const dbName = DB_PREFIX + channelName; const openRequest = IndexedDB.open(dbName); openRequest.onupgradeneeded = (ev) => { const db = ev.target.result; db.createObjectStore(OBJECT_STORE_ID, { keyPath: "id", autoIncrement: true }); }; const dbPromise = new Promise((resolve, reject) => { openRequest.onerror = (ev) => reject(ev); openRequest.onsuccess = () => { resolve(openRequest.result); }; }); return dbPromise; } function writeMessage(db, readerUuid, messageJson) { const time = Date.now(); const writeObject = { uuid: readerUuid, time, data: messageJson }; const tx = db.transaction([OBJECT_STORE_ID], "readwrite", TRANSACTION_SETTINGS); return new Promise((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = (ev) => reject(ev); const objectStore = tx.objectStore(OBJECT_STORE_ID); objectStore.add(writeObject); commitIndexedDBTransaction(tx); }); } function getAllMessages(db) { const tx = db.transaction(OBJECT_STORE_ID, "readonly", TRANSACTION_SETTINGS); const objectStore = tx.objectStore(OBJECT_STORE_ID); const ret = []; return new Promise((resolve) => { objectStore.openCursor().onsuccess = (ev) => { const cursor = ev.target.result; if (cursor) { ret.push(cursor.value); cursor.continue(); } else { commitIndexedDBTransaction(tx); resolve(ret); } }; }); } function getMessagesHigherThan(db, lastCursorId) { const tx = db.transaction(OBJECT_STORE_ID, "readonly", TRANSACTION_SETTINGS); const objectStore = tx.objectStore(OBJECT_STORE_ID); const ret = []; let keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); if (objectStore.getAll) { const getAllRequest = objectStore.getAll(keyRangeValue); return new Promise((resolve, reject) => { getAllRequest.onerror = (err) => reject(err); getAllRequest.onsuccess = function(e) { resolve(e.target.result); }; }); } function openCursor() { try { keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); return objectStore.openCursor(keyRangeValue); } catch { return objectStore.openCursor(); } } return new Promise((resolve, reject) => { const openCursorRequest = openCursor(); openCursorRequest.onerror = (err) => reject(err); openCursorRequest.onsuccess = (ev) => { const cursor = ev.target.result; if (cursor) { if (cursor.value.id < lastCursorId + 1) { cursor.continue(lastCursorId + 1); } else { ret.push(cursor.value); cursor.continue(); } } else { commitIndexedDBTransaction(tx); resolve(ret); } }; }); } function removeMessagesById(db, ids) { const tx = db.transaction([OBJECT_STORE_ID], "readwrite", TRANSACTION_SETTINGS); const objectStore = tx.objectStore(OBJECT_STORE_ID); return Promise.all(ids.map((id) => { const deleteRequest = objectStore.delete(id); return new Promise((resolve) => { deleteRequest.onsuccess = () => resolve(); }); })); } function getOldMessages(db, ttl) { const olderThen = Date.now() - ttl; const tx = db.transaction(OBJECT_STORE_ID, "readonly", TRANSACTION_SETTINGS); const objectStore = tx.objectStore(OBJECT_STORE_ID); const ret = []; return new Promise((resolve) => { objectStore.openCursor().onsuccess = (ev) => { const cursor = ev.target.result; if (cursor) { const msgObk = cursor.value; if (msgObk.time < olderThen) { ret.push(msgObk); cursor.continue(); } else { commitIndexedDBTransaction(tx); resolve(ret); } } else { resolve(ret); } }; }); } function cleanOldMessages(db, ttl) { return getOldMessages(db, ttl).then((tooOld) => { return removeMessagesById(db, tooOld.map((msg) => msg.id)); }); } function create(channelName, options$1) { options$1 = options.fillOptionsWithDefaults(options$1); return createDatabase(channelName).then((db) => { const state = { closed: false, lastCursorId: 0, channelName, options: options$1, uuid: util.generateRandomId(), /** * emittedMessagesIds * contains all messages that have been emitted before * @type {ObliviousSet} */ eMIs: new obliviousSet.ObliviousSet(options$1.idb.ttl * 2), // ensures we do not read messages in parrallel writeBlockPromise: util.PROMISE_RESOLVED_VOID, messagesCallback: null, readQueuePromises: [], db, time: util.microSeconds() }; db.onclose = function() { state.closed = true; if (options$1.idb.onclose) options$1.idb.onclose(); }; _readLoop(state); return state; }); } function _readLoop(state) { if (state.closed) return; readNewMessages(state).then(() => util.sleep(state.options.idb.fallbackInterval)).then(() => _readLoop(state)).catch((e) => { throw e; }); } function _filterMessage(msgObj, state) { if (msgObj.uuid === state.uuid) return false; if (state.eMIs.has(msgObj.id)) return false; if (msgObj.data.time < state.messagesCallbackTime) return false; return true; } function readNewMessages(state) { if (state.closed) return util.PROMISE_RESOLVED_VOID; if (!state.messagesCallback) return util.PROMISE_RESOLVED_VOID; return getMessagesHigherThan(state.db, state.lastCursorId).then((newerMessages) => { const useMessages = newerMessages.filter((msgObj) => !!msgObj).map((msgObj) => { if (msgObj.id > state.lastCursorId) { state.lastCursorId = msgObj.id; } return msgObj; }).filter((msgObj) => _filterMessage(msgObj, state)).sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); useMessages.forEach((msgObj) => { if (state.messagesCallback) { state.eMIs.add(msgObj.id); state.messagesCallback(msgObj.data); } }); return util.PROMISE_RESOLVED_VOID; }); } function close(channelState) { channelState.closed = true; channelState.db.close(); } function postMessage(channelState, messageJson) { channelState.writeBlockPromise = channelState.writeBlockPromise.then(() => writeMessage(channelState.db, channelState.uuid, messageJson)).then(() => { if (util.randomInt(0, 10) === 0) { cleanOldMessages(channelState.db, channelState.options.idb.ttl); } return util.PROMISE_RESOLVED_VOID; }); return channelState.writeBlockPromise; } function onMessage(channelState, fn, time) { channelState.messagesCallbackTime = time; channelState.messagesCallback = fn; readNewMessages(channelState); } function canBeUsed() { const idb = getIdb(); if (!idb) return false; return true; } function averageResponseTime(options2) { return options2.idb.fallbackInterval * 2; } exports.TRANSACTION_SETTINGS = TRANSACTION_SETTINGS; exports.averageResponseTime = averageResponseTime; exports.canBeUsed = canBeUsed; exports.cleanOldMessages = cleanOldMessages; exports.close = close; exports.commitIndexedDBTransaction = commitIndexedDBTransaction; exports.create = create; exports.createDatabase = createDatabase; exports.getAllMessages = getAllMessages; exports.getIdb = getIdb; exports.getMessagesHigherThan = getMessagesHigherThan; exports.getOldMessages = getOldMessages; exports.microSeconds = microSeconds; exports.onMessage = onMessage; exports.postMessage = postMessage; exports.removeMessagesById = removeMessagesById; exports.type = type; exports.writeMessage = writeMessage; } }); // dist/lib.cjs/methods/localstorage.js var require_localstorage = __commonJS({ "dist/lib.cjs/methods/localstorage.js"(exports) { "use strict"; var obliviousSet = require_index_es5(); var options = require_options(); var util = require_util(); var microSeconds = util.microSeconds; var KEY_PREFIX = "pubkey.broadcastChannel-"; var type = "localstorage"; function getLocalStorage() { let localStorage2 = null; if (typeof window === "undefined") return null; try { localStorage2 = window.localStorage; localStorage2 = window["ie8-eventlistener/storage"] || window.localStorage; } catch { } return localStorage2; } function storageKey(channelName) { return KEY_PREFIX + channelName; } function postMessage(channelState, messageJson) { return new Promise((resolve, reject) => { util.sleep().then(() => { var _getLocalStorage; const key = storageKey(channelState.channelName); const writeObj = { token: util.generateRandomId(), time: Date.now(), data: messageJson, uuid: channelState.uuid }; const value = JSON.stringify(writeObj); (_getLocalStorage = getLocalStorage()) === null || _getLocalStorage === void 0 || _getLocalStorage.setItem(key, value); const ev = document.createEvent("StorageEvent"); ev.initStorageEvent("storage", true, true, key, null, value, "", null); window.dispatchEvent(ev); resolve(); }).catch(reject); }); } function addStorageEventListener(channelName, fn) { const key = storageKey(channelName); const listener = (ev) => { if (ev.key === key && ev.newValue) { fn(JSON.parse(ev.newValue)); } }; window.addEventListener("storage", listener); return listener; } function removeStorageEventListener(listener) { window.removeEventListener("storage", listener); } function canBeUsed() { const ls = getLocalStorage(); if (!ls) return false; try { const key = "__broadcastchannel_check"; ls.setItem(key, "works"); ls.removeItem(key); } catch { return false; } return true; } function create(channelName, options$1) { const filledOptions = options.fillOptionsWithDefaults(options$1); if (!canBeUsed()) { throw new Error("BroadcastChannel: localstorage cannot be used"); } const uuid = util.generateRandomId(); const eMIs = new obliviousSet.ObliviousSet(filledOptions.localstorage.removeTimeout); const state = { channelName, uuid, time: util.microSeconds(), eMIs // emittedMessagesIds }; state.listener = addStorageEventListener(channelName, (msgObj) => { if (!state.messagesCallback) return; if (msgObj.uuid === uuid) return; if (!msgObj.token || eMIs.has(msgObj.token)) return; if (msgObj.data.time && msgObj.data.time < (state.messagesCallbackTime || 0)) return; eMIs.add(msgObj.token); state.messagesCallback(msgObj.data); }); return state; } function close(channelState) { if (channelState.listener) { removeStorageEventListener(channelState.listener); } } function onMessage(channelState, fn, time) { channelState.messagesCallbackTime = time; channelState.messagesCallback = fn; } function averageResponseTime() { const defaultTime = 120; const userAgent = navigator.userAgent.toLowerCase(); if (userAgent.includes("safari") && !userAgent.includes("chrome")) { return defaultTime * 2; } return defaultTime; } exports.addStorageEventListener = addStorageEventListener; exports.averageResponseTime = averageResponseTime; exports.canBeUsed = canBeUsed; exports.close = close; exports.create = create; exports.getLocalStorage = getLocalStorage; exports.microSeconds = microSeconds; exports.onMessage = onMessage; exports.postMessage = postMessage; exports.removeStorageEventListener = removeStorageEventListener; exports.storageKey = storageKey; exports.type = type; } }); // dist/lib.cjs/methods/native.js var require_native = __commonJS({ "dist/lib.cjs/methods/native.js"(exports) { "use strict"; var util = require_util(); var microSeconds = util.microSeconds; var type = "native"; function create(channelName) { const state = { time: util.microSeconds(), messagesCallback: null, bc: new BroadcastChannel(channelName), subFns: [] // subscriberFunctions }; state.bc.onmessage = (msg) => { if (state.messagesCallback) { state.messagesCallback(msg.data); } }; return state; } function close(channelState) { channelState.bc.close(); channelState.subFns = []; } function postMessage(channelState, messageJson) { try { channelState.bc.postMessage(messageJson); return util.PROMISE_RESOLVED_VOID; } catch (err) { return Promise.reject(err); } } function onMessage(channelState, fn) { channelState.messagesCallback = fn; } function canBeUsed() { if (typeof window === "undefined") return false; if (typeof BroadcastChannel === "function") { if (BroadcastChannel._pubkey) { throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill"); } return true; } return false; } function averageResponseTime() { return 150; } exports.averageResponseTime = averageResponseTime; exports.canBeUsed = canBeUsed; exports.close = close; exports.create = create; exports.microSeconds = microSeconds; exports.onMessage = onMessage; exports.postMessage = postMessage; exports.type = type; } }); // node_modules/@noble/hashes/utils.js function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber(n, title = "") { if (!Number.isSafeInteger(n) || n < 0) { const prefix = title && `"${title}" `; throw new Error(`${prefix}expected integer >= 0, got ${n}`); } } function abytes(value, length, title = "") { const bytes2 = isBytes(value); const len = value?.length; const needsLen = length !== void 0; if (!bytes2 || needsLen && len !== length) { const prefix = title && `"${title}" `; const ofLen = needsLen ? ` of length ${length}` : ""; const got = bytes2 ? `length=${len}` : `type=${typeof value}`; throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got); } return value; } function ahash(h) { if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash must wrapped by utils.createHasher"); anumber(h.outputLen); anumber(h.blockLen); } function aexists(instance, checkFinished = true) { if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } function aoutput(out, instance) { abytes(out, void 0, "digestInto() output"); const min = instance.outputLen; if (out.length < min) { throw new Error('"digestInto() output" expected to be of length >=' + min); } } function u32(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } function clean(...arrays) { for (let i = 0; i < arrays.length; i++) { arrays[i].fill(0); } } function createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr(word, shift) { return word << 32 - shift | word >>> shift; } function byteSwap(word) { return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } function byteSwap32(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap(arr[i]); } return arr; } function bytesToHex(bytes2) { abytes(bytes2); if (hasHexBuiltin) return bytes2.toHex(); let hex2 = ""; for (let i = 0; i < bytes2.length; i++) { hex2 += hexes[bytes2[i]]; } return hex2; } function asciiToBase16(ch) { if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); return; } function hexToBytes(hex2) { if (typeof hex2 !== "string") throw new Error("hex string expected, got " + typeof hex2); if (hasHexBuiltin) return Uint8Array.fromHex(hex2); const hl = hex2.length; const al = hl / 2; if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = asciiToBase16(hex2.charCodeAt(hi)); const n2 = asciiToBase16(hex2.charCodeAt(hi + 1)); if (n1 === void 0 || n2 === void 0) { const char = hex2[hi] + hex2[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } function createHasher(hashCons, info = {}) { const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); const tmp = hashCons(void 0); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); Object.assign(hashC, info); return Object.freeze(hashC); } function randomBytes(bytesLength = 32) { const cr = typeof globalThis === "object" ? globalThis.crypto : null; if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined"); return cr.getRandomValues(new Uint8Array(bytesLength)); } var isLE, swap32IfBE, hasHexBuiltin, hexes, asciis, oidNist; var init_utils = __esm({ "node_modules/@noble/hashes/utils.js"() { isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); swap32IfBE = isLE ? (u) => u : byteSwap32; hasHexBuiltin = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; oidNist = (suffix) => ({ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) }); } }); // node_modules/@noble/hashes/_md.js function Chi(a, b, c) { return a & b ^ ~a & c; } function Maj(a, b, c) { return a & b ^ a & c ^ b & c; } var HashMD, SHA256_IV, SHA224_IV, SHA384_IV, SHA512_IV; var init_md = __esm({ "node_modules/@noble/hashes/_md.js"() { init_utils(); HashMD = class { blockLen; outputLen; padOffset; isLE; // For partial updates less than block size buffer; view; finished = false; length = 0; pos = 0; destroyed = false; constructor(blockLen, outputLen, padOffset, isLE2) { this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE2; this.buffer = new Uint8Array(blockLen); this.view = createView(this.buffer); } update(data) { aexists(this); abytes(data); const { view, buffer, blockLen } = this; const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView = createView(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; } } this.length += data.length; this.roundClean(); return this; } digestInto(out) { aexists(this); aoutput(out, this); this.finished = true; const { buffer, view, blockLen, isLE: isLE2 } = this; let { pos } = this; buffer[pos++] = 128; clean(this.buffer.subarray(pos)); if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } for (let i = pos; i < blockLen; i++) buffer[i] = 0; view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2); this.process(view, 0); const oview = createView(out); const len = this.outputLen; if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit"); const outLen = len / 4; const state = this.get(); if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE2); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to ||= new this.constructor(); to.set(...this.get()); const { blockLen, buffer, length, finished, destroyed, pos } = this; to.destroyed = destroyed; to.finished = finished; to.length = length; to.pos = pos; if (length % blockLen) to.buffer.set(buffer); return to; } clone() { return this._cloneInto(); } }; SHA256_IV = /* @__PURE__ */ Uint32Array.from([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); SHA224_IV = /* @__PURE__ */ Uint32Array.from([ 3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428 ]); SHA384_IV = /* @__PURE__ */ Uint32Array.from([ 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428 ]); SHA512_IV = /* @__PURE__ */ Uint32Array.from([ 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209 ]); } }); // node_modules/@noble/hashes/_u64.js function fromBig(n, le = false) { if (le) return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; return { h: Number(n >> _3