@nhtio/swarm 1.20250425.0 → 1.20251110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var nu=Object.defineProperty;var iu=Object.getPrototypeOf;var su=Reflect.get;var Ya=e=>{throw TypeError(e)};var ou=(e,t,v)=>t in e?nu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:v}):e[t]=v;var Ta=(e,t,v)=>ou(e,typeof t!="symbol"?t+"":t,v),Wa=(e,t,v)=>t.has(e)||Ya("Cannot "+v);var fo=(e,t,v)=>(Wa(e,t,"read from private field"),v?v.call(e):t.get(e)),Xo=(e,t,v)=>t.has(e)?Ya("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,v),Jo=(e,t,v,w)=>(Wa(e,t,"write to private field"),w?w.call(e,v):t.set(e,v),v),Oo=(e,t,v)=>(Wa(e,t,"access private method"),v);var Ja=(e,t,v)=>su(iu(e),v,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const types$1=require("./types-C0eRuyk9.js"),errors=require("./errors-j8BTGk4y.js"),isTabEnvironment=()=>typeof window<"u"&&typeof window.navigator<"u"&&typeof window.navigator.userAgent<"u",isWorkerEnvironment=()=>typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope,isSsrEnvironment=()=>typeof process<"u"&&typeof process.versions<"u"&&!!process.versions.node,isSafari=()=>typeof window<"u"&&typeof window.navigator<"u"&&window.navigator.userAgent.includes("Safari")&&!window.navigator.userAgent.includes("Chrome");function isGlobalObject(e){return typeof e=="object"&&e!==null&&"Math"in e}const getGlobal=()=>{const t=[typeof window<"u"?window:void 0,typeof self<"u"?self:void 0,typeof global<"u"?global:void 0].filter(v=>isGlobalObject(v));if(t.length===0)throw new Error("No global object found");return t[0]},makeRandomId=e=>{const t=getGlobal(),v=new Uint8Array(e);if(typeof t.crypto<"u"&&typeof t.crypto.getRandomValues=="function")t.crypto.getRandomValues(v);else for(let w=0;w<e;w++)v[w]=Math.floor(Math.random()*256);return Array.from(v).map(w=>w.toString(16).padStart(2,"0")).join("")},FOR_SWARM=Symbol("nhtio.swarm"),FOR_LOGGER=Symbol("nhtio.swarm.logger"),FOR_ENCRYPTION=Symbol("nhtio.swarm.logger"),LogLevelStyles={EMERG:e=>[`%c${e}`,"color: white; background: #FF0000; font-weight: bold; padding: 2px 6px; border-radius: 2px"],ALERT:e=>[`%c${e}`,"color: white; background: #FF5555; font-weight: bold; padding: 2px 6px; border-radius: 2px"],CRIT:e=>[`%c${e}`,"color: white; background: #FF6F00; font-weight: bold; padding: 2px 6px; border-radius: 2px"],ERROR:e=>[`%c${e}`,"color: black; background: #FFA500; font-weight: bold; padding: 2px 6px; border-radius: 2px"],WARNING:e=>[`%c${e}`,"color: black; background: #FFD700; font-weight: bold; padding: 2px 6px; border-radius: 2px"],NOTICE:e=>[`%c${e}`,"color: black; background: #00CED1; font-weight: bold; padding: 2px 6px; border-radius: 2px"],INFO:e=>[`%c${e}`,"color: white; background: #1E90FF; font-weight: normal; padding: 2px 6px; border-radius: 2px"],DEBUG:e=>[`%c${e}`,"color: #AAAAAA; font-style: italic; padding: 2px 6px"]};var LogLevelValues=(e=>(e[e.EMERG=0]="EMERG",e[e.ALERT=1]="ALERT",e[e.CRIT=2]="CRIT",e[e.ERROR=3]="ERROR",e[e.WARNING=4]="WARNING",e[e.NOTICE=5]="NOTICE",e[e.INFO=6]="INFO",e[e.DEBUG=7]="DEBUG",e))(LogLevelValues||{});const EnvironmentStyles={BROWSER:e=>[`%c${e}`,"color: white; background: #3949AB; font-weight: bold; padding: 2px 6px; border-radius: 2px"],WORKER:e=>[`%c${e}`,"color: white; background: #5E35B1; font-weight: bold; padding: 2px 6px; border-radius: 2px"],SSR:e=>[`%c${e}`,"color: white; background: #607D8B; font-weight: bold; padding: 2px 6px; border-radius: 2px"],UNKNOWN:e=>[`%c${e}`,"color: black; background: #E0E0E0; font-weight: bold; font-style: italic; padding: 2px 6px; border-radius: 2px"]};var LogLevelConsoleMethods=(e=>(e.EMERG="error",e.ALERT="error",e.CRIT="error",e.ERROR="error",e.WARNING="warn",e.NOTICE="info",e.INFO="info",e.DEBUG="debug",e))(LogLevelConsoleMethods||{}),Na,La,Da,ja,Ca,xa,Qo,Xa,ea;class Logger{constructor(t=3){Xo(this,Qo);Xo(this,Na);Xo(this,La);Xo(this,Da);Xo(this,ja);Xo(this,Ca);Xo(this,xa);Jo(this,xa,t),Jo(this,Na,isTabEnvironment()),Jo(this,La,isWorkerEnvironment()),Jo(this,Da,isSsrEnvironment()),Jo(this,ja,isSafari())}get level(){return LogLevelValues[fo(this,xa)]}set level(t){Jo(this,xa,LogLevelValues[t.toUpperCase()])}EMERG(...t){Oo(this,Qo,ea).call(this,"EMERG",...t)}ALERT(...t){Oo(this,Qo,ea).call(this,"ALERT",...t)}CRIT(...t){Oo(this,Qo,ea).call(this,"CRIT",...t)}ERROR(...t){Oo(this,Qo,ea).call(this,"ERROR",...t)}WARNING(...t){Oo(this,Qo,ea).call(this,"WARNING",...t)}NOTICE(...t){Oo(this,Qo,ea).call(this,"NOTICE",...t)}INFO(...t){Oo(this,Qo,ea).call(this,"INFO",...t)}DEBUG(...t){Oo(this,Qo,ea).call(this,"DEBUG",...t)}emerg(...t){Oo(this,Qo,ea).call(this,"EMERG",...t)}alert(...t){Oo(this,Qo,ea).call(this,"ALERT",...t)}crit(...t){Oo(this,Qo,ea).call(this,"CRIT",...t)}error(...t){Oo(this,Qo,ea).call(this,"ERROR",...t)}warning(...t){Oo(this,Qo,ea).call(this,"WARNING",...t)}notice(...t){Oo(this,Qo,ea).call(this,"NOTICE",...t)}info(...t){Oo(this,Qo,ea).call(this,"INFO",...t)}debug(...t){Oo(this,Qo,ea).call(this,"DEBUG",...t)}}Na=new WeakMap,La=new WeakMap,Da=new WeakMap,ja=new WeakMap,Ca=new WeakMap,xa=new WeakMap,Qo=new WeakSet,Xa=function(){let t;return fo(this,Na)?t="BROWSER":fo(this,La)?t="WORKER":fo(this,Da)?t="SSR":t="UNKNOWN",EnvironmentStyles[t](t)},ea=function(t,...v){t=t.toUpperCase();const w=LogLevelValues[t],T=LogLevelValues[fo(this,xa)];if(w>T)return;const[x,C]=Oo(this,Qo,Xa).call(this),[D,Y]=LogLevelStyles[t](t),L=[`${x}${D}${fo(this,Ca)?`%c ${fo(this,Ca)}`:""}`,C,Y];for(fo(this,Ca)&&L.push("color: inherit"),L.push(...v);L[L.length-1]===void 0;)L.pop();fo(this,ja)||fo(this,Da)?console[LogLevelConsoleMethods[t]](...L):(console.groupCollapsed(...L),console.debug(new Error("stack").stack.split(`
1
+ "use strict";var nu=Object.defineProperty;var iu=Object.getPrototypeOf;var su=Reflect.get;var Ya=e=>{throw TypeError(e)};var ou=(e,t,v)=>t in e?nu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:v}):e[t]=v;var Ta=(e,t,v)=>ou(e,typeof t!="symbol"?t+"":t,v),Wa=(e,t,v)=>t.has(e)||Ya("Cannot "+v);var fo=(e,t,v)=>(Wa(e,t,"read from private field"),v?v.call(e):t.get(e)),Xo=(e,t,v)=>t.has(e)?Ya("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,v),Jo=(e,t,v,w)=>(Wa(e,t,"write to private field"),w?w.call(e,v):t.set(e,v),v),Oo=(e,t,v)=>(Wa(e,t,"access private method"),v);var Ja=(e,t,v)=>su(iu(e),v,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const types$1=require("./types-C0eRuyk9.js"),errors=require("./errors-j8BTGk4y.js"),isTabEnvironment=()=>typeof window<"u"&&typeof window.navigator<"u"&&typeof window.navigator.userAgent<"u",isWorkerEnvironment=()=>typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope,isWebWorkerEnvironment=()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,isSsrEnvironment=()=>typeof process<"u"&&typeof process.versions<"u"&&!!process.versions.node,isSafari=()=>typeof window<"u"&&typeof window.navigator<"u"&&window.navigator.userAgent.includes("Safari")&&!window.navigator.userAgent.includes("Chrome");function isGlobalObject(e){return typeof e=="object"&&e!==null&&"Math"in e}const getGlobal=()=>{const t=[typeof window<"u"?window:void 0,typeof self<"u"?self:void 0,typeof global<"u"?global:void 0].filter(v=>isGlobalObject(v));if(t.length===0)throw new Error("No global object found");return t[0]},makeRandomId=e=>{const t=getGlobal(),v=new Uint8Array(e);if(typeof t.crypto<"u"&&typeof t.crypto.getRandomValues=="function")t.crypto.getRandomValues(v);else for(let w=0;w<e;w++)v[w]=Math.floor(Math.random()*256);return Array.from(v).map(w=>w.toString(16).padStart(2,"0")).join("")},FOR_SWARM=Symbol("nhtio.swarm"),FOR_LOGGER=Symbol("nhtio.swarm.logger"),FOR_ENCRYPTION=Symbol("nhtio.swarm.logger"),LogLevelStyles={EMERG:e=>[`%c${e}`,"color: white; background: #FF0000; font-weight: bold; padding: 2px 6px; border-radius: 2px"],ALERT:e=>[`%c${e}`,"color: white; background: #FF5555; font-weight: bold; padding: 2px 6px; border-radius: 2px"],CRIT:e=>[`%c${e}`,"color: white; background: #FF6F00; font-weight: bold; padding: 2px 6px; border-radius: 2px"],ERROR:e=>[`%c${e}`,"color: black; background: #FFA500; font-weight: bold; padding: 2px 6px; border-radius: 2px"],WARNING:e=>[`%c${e}`,"color: black; background: #FFD700; font-weight: bold; padding: 2px 6px; border-radius: 2px"],NOTICE:e=>[`%c${e}`,"color: black; background: #00CED1; font-weight: bold; padding: 2px 6px; border-radius: 2px"],INFO:e=>[`%c${e}`,"color: white; background: #1E90FF; font-weight: normal; padding: 2px 6px; border-radius: 2px"],DEBUG:e=>[`%c${e}`,"color: #AAAAAA; font-style: italic; padding: 2px 6px"]};var LogLevelValues=(e=>(e[e.EMERG=0]="EMERG",e[e.ALERT=1]="ALERT",e[e.CRIT=2]="CRIT",e[e.ERROR=3]="ERROR",e[e.WARNING=4]="WARNING",e[e.NOTICE=5]="NOTICE",e[e.INFO=6]="INFO",e[e.DEBUG=7]="DEBUG",e))(LogLevelValues||{});const EnvironmentStyles={BROWSER:e=>[`%c${e}`,"color: white; background: #3949AB; font-weight: bold; padding: 2px 6px; border-radius: 2px"],WORKER:e=>[`%c${e}`,"color: white; background: #5E35B1; font-weight: bold; padding: 2px 6px; border-radius: 2px"],SSR:e=>[`%c${e}`,"color: white; background: #607D8B; font-weight: bold; padding: 2px 6px; border-radius: 2px"],UNKNOWN:e=>[`%c${e}`,"color: black; background: #E0E0E0; font-weight: bold; font-style: italic; padding: 2px 6px; border-radius: 2px"]};var LogLevelConsoleMethods=(e=>(e.EMERG="error",e.ALERT="error",e.CRIT="error",e.ERROR="error",e.WARNING="warn",e.NOTICE="info",e.INFO="info",e.DEBUG="debug",e))(LogLevelConsoleMethods||{}),Na,La,Da,ja,Ca,xa,Qo,Xa,ea;class Logger{constructor(t=3){Xo(this,Qo);Xo(this,Na);Xo(this,La);Xo(this,Da);Xo(this,ja);Xo(this,Ca);Xo(this,xa);Jo(this,xa,t),Jo(this,Na,isTabEnvironment()),Jo(this,La,isWorkerEnvironment()),Jo(this,Da,isSsrEnvironment()),Jo(this,ja,isSafari())}get level(){return LogLevelValues[fo(this,xa)]}set level(t){Jo(this,xa,LogLevelValues[t.toUpperCase()])}EMERG(...t){Oo(this,Qo,ea).call(this,"EMERG",...t)}ALERT(...t){Oo(this,Qo,ea).call(this,"ALERT",...t)}CRIT(...t){Oo(this,Qo,ea).call(this,"CRIT",...t)}ERROR(...t){Oo(this,Qo,ea).call(this,"ERROR",...t)}WARNING(...t){Oo(this,Qo,ea).call(this,"WARNING",...t)}NOTICE(...t){Oo(this,Qo,ea).call(this,"NOTICE",...t)}INFO(...t){Oo(this,Qo,ea).call(this,"INFO",...t)}DEBUG(...t){Oo(this,Qo,ea).call(this,"DEBUG",...t)}emerg(...t){Oo(this,Qo,ea).call(this,"EMERG",...t)}alert(...t){Oo(this,Qo,ea).call(this,"ALERT",...t)}crit(...t){Oo(this,Qo,ea).call(this,"CRIT",...t)}error(...t){Oo(this,Qo,ea).call(this,"ERROR",...t)}warning(...t){Oo(this,Qo,ea).call(this,"WARNING",...t)}notice(...t){Oo(this,Qo,ea).call(this,"NOTICE",...t)}info(...t){Oo(this,Qo,ea).call(this,"INFO",...t)}debug(...t){Oo(this,Qo,ea).call(this,"DEBUG",...t)}}Na=new WeakMap,La=new WeakMap,Da=new WeakMap,ja=new WeakMap,Ca=new WeakMap,xa=new WeakMap,Qo=new WeakSet,Xa=function(){let t;return fo(this,Na)?t="BROWSER":fo(this,La)?t="WORKER":fo(this,Da)?t="SSR":t="UNKNOWN",EnvironmentStyles[t](t)},ea=function(t,...v){t=t.toUpperCase();const w=LogLevelValues[t],T=LogLevelValues[fo(this,xa)];if(w>T)return;const[x,C]=Oo(this,Qo,Xa).call(this),[D,Y]=LogLevelStyles[t](t),L=[`${x}${D}${fo(this,Ca)?`%c ${fo(this,Ca)}`:""}`,C,Y];for(fo(this,Ca)&&L.push("color: inherit"),L.push(...v);L[L.length-1]===void 0;)L.pop();fo(this,ja)||fo(this,Da)?console[LogLevelConsoleMethods[t]](...L):(console.groupCollapsed(...L),console.debug(new Error("stack").stack.split(`
2
2
  `).slice(3).join(`
3
3
  `)),console.groupEnd())};const getLogLevel=()=>{const e=getGlobal();return typeof e.SWARM_LOG_LEVEL=="string"&&e.SWARM_LOG_LEVEL.toUpperCase()in LogLevelValues?e.SWARM_LOG_LEVEL:3},getLogger=()=>{const e=getGlobal();if(typeof e[FOR_LOGGER]<"u"&&e[FOR_LOGGER]instanceof Logger)return e[FOR_LOGGER];const t=getLogLevel(),v=LogLevelValues[t],w=new Logger(v);return e[FOR_LOGGER]=w,w},setLogLevel=e=>{const t=getGlobal(),v=getLogger();t.SWARM_LOG_LEVEL=e.toUpperCase(),v.level=e};var tinyEmitter={exports:{}};tinyEmitter.exports;function E$2(){}E$2.prototype={on:function(e,t,v){var w=this.e||(this.e={});return(w[e]||(w[e]=[])).push({fn:t,ctx:v}),this},once:function(e,t,v){var w=this;function T(){w.off(e,T),t.apply(v,arguments)}return T._=t,this.on(e,T,v)},emit:function(e){var t=[].slice.call(arguments,1),v=((this.e||(this.e={}))[e]||[]).slice(),w=0,T=v.length;for(w;w<T;w++)v[w].fn.apply(v[w].ctx,t);return this},off:function(e,t){var v=this.e||(this.e={}),w=v[e],T=[];if(w&&t)for(var x=0,C=w.length;x<C;x++)w[x].fn!==t&&w[x].fn._!==t&&T.push(w[x]);return T.length?v[e]=T:delete v[e],this}};tinyEmitter.exports=E$2;var TinyEmitter=tinyEmitter.exports.TinyEmitter=E$2;tinyEmitter.exports;class TypedEventEmitter extends TinyEmitter{on(t,v,w){return super.on(t,v,w),this}once(t,v,w){return super.once(t,v,w),this}emit(t,...v){return super.emit(t,...v),this}off(t,v){return super.off(t,v),this}}function isPromise(e){return e&&typeof e.then=="function"}Promise.resolve(!1);var PROMISE_RESOLVED_TRUE=Promise.resolve(!0),PROMISE_RESOLVED_VOID=Promise.resolve();function sleep(e,t){return e||(e=0),new Promise(function(v){return setTimeout(function(){return v(t)},e)})}function randomInt(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function randomToken(){return Math.random().toString(36).substring(2)}var lastMs=0;function microSeconds$4(){var e=Date.now()*1e3;return e<=lastMs&&(e=lastMs+1),lastMs=e,e}function supportsWebLockAPI(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}var microSeconds$3=microSeconds$4,type$4="native";function create$3(e){var t={time:microSeconds$4(),messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(v){t.messagesCallback&&t.messagesCallback(v.data)},t}function close$3(e){e.bc.close(),e.subFns=[]}function postMessage$3(e,t){try{return e.bc.postMessage(t,!1),PROMISE_RESOLVED_VOID}catch(v){return Promise.reject(v)}}function onMessage$3(e,t){e.messagesCallback=t}function canBeUsed$3(){if(typeof globalThis<"u"&&globalThis.Deno&&globalThis.Deno.args)return!0;if((typeof window<"u"||typeof self<"u")&&typeof BroadcastChannel=="function"){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}else return!1}function averageResponseTime$3(){return 150}var NativeMethod={create:create$3,close:close$3,onMessage:onMessage$3,postMessage:postMessage$3,canBeUsed:canBeUsed$3,type:type$4,averageResponseTime:averageResponseTime$3,microSeconds:microSeconds$3};class ObliviousSet{constructor(t){Ta(this,"ttl");Ta(this,"map",new Map);Ta(this,"_to",!1);this.ttl=t}has(t){return this.map.has(t)}add(t){this.map.set(t,now$1()),this._to||(this._to=!0,setTimeout(()=>{this._to=!1,removeTooOldValues(this)},0))}clear(){this.map.clear()}}function removeTooOldValues(e){const t=now$1()-e.ttl,v=e.map[Symbol.iterator]();for(;;){const w=v.next().value;if(!w)return;const T=w[0];if(w[1]<t)e.map.delete(T);else return}}function now$1(){return Date.now()}function fillOptionsWithDefaults$1(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return typeof t.webWorkerSupport>"u"&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=1e3*45),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&typeof e.idb.onclose=="function"&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=1e3*60),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=1e3*60*2),t.node.maxParallelWrites||(t.node.maxParallelWrites=2048),typeof t.node.useFastPath>"u"&&(t.node.useFastPath=!0),t}var microSeconds$2=microSeconds$4,DB_PREFIX="pubkey.broadcast-channel-0-",OBJECT_STORE_ID="messages",TRANSACTION_SETTINGS={durability:"relaxed"},type$3="idb";function getIdb(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"){if(typeof window.mozIndexedDB<"u")return window.mozIndexedDB;if(typeof window.webkitIndexedDB<"u")return window.webkitIndexedDB;if(typeof window.msIndexedDB<"u")return window.msIndexedDB}return!1}function commitIndexedDBTransaction(e){e.commit&&e.commit()}function createDatabase(e){var t=getIdb(),v=DB_PREFIX+e,w=t.open(v);return w.onupgradeneeded=function(T){var x=T.target.result;x.createObjectStore(OBJECT_STORE_ID,{keyPath:"id",autoIncrement:!0})},new Promise(function(T,x){w.onerror=function(C){return x(C)},w.onsuccess=function(){T(w.result)}})}function writeMessage(e,t,v){var w=Date.now(),T={uuid:t,time:w,data:v},x=e.transaction([OBJECT_STORE_ID],"readwrite",TRANSACTION_SETTINGS);return new Promise(function(C,D){x.oncomplete=function(){return C()},x.onerror=function(L){return D(L)};var Y=x.objectStore(OBJECT_STORE_ID);Y.add(T),commitIndexedDBTransaction(x)})}function getMessagesHigherThan(e,t){var v=e.transaction(OBJECT_STORE_ID,"readonly",TRANSACTION_SETTINGS),w=v.objectStore(OBJECT_STORE_ID),T=[],x=IDBKeyRange.bound(t+1,1/0);if(w.getAll){var C=w.getAll(x);return new Promise(function(Y,L){C.onerror=function(q){return L(q)},C.onsuccess=function(q){Y(q.target.result)}})}function D(){try{return x=IDBKeyRange.bound(t+1,1/0),w.openCursor(x)}catch{return w.openCursor()}}return new Promise(function(Y,L){var q=D();q.onerror=function(N){return L(N)},q.onsuccess=function(N){var F=N.target.result;F?F.value.id<t+1?F.continue(t+1):(T.push(F.value),F.continue()):(commitIndexedDBTransaction(v),Y(T))}})}function removeMessagesById(e,t){if(e.closed)return Promise.resolve([]);var v=e.db.transaction(OBJECT_STORE_ID,"readwrite",TRANSACTION_SETTINGS),w=v.objectStore(OBJECT_STORE_ID);return Promise.all(t.map(function(T){var x=w.delete(T);return new Promise(function(C){x.onsuccess=function(){return C()}})}))}function getOldMessages(e,t){var v=Date.now()-t,w=e.transaction(OBJECT_STORE_ID,"readonly",TRANSACTION_SETTINGS),T=w.objectStore(OBJECT_STORE_ID),x=[];return new Promise(function(C){T.openCursor().onsuccess=function(D){var Y=D.target.result;if(Y){var L=Y.value;L.time<v?(x.push(L),Y.continue()):(commitIndexedDBTransaction(w),C(x))}else C(x)}})}function cleanOldMessages(e){return getOldMessages(e.db,e.options.idb.ttl).then(function(t){return removeMessagesById(e,t.map(function(v){return v.id}))})}function create$2(e,t){return t=fillOptionsWithDefaults$1(t),createDatabase(e).then(function(v){var w={closed:!1,lastCursorId:0,channelName:e,options:t,uuid:randomToken(),eMIs:new ObliviousSet(t.idb.ttl*2),writeBlockPromise:PROMISE_RESOLVED_VOID,messagesCallback:null,readQueuePromises:[],db:v};return v.onclose=function(){w.closed=!0,t.idb.onclose&&t.idb.onclose()},_readLoop(w),w})}function _readLoop(e){e.closed||readNewMessages(e).then(function(){return sleep(e.options.idb.fallbackInterval)}).then(function(){return _readLoop(e)})}function _filterMessage(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time<t.messagesCallbackTime)}function readNewMessages(e){return e.closed||!e.messagesCallback?PROMISE_RESOLVED_VOID:getMessagesHigherThan(e.db,e.lastCursorId).then(function(t){var v=t.filter(function(w){return!!w}).map(function(w){return w.id>e.lastCursorId&&(e.lastCursorId=w.id),w}).filter(function(w){return _filterMessage(w,e)}).sort(function(w,T){return w.time-T.time});return v.forEach(function(w){e.messagesCallback&&(e.eMIs.add(w.id),e.messagesCallback(w.data))}),PROMISE_RESOLVED_VOID})}function close$2(e){e.closed=!0,e.db.close()}function postMessage$2(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return writeMessage(e.db,e.uuid,t)}).then(function(){randomInt(0,10)===0&&cleanOldMessages(e)}),e.writeBlockPromise}function onMessage$2(e,t,v){e.messagesCallbackTime=v,e.messagesCallback=t,readNewMessages(e)}function canBeUsed$2(){return!!getIdb()}function averageResponseTime$2(e){return e.idb.fallbackInterval*2}var IndexedDBMethod={create:create$2,close:close$2,onMessage:onMessage$2,postMessage:postMessage$2,canBeUsed:canBeUsed$2,type:type$3,averageResponseTime:averageResponseTime$2,microSeconds:microSeconds$2},microSeconds$1=microSeconds$4,KEY_PREFIX="pubkey.broadcastChannel-",type$2="localstorage";function getLocalStorage(){var e;if(typeof window>"u")return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch{}return e}function storageKey(e){return KEY_PREFIX+e}function postMessage$1(e,t){return new Promise(function(v){sleep().then(function(){var w=storageKey(e.channelName),T={token:randomToken(),time:Date.now(),data:t,uuid:e.uuid},x=JSON.stringify(T);getLocalStorage().setItem(w,x);var C=document.createEvent("Event");C.initEvent("storage",!0,!0),C.key=w,C.newValue=x,window.dispatchEvent(C),v()})})}function addStorageEventListener(e,t){var v=storageKey(e),w=function(x){x.key===v&&t(JSON.parse(x.newValue))};return window.addEventListener("storage",w),w}function removeStorageEventListener(e){window.removeEventListener("storage",e)}function create$1(e,t){if(t=fillOptionsWithDefaults$1(t),!canBeUsed$1())throw new Error("BroadcastChannel: localstorage cannot be used");var v=randomToken(),w=new ObliviousSet(t.localstorage.removeTimeout),T={channelName:e,uuid:v,eMIs:w};return T.listener=addStorageEventListener(e,function(x){T.messagesCallback&&x.uuid!==v&&(!x.token||w.has(x.token)||x.data.time&&x.data.time<T.messagesCallbackTime||(w.add(x.token),T.messagesCallback(x.data)))}),T}function close$1(e){removeStorageEventListener(e.listener)}function onMessage$1(e,t,v){e.messagesCallbackTime=v,e.messagesCallback=t}function canBeUsed$1(){var e=getLocalStorage();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch{return!1}return!0}function averageResponseTime$1(){var e=120,t=navigator.userAgent.toLowerCase();return t.includes("safari")&&!t.includes("chrome")?e*2:e}var LocalstorageMethod={create:create$1,close:close$1,onMessage:onMessage$1,postMessage:postMessage$1,canBeUsed:canBeUsed$1,type:type$2,averageResponseTime:averageResponseTime$1,microSeconds:microSeconds$1},microSeconds=microSeconds$4,type$1="simulate",SIMULATE_CHANNELS=new Set;function create(e){var t={time:microSeconds(),name:e,messagesCallback:null};return SIMULATE_CHANNELS.add(t),t}function close(e){SIMULATE_CHANNELS.delete(e)}var SIMULATE_DELAY_TIME=5;function postMessage(e,t){return new Promise(function(v){return setTimeout(function(){var w=Array.from(SIMULATE_CHANNELS);w.forEach(function(T){T.name===e.name&&T!==e&&T.messagesCallback&&T.time<t.time&&T.messagesCallback(t)}),v()},SIMULATE_DELAY_TIME)})}function onMessage(e,t){e.messagesCallback=t}function canBeUsed(){return!0}function averageResponseTime(){return SIMULATE_DELAY_TIME}var SimulateMethod={create,close,onMessage,postMessage,canBeUsed,type:type$1,averageResponseTime,microSeconds},METHODS=[NativeMethod,IndexedDBMethod,LocalstorageMethod];function chooseMethod(e){var t=[].concat(e.methods,METHODS).filter(Boolean);if(e.type){if(e.type==="simulate")return SimulateMethod;var v=t.find(function(T){return T.type===e.type});if(v)return v;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||(t=t.filter(function(T){return T.type!=="idb"}));var w=t.find(function(T){return T.canBeUsed()});if(w)return w;throw new Error("No usable method found in "+JSON.stringify(METHODS.map(function(T){return T.type})))}var OPEN_BROADCAST_CHANNELS=new Set,lastId=0,BroadcastChannel$1=function(t,v){this.id=lastId++,OPEN_BROADCAST_CHANNELS.add(this),this.name=t,ENFORCED_OPTIONS&&(v=ENFORCED_OPTIONS),this.options=fillOptionsWithDefaults$1(v),this.method=chooseMethod(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,_prepareChannel(this)};BroadcastChannel$1._pubkey=!0;var ENFORCED_OPTIONS;BroadcastChannel$1.prototype={postMessage:function(t){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(t));return _post(this,"message",t)},postInternal:function(t){return _post(this,"internal",t)},set onmessage(e){var t=this.method.microSeconds(),v={time:t,fn:e};_removeListenerObject(this,"message",this._onML),e&&typeof e=="function"?(this._onML=v,_addListenerObject(this,"message",v)):this._onML=null},addEventListener:function(t,v){var w=this.method.microSeconds(),T={time:w,fn:v};_addListenerObject(this,t,T)},removeEventListener:function(t,v){var w=this._addEL[t].find(function(T){return T.fn===v});_removeListenerObject(this,t,w)},close:function(){var t=this;if(!this.closed){OPEN_BROADCAST_CHANNELS.delete(this),this.closed=!0;var v=this._prepP?this._prepP:PROMISE_RESOLVED_VOID;return this._onML=null,this._addEL.message=[],v.then(function(){return Promise.all(Array.from(t._uMP))}).then(function(){return Promise.all(t._befC.map(function(w){return w()}))}).then(function(){return t.method.close(t._state)})}},get type(){return this.method.type},get isClosed(){return this.closed}};function _post(e,t,v){var w=e.method.microSeconds(),T={time:w,type:t,data:v},x=e._prepP?e._prepP:PROMISE_RESOLVED_VOID;return x.then(function(){var C=e.method.postMessage(e._state,T);return e._uMP.add(C),C.catch().then(function(){return e._uMP.delete(C)}),C})}function _prepareChannel(e){var t=e.method.create(e.name,e.options);isPromise(t)?(e._prepP=t,t.then(function(v){e._state=v})):e._state=t}function _hasMessageListeners(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function _addListenerObject(e,t,v){e._addEL[t].push(v),_startListening(e)}function _removeListenerObject(e,t,v){e._addEL[t]=e._addEL[t].filter(function(w){return w!==v}),_stopListening(e)}function _startListening(e){if(!e._iL&&_hasMessageListeners(e)){var t=function(T){e._addEL[T.type].forEach(function(x){T.time>=x.time&&x.fn(T.data)})},v=e.method.microSeconds();e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,v)}):(e._iL=!0,e.method.onMessage(e._state,t,v))}}function _stopListening(e){if(e._iL&&!_hasMessageListeners(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}function addBrowser(e){if(typeof WorkerGlobalScope=="function"&&self instanceof WorkerGlobalScope){var t=self.close.bind(self);self.close=function(){return e(),t()}}else{if(typeof window.addEventListener!="function")return;window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0)}}function addNode(e){process.on("exit",function(){return e()}),process.on("beforeExit",function(){return e().then(function(){return process.exit()})}),process.on("SIGINT",function(){return e().then(function(){return process.exit()})}),process.on("uncaughtException",function(t){return e().then(function(){console.trace(t),process.exit(101)})})}var isNode=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",USE_METHOD=isNode?addNode:addBrowser,LISTENERS=new Set,startedListening=!1;function startListening(){startedListening||(startedListening=!0,USE_METHOD(runAll))}function add(e){if(startListening(),typeof e!="function")throw new Error("Listener is no function");LISTENERS.add(e);var t={remove:function(){return LISTENERS.delete(e)},run:function(){return LISTENERS.delete(e),e()}};return t}function runAll(){var e=[];return LISTENERS.forEach(function(t){e.push(t()),LISTENERS.delete(t)}),Promise.all(e)}function sendLeaderMessage(e,t){var v={context:"leader",action:t,token:e.token};return e.broadcastChannel.postInternal(v)}function beLeader(e){e.isLeader=!0,e._hasLeader=!0;var t=add(function(){return e.die()});e._unl.push(t);var v=function(T){T.context==="leader"&&T.action==="apply"&&sendLeaderMessage(e,"tell"),T.context==="leader"&&T.action==="tell"&&!e._dpLC&&(e._dpLC=!0,e._dpL(),sendLeaderMessage(e,"tell"))};return e.broadcastChannel.addEventListener("internal",v),e._lstns.push(v),sendLeaderMessage(e,"tell")}var LeaderElectionWebLock=function(t,v){var w=this;this.broadcastChannel=t,t._befC.push(function(){return w.die()}),this._options=v,this.isLeader=!1,this.isDead=!1,this.token=randomToken(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+t.method.type+"||"+t.name};LeaderElectionWebLock.prototype={hasLeader:function(){var t=this;return navigator.locks.query().then(function(v){var w=v.held?v.held.filter(function(T){return T.name===t.lN}):[];return!!(w&&w.length>0)})},awaitLeadership:function(){var t=this;if(!this._wLMP){this._wKMC.c=new AbortController;var v=new Promise(function(w,T){t._wKMC.res=w,t._wKMC.rej=T});this._wLMP=new Promise(function(w){navigator.locks.request(t.lN,{signal:t._wKMC.c.signal},function(){return t._wKMC.c=void 0,beLeader(t),w(),v}).catch(function(){})})}return this._wLMP},set onduplicate(e){},die:function(){var t=this;return this._lstns.forEach(function(v){return t.broadcastChannel.removeEventListener("internal",v)}),this._lstns=[],this._unl.forEach(function(v){return v.remove()}),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort("LeaderElectionWebLock.die() called"),sendLeaderMessage(this,"death")}};var LeaderElection=function(t,v){var w=this;this.broadcastChannel=t,this._options=v,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=randomToken(),this._aplQ=PROMISE_RESOLVED_VOID,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var T=function(C){C.context==="leader"&&(C.action==="death"&&(w._hasLeader=!1),C.action==="tell"&&(w._hasLeader=!0))};this.broadcastChannel.addEventListener("internal",T),this._lstns.push(T)};LeaderElection.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(t){var v=this;if(this.isLeader)return sleep(0,!0);if(this.isDead)return sleep(0,!1);if(this._aplQC>1)return this._aplQ;var w=function(){if(v.isLeader)return PROMISE_RESOLVED_TRUE;var x=!1,C,D=new Promise(function(q){C=function(){x=!0,q()}}),Y=function(N){N.context==="leader"&&N.token!=v.token&&(N.action==="apply"&&N.token>v.token&&C(),N.action==="tell"&&(C(),v._hasLeader=!0))};v.broadcastChannel.addEventListener("internal",Y);var L=t?v._options.responseTime*4:v._options.responseTime;return sendLeaderMessage(v,"apply").then(function(){return Promise.race([sleep(L),D.then(function(){return Promise.reject(new Error)})])}).then(function(){return sendLeaderMessage(v,"apply")}).then(function(){return Promise.race([sleep(L),D.then(function(){return Promise.reject(new Error)})])}).catch(function(){}).then(function(){return v.broadcastChannel.removeEventListener("internal",Y),x?!1:beLeader(v).then(function(){return!0})})};return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then(function(){return w()}).then(function(){v._aplQC=v._aplQC-1}),this._aplQ.then(function(){return v.isLeader})},awaitLeadership:function(){return this._aLP||(this._aLP=_awaitLeadershipOnce(this)),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var t=this;return this._lstns.forEach(function(v){return t.broadcastChannel.removeEventListener("internal",v)}),this._lstns=[],this._unl.forEach(function(v){return v.remove()}),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,sendLeaderMessage(this,"death")}};function _awaitLeadershipOnce(e){return e.isLeader?PROMISE_RESOLVED_VOID:new Promise(function(t){var v=!1;function w(){v||(v=!0,e.broadcastChannel.removeEventListener("internal",x),t(!0))}e.applyOnce().then(function(){e.isLeader&&w()});var T=function(){return sleep(e._options.fallbackInterval).then(function(){if(!(e.isDead||v))if(e.isLeader)w();else return e.applyOnce(!0).then(function(){e.isLeader?w():T()})})};T();var x=function(D){D.context==="leader"&&D.action==="death"&&(e._hasLeader=!1,e.applyOnce().then(function(){e.isLeader&&w()}))};e.broadcastChannel.addEventListener("internal",x),e._lstns.push(x)})}function fillOptionsWithDefaults(e,t){return e||(e={}),e=JSON.parse(JSON.stringify(e)),e.fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}function createLeaderElection(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=fillOptionsWithDefaults(t,e);var v=supportsWebLockAPI()?new LeaderElectionWebLock(e,t):new LeaderElection(e,t);return e._befC.push(function(){return v.die()}),e._leaderElector=v,v}var d$1=Object.defineProperty,f$2=e=>{throw TypeError(e)},p$1=(e,t,v)=>t in e?d$1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:v}):e[t]=v,h=(e,t,v)=>p$1(e,typeof t!="symbol"?t+"":t,v),b$1=(e,t,v)=>t.has(e)||f$2("Cannot "+v),n$1=(e,t,v)=>(b$1(e,t,"read from private field"),v?v.call(e):t.get(e)),l$2=(e,t,v)=>t.has(e)?f$2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,v),E$1=(e,t,v,w)=>(b$1(e,t,"write to private field"),w?w.call(e,v):t.set(e,v),v);const u$1=class extends TypeError{constructor(t,v,w){const T=w?{cause:w.cause}:{};super(v,T),h(this,"$__name"),h(this,"$__message");const x=this.constructor;if(Object.setPrototypeOf(this,x),this.$__name=t,this.$__message=v,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,x),typeof this.stack!="string"&&Object.defineProperty(this,"stack",{value:"",writable:!0,enumerable:!1,configurable:!0}),this.stack&&w&&w.trim&&w.trim>0){const C=this.stack.split(`
4
4
  `);C.splice(0,w.trim),this.stack=C.join(`
@@ -45,5 +45,5 @@ ${yr}`,Xi=Math.min(Oi.length,Li);let to=0;for(;to<Xi-1;to++){const Gi=Di(String(
45
45
  ${xi}`,Mi.pop(),`[${Ni}]`}let Si=Object.keys(Oi);const Ci=Si.length;if(Ci===0)return"{}";if(Ti<Mi.length+1)return'"[Object]"';yr+=ki;const Ki=`,
46
46
  ${yr}`;let Yi="",Qi="",Zi=Math.min(Ci,Li);Y(Oi)&&(Yi+=L(Oi,Ki,Li),Si=Si.slice(Oi.length),Zi-=Oi.length,Qi=Ki),Wi&&(Si=C(Si,Vi)),Mi.push(Oi);for(let Ni=0;Ni<Zi;Ni++){const Fi=Si[Ni],Xi=Di(Fi,Oi[Fi],Mi,ki,yr);Xi!==void 0&&(Yi+=`${Qi}${x(Fi)}: ${Xi}`,Qi=Ki)}if(Ci>Li){const Ni=Ci-Li;Yi+=`${Qi}"...": "${he(Ni)} not stringified"`,Qi=Ki}return Qi!==""&&(Yi=`
47
47
  ${yr}${Yi}
48
- ${xi}`),Mi.pop(),`{${Yi}}`}case"number":return isFinite(Oi)?String(Oi):_r?_r(Oi):"null";case"boolean":return Oi===!0?"true":"false";case"undefined":return;case"bigint":if(qi)return String(Oi);default:return _r?_r(Oi):void 0}}function z(vr,Oi,Mi){switch(typeof Oi){case"string":return x(Oi);case"object":{if(Oi===null)return"null";if(typeof Oi.toJSON=="function"){if(Oi=Oi.toJSON(vr),typeof Oi!="object")return z(vr,Oi,Mi);if(Oi===null)return"null"}if(Mi.indexOf(Oi)!==-1)return Bi;let ki="";const yr=Oi.length!==void 0;if(yr&&Array.isArray(Oi)){if(Oi.length===0)return"[]";if(Ti<Mi.length+1)return'"[Array]"';Mi.push(Oi);const Yi=Math.min(Oi.length,Li);let Qi=0;for(;Qi<Yi-1;Qi++){const Ni=z(String(Qi),Oi[Qi],Mi);ki+=Ni!==void 0?Ni:"null",ki+=","}const Zi=z(String(Qi),Oi[Qi],Mi);if(ki+=Zi!==void 0?Zi:"null",Oi.length-1>Li){const Ni=Oi.length-Li-1;ki+=`,"... ${he(Ni)} not stringified"`}return Mi.pop(),`[${ki}]`}let xi=Object.keys(Oi);const Si=xi.length;if(Si===0)return"{}";if(Ti<Mi.length+1)return'"[Object]"';let Ci="",Ki=Math.min(Si,Li);yr&&Y(Oi)&&(ki+=L(Oi,",",Li),xi=xi.slice(Oi.length),Ki-=Oi.length,Ci=","),Wi&&(xi=C(xi,Vi)),Mi.push(Oi);for(let Yi=0;Yi<Ki;Yi++){const Qi=xi[Yi],Zi=z(Qi,Oi[Qi],Mi);Zi!==void 0&&(ki+=`${Ci}${x(Qi)}:${Zi}`,Ci=",")}if(Si>Li){const Yi=Si-Li;ki+=`${Ci}"...":"${he(Yi)} not stringified"`}return Mi.pop(),`{${ki}}`}case"number":return isFinite(Oi)?String(Oi):_r?_r(Oi):"null";case"boolean":return Oi===!0?"true":"false";case"undefined":return;case"bigint":if(qi)return String(Oi);default:return _r?_r(Oi):void 0}}function gr(vr,Oi,Mi){if(arguments.length>1){let ki="";if(typeof Mi=="number"?ki=" ".repeat(Math.min(Mi,10)):typeof Mi=="string"&&(ki=Mi.slice(0,10)),Oi!=null){if(typeof Oi=="function")return Hi("",{"":vr},[],Oi,ki,"");if(Array.isArray(Oi))return pr("",vr,[],tt(Oi),ki,"")}if(ki.length!==0)return Di("",vr,[],ki,"")}return z("",vr,[])}return gr}})(safeStableStringify,safeStableStringify.exports);var safeStableStringifyExports=safeStableStringify.exports;const cjsModule=getDefaultExportFromCjs$1(safeStableStringifyExports),configure=cjsModule.configure;var RGX=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,SEC=1e3,MIN=SEC*60,HOUR=MIN*60,DAY=HOUR*24,YEAR=DAY*365.25;function parse(e){var t,v=e.toLowerCase().match(RGX);if(v!=null&&(t=parseFloat(v[1])))return v[3]!=null?t*SEC:v[4]!=null?t*MIN:v[5]!=null?t*HOUR:v[6]!=null?t*DAY:v[7]!=null?t*DAY*7:v[8]!=null?t*YEAR:t}const textEncoder=new TextEncoder;function toUint8Array(e){if(typeof e=="string")return textEncoder.encode(e);if(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(Array.isArray(e))return Uint8Array.from(e);const t=typeof e[Symbol.toPrimitive]=="function"?e[Symbol.toPrimitive]("string"):e.valueOf();return textEncoder.encode(String(t))}function safeEqual(e,t){if(typeof e=="string"&&typeof t=="string"){const x=textEncoder.encode(e),C=textEncoder.encode(t),D=x.length,Y=new Uint8Array(D);Y.set(x.subarray(0,D));const L=new Uint8Array(D);L.set(C.subarray(0,D));let q=0;for(let N=0;N<D;N++)q|=Y[N]^L[N];return q===0&&C.length===D}const v=toUint8Array(e),w=toUint8Array(t);if(v.length!==w.length)return!1;let T=0;for(const[x,C]of v.entries())T|=C^w[x];return T===0}const base64=new Base64,getRandomString=e=>{const t=(e+1)*6,v=cryptoBrowserifyExports.randomBytes(Math.ceil(t/8));return Buffer$C.from(v.buffer).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"").slice(0,e)};function safeParse(e,t){return parse_1(e,t,{protoAction:"remove",constructorAction:"remove"})}const stringify=configure({bigint:!1,circularValue:void 0,deterministic:!1});function jsonStringifyReplacer(e){return function(t,v){const w=e?e.call(this,t,v):v;return typeof w=="bigint"?w.toString():w}}function safeStringify(e,t,v){return stringify(e,jsonStringifyReplacer(t),v)}const parseMs=e=>{if(typeof e=="number")return e;const t=parse(e);if(t===void 0)throw new Error(`Invalid duration expression "${e}"`);return t},json={safeParse,safeStringify};var Ir,Hr,Kr;class MessageBuilder{constructor(){ir(this,Ir)}build(t,v,w){const T=Dr(this,Ir,Hr).call(this,v);return json.safeStringify({message:t,purpose:w,expiryDate:T})}verify(t,v){const w=json.safeParse(t);return typeof w!="object"||!w||!w.message||w.purpose!==v||Dr(this,Ir,Kr).call(this,w)?null:w.message}}Ir=new WeakSet,Hr=function(e){if(!e)return;const t=parseMs(e);return new Date(Date.now()+t)},Kr=function(e){if(!e.expiryDate)return!1;const t=new Date(e.expiryDate);return Number.isNaN(t.getTime())||t<new Date};var Cr;class Hmac{constructor(t){ir(this,Cr),Br(this,Cr,t)}generate(t){return base64.urlEncode(cryptoBrowserifyExports.createHmac("sha256",Uint8Array.from(tr(this,Cr))).update(t).digest())}compare(t,v){return safeEqual(this.generate(t),v)}}Cr=new WeakMap;var Ar,Tr;class MessageVerifier{constructor(t){ir(this,Ar),ir(this,Tr,"."),Br(this,Ar,cryptoBrowserifyExports.createHash("sha256").update(t).digest())}sign(t,v,w){if(t==null)throw new I(`Cannot sign "${t}" value`);if(!kr$1(t))throw new O(t);const T=base64.urlEncode(new MessageBuilder().build(t,v,w));return`${T}${tr(this,Tr)}${new Hmac(tr(this,Ar)).generate(T)}`}unsign(t,v){if(typeof t!="string")return null;const[w,T]=t.split(tr(this,Tr));if(!w||!T)return null;const x=base64.urlDecode(w,void 0,!1);return x&&new Hmac(tr(this,Ar)).compare(w,T)?new MessageBuilder().verify(x,v):null}encodable(t){return kr$1(t)}static encodable(t){return kr$1(t)}}Ar=new WeakMap,Tr=new WeakMap;var Rr,nr,Mr,kr,Gr;const Lr=class Qa{constructor(t){ir(this,kr),ir(this,Rr),ir(this,nr),ir(this,Mr,"."),qr(this,"verifier"),qr(this,"base64",base64);const v=t.secret&&typeof t.secret=="object"&&"release"in t.secret?t.secret.release():t.secret;Br(this,Rr,{algorithm:"aes-256-cbc",...t}),Dr(this,kr,Gr).call(this,v),Br(this,nr,cryptoBrowserifyExports.createHash("sha256").update(v).digest()),this.verifier=new MessageVerifier(v)}get algorithm(){return tr(this,Rr).algorithm}encrypt(t,v,w){t=Buffer$C.from(ji(t)).toString("base64");const T=getRandomString(16),x=cryptoBrowserifyExports.createCipheriv(this.algorithm,Uint8Array.from(tr(this,nr)),T),C=new MessageBuilder().build(t,v,w),D=Buffer$C.concat([Uint8Array.from(x.update(C,"utf-8")),Uint8Array.from(x.final())]),Y=`${this.base64.urlEncode(D)}${tr(this,Mr)}${this.base64.urlEncode(T)}`;return`${Y}${tr(this,Mr)}${new Hmac(tr(this,nr)).generate(Y)}`}decrypt(t,v){if(typeof t!="string")return null;const[w,T,x]=t.split(tr(this,Mr));if(!w||!T||!x)return null;const C=this.base64.urlDecode(w,"base64");if(!C)return null;const D=this.base64.urlDecode(T);if(!D||!new Hmac(tr(this,nr)).compare(`${w}${tr(this,Mr)}${T}`,x))return null;try{const Y=cryptoBrowserifyExports.createDecipheriv(this.algorithm,Uint8Array.from(tr(this,nr)),D),L=Y.update(C,"base64","utf8")+Y.final("utf8"),q=new MessageBuilder().verify(L,v);if(!q||typeof q!="string")return null;const N=Uint8Array.from(Buffer$C.from(q,"base64"));return Ii(N)}catch{return null}}child(t){return new Qa({...tr(this,Rr),...t})}encodable(t){return kr$1(t)}static encodable(t){return kr$1(t)}};Rr=new WeakMap,nr=new WeakMap,Mr=new WeakMap,kr=new WeakSet,Gr=function(e){if(typeof e!="string")throw new A;if(e.length<16)throw new k};let Encryption=Lr;const REDACTED="[redacted]";var Pr,ar;const Fr=class eu{constructor(t,v){ir(this,Pr),ir(this,ar),Br(this,Pr,t),Br(this,ar,v||REDACTED)}toJSON(){return tr(this,ar)}valueOf(){return tr(this,ar)}toLocaleString(){return tr(this,ar)}toString(){return tr(this,ar)}release(){return tr(this,Pr)}map(t){return new eu(t(tr(this,Pr)))}};Pr=new WeakMap,ar=new WeakMap;let Secret=Fr;const getEncryption=e=>{const t=getGlobal();if(typeof t[FOR_ENCRYPTION]<"u"&&t[FOR_ENCRYPTION]instanceof Encryption)return t[FOR_ENCRYPTION];if(typeof e=="string"||e instanceof Secret)return t[FOR_ENCRYPTION]=new Encryption({secret:e}),t[FOR_ENCRYPTION];throw new errors.MissingEncryptionKey},setPSK=e=>{const t=getGlobal();if(!(typeof t[FOR_ENCRYPTION]<"u"&&t[FOR_ENCRYPTION]instanceof Encryption)&&(typeof e=="string"||e instanceof Secret)){t[FOR_ENCRYPTION]=new Encryption({secret:e});return}},logger=getLogger();var Oa,na,Ba,fa,ua,ca,oa,aa,ta,ia,la,Ia,Co,za,Ga,Va,Ka,Pa,tu,qa,ru,Za;const ra=class ra extends TypedEventEmitter{constructor(v){const w=getGlobal(),T=getEncryption(v);if(typeof w[FOR_SWARM]<"u"&&w[FOR_SWARM]instanceof ra)throw new errors.AlreadyInitializedInContextError;if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new errors.UnsupportedEnvironmentError;super();Xo(this,Co);Xo(this,Oa);Xo(this,na);Xo(this,Ba);Xo(this,fa);Xo(this,ua);Xo(this,ca);Xo(this,oa);Xo(this,aa);Xo(this,ta);Xo(this,ia);Xo(this,la);Xo(this,Ia);w[FOR_SWARM]=this,Jo(this,aa,T),Jo(this,Oa,makeRandomId(8)),Jo(this,na,new TypedEventEmitter),Jo(this,Ba,new Map),Jo(this,fa,new Map),Jo(this,ua,new Map),Jo(this,ca,new Map),Jo(this,oa,new Map),Jo(this,Ia,1e3),logger.debug(`Swarm instance initialized with ID "${fo(this,Oa)}"`),Jo(this,la,!1),Jo(this,ta,new BroadcastChannel$1("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{logger.WARNING("Swarm channel closed, reinitializing..."),fo(this,ta).close(),Oo(this,Co,za).call(this,!0)}}})),Jo(this,ia,createLeaderElection(fo(this,ta))),Oo(this,Co,Ka).call(this),Oo(this,Co,Ga).call(this),logger.debug("Swarm instance is ready"),Oo(this,Co,ru).call(this),isTabEnvironment()&&w.addEventListener("beforeunload",()=>{Oo(this,Co,qa).call(this,ra.INTERNAL_OBITUARY,fo(this,Oa))})}get id(){return fo(this,Oa)}get leader(){return fo(this,la)}emit(v,...w){const T={id:makeRandomId(16),event:v,args:w,needsAck:!1,isAck:!1},x=fo(this,aa).encrypt(T);return fo(this,ta).postMessage(x).catch(C=>{logger.error("Got error while sending message",C)}),super.emit(v,...w),this}onLeadershipChange(v){return fo(this,na).on("leadership",v),this}offLeadershipChange(v){return fo(this,na).off("leadership",v),this}onceLeadershipChange(v){return fo(this,na).once("leadership",v),this}collect(v,...w){const T=makeRandomId(16),x=fo(this,ca).get(v),C={responses:[],timer:null,resolve:L=>{}},D=new Promise(L=>{C.resolve=L,C.timer=setTimeout(()=>{fo(this,ua).delete(T),L(C.responses)},fo(this,Ia))});fo(this,ua).set(T,C),x&&Promise.resolve(x(...w)).then(L=>{C.responses.push(L),Oo(this,Co,Za).call(this,T)});const Y={id:T,event:v,args:w,needsCollect:!0};return fo(this,ta).postMessage(fo(this,aa).encrypt(Y)).catch(L=>logger.error(L)),D}onCollect(v,w){return fo(this,ca).set(v,w),this}offCollect(v){return fo(this,ca).delete(v),this}request(v,...w){const T=makeRandomId(16),x={id:T,event:v,args:w,needsAck:!0},C=fo(this,aa).encrypt(x);return fo(this,ta).postMessage(C).catch(D=>{logger.error("Error sending request:",D)}),new Promise((D,Y)=>{const L=setTimeout(()=>{fo(this,fa).delete(T),Y(new errors.RequestTimeoutError(v))},fo(this,Ia));fo(this,fa).set(T,{resolve:D,reject:Y,timer:L})})}onRequest(v,w){return fo(this,Ba).set(v,w),this}offRequest(v){return fo(this,Ba).delete(v),this}setAwaitResponseTimeout(v){return Jo(this,Ia,v),this}static instance(v){const w=getGlobal();return typeof w[FOR_SWARM]<"u"&&w[FOR_SWARM]instanceof ra?w[FOR_SWARM]:new ra(v)}};Oa=new WeakMap,na=new WeakMap,Ba=new WeakMap,fa=new WeakMap,ua=new WeakMap,ca=new WeakMap,oa=new WeakMap,aa=new WeakMap,ta=new WeakMap,ia=new WeakMap,la=new WeakMap,Ia=new WeakMap,Co=new WeakSet,za=function(v=!1){fo(this,ta)&&!v||(Jo(this,ta,new BroadcastChannel$1("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{fo(this,ta).close(),Oo(this,Co,za).call(this,!0)}}})),Jo(this,ia,createLeaderElection(fo(this,ta))),Oo(this,Co,Ga).call(this))},Ga=function(){logger.debug("Hooking swarm channel events"),fo(this,ta).onmessage=v=>Oo(this,Co,tu).call(this,v),logger.debug("Swarm channel events hooked")},Va=function(v){fo(this,la)!==v&&(Jo(this,la,v),fo(this,na).emit("leadership",v),logger.debug(`Swarm instance is now ${v?"the":"not the"} leader`))},Ka=function(){new Promise(async v=>{await fo(this,ia).hasLeader()||(logger.debug("No leader found, trying to elect one"),await fo(this,ia).awaitLeadership(),logger.debug("Leader elected"),Oo(this,Co,Va).call(this,fo(this,ia).isLeader)),v(void 0)}).catch(v=>{logger.error("Got error while checking for leader",v)}).finally(()=>{setTimeout(()=>Oo(this,Co,Ka).call(this),500)})},Pa=function(v){fo(this,ta).postMessage(fo(this,aa).encrypt({id:makeRandomId(16),...v})).catch(w=>logger.error(w))},tu=function(v){const w=fo(this,aa).decrypt(v);if(typeof w!="object"||w===null||typeof w.event!="string"&&typeof w.event!="number"||!Array.isArray(w.args))return;const{id:T,event:x,args:C,needsAck:D,isAck:Y,needsCollect:L,isCollectResponse:q,replyTo:N,result:F,error:ae}=w;if(x===ra.INTERNAL_HEARTBEAT){const[he]=C,tt=!fo(this,oa).has(he);fo(this,oa).set(he,Date.now()),fo(this,na).emit(tt?"peerJoined":"peerHeartbeat",he);return}if(x===ra.INTERNAL_OBITUARY){const[he]=C;fo(this,oa).delete(he)&&fo(this,na).emit("peerLeft",he);return}if(Y&&N){const he=fo(this,fa).get(N);he&&(clearTimeout(he.timer),fo(this,fa).delete(N),typeof ae=="string"?he.reject(new Error(String(ae))):he.resolve(F));return}if(D){fo(this,ia).hasLeader().then(async he=>{if(he||(await fo(this,ia).awaitLeadership(),Oo(this,Co,Va).call(this,fo(this,ia).isLeader)),fo(this,la)){const tt=fo(this,Ba).get(x);tt&&Promise.resolve(tt(...C)).then(br=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isAck:!0,replyTo:T,result:br})}).catch(br=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isAck:!0,replyTo:T,error:br.message})})}});return}if(q&&N){const he=fo(this,ua).get(N);he&&(he.responses.push(F),Oo(this,Co,Za).call(this,N));return}if(L){const he=fo(this,ca).get(x);he&&Promise.resolve(he(...C)).then(tt=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isCollectResponse:!0,replyTo:T,result:tt})}).catch(tt=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isCollectResponse:!0,replyTo:T,error:tt.message})});return}Ja(ra.prototype,this,"emit").call(this,x,...C)},qa=function(v,...w){const T={id:makeRandomId(16),event:v,args:w};fo(this,ta).postMessage(fo(this,aa).encrypt(T)).catch(x=>logger.error(x))},ru=function(){Oo(this,Co,qa).call(this,ra.INTERNAL_HEARTBEAT,this.id),setInterval(()=>{Oo(this,Co,qa).call(this,ra.INTERNAL_HEARTBEAT,this.id)},2e3),setInterval(()=>{const v=Date.now();for(const[w,T]of fo(this,oa))v-T>6e3&&(fo(this,oa).delete(w),fo(this,na).emit("peerLeft",w))},2e3)},Za=function(v){const w=fo(this,ua).get(v);if(!w)return;const T=fo(this,oa).size+1;w.responses.length>=T&&(clearTimeout(w.timer),setTimeout(()=>{fo(this,ua).delete(v)&&w.resolve(w.responses)},100))},Ta(ra,"INTERNAL_HEARTBEAT","__swarm_heartbeat"),Ta(ra,"INTERNAL_OBITUARY","__swarm_obituary");let Swarm=ra;const version="1.20250425.0";exports.types=types$1.types;exports.errors=errors.errors;exports.Secret=Secret;exports.Swarm=Swarm;exports.setLogLevel=setLogLevel;exports.setPSK=setPSK;exports.version=version;
48
+ ${xi}`),Mi.pop(),`{${Yi}}`}case"number":return isFinite(Oi)?String(Oi):_r?_r(Oi):"null";case"boolean":return Oi===!0?"true":"false";case"undefined":return;case"bigint":if(qi)return String(Oi);default:return _r?_r(Oi):void 0}}function z(vr,Oi,Mi){switch(typeof Oi){case"string":return x(Oi);case"object":{if(Oi===null)return"null";if(typeof Oi.toJSON=="function"){if(Oi=Oi.toJSON(vr),typeof Oi!="object")return z(vr,Oi,Mi);if(Oi===null)return"null"}if(Mi.indexOf(Oi)!==-1)return Bi;let ki="";const yr=Oi.length!==void 0;if(yr&&Array.isArray(Oi)){if(Oi.length===0)return"[]";if(Ti<Mi.length+1)return'"[Array]"';Mi.push(Oi);const Yi=Math.min(Oi.length,Li);let Qi=0;for(;Qi<Yi-1;Qi++){const Ni=z(String(Qi),Oi[Qi],Mi);ki+=Ni!==void 0?Ni:"null",ki+=","}const Zi=z(String(Qi),Oi[Qi],Mi);if(ki+=Zi!==void 0?Zi:"null",Oi.length-1>Li){const Ni=Oi.length-Li-1;ki+=`,"... ${he(Ni)} not stringified"`}return Mi.pop(),`[${ki}]`}let xi=Object.keys(Oi);const Si=xi.length;if(Si===0)return"{}";if(Ti<Mi.length+1)return'"[Object]"';let Ci="",Ki=Math.min(Si,Li);yr&&Y(Oi)&&(ki+=L(Oi,",",Li),xi=xi.slice(Oi.length),Ki-=Oi.length,Ci=","),Wi&&(xi=C(xi,Vi)),Mi.push(Oi);for(let Yi=0;Yi<Ki;Yi++){const Qi=xi[Yi],Zi=z(Qi,Oi[Qi],Mi);Zi!==void 0&&(ki+=`${Ci}${x(Qi)}:${Zi}`,Ci=",")}if(Si>Li){const Yi=Si-Li;ki+=`${Ci}"...":"${he(Yi)} not stringified"`}return Mi.pop(),`{${ki}}`}case"number":return isFinite(Oi)?String(Oi):_r?_r(Oi):"null";case"boolean":return Oi===!0?"true":"false";case"undefined":return;case"bigint":if(qi)return String(Oi);default:return _r?_r(Oi):void 0}}function gr(vr,Oi,Mi){if(arguments.length>1){let ki="";if(typeof Mi=="number"?ki=" ".repeat(Math.min(Mi,10)):typeof Mi=="string"&&(ki=Mi.slice(0,10)),Oi!=null){if(typeof Oi=="function")return Hi("",{"":vr},[],Oi,ki,"");if(Array.isArray(Oi))return pr("",vr,[],tt(Oi),ki,"")}if(ki.length!==0)return Di("",vr,[],ki,"")}return z("",vr,[])}return gr}})(safeStableStringify,safeStableStringify.exports);var safeStableStringifyExports=safeStableStringify.exports;const cjsModule=getDefaultExportFromCjs$1(safeStableStringifyExports),configure=cjsModule.configure;var RGX=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,SEC=1e3,MIN=SEC*60,HOUR=MIN*60,DAY=HOUR*24,YEAR=DAY*365.25;function parse(e){var t,v=e.toLowerCase().match(RGX);if(v!=null&&(t=parseFloat(v[1])))return v[3]!=null?t*SEC:v[4]!=null?t*MIN:v[5]!=null?t*HOUR:v[6]!=null?t*DAY:v[7]!=null?t*DAY*7:v[8]!=null?t*YEAR:t}const textEncoder=new TextEncoder;function toUint8Array(e){if(typeof e=="string")return textEncoder.encode(e);if(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(Array.isArray(e))return Uint8Array.from(e);const t=typeof e[Symbol.toPrimitive]=="function"?e[Symbol.toPrimitive]("string"):e.valueOf();return textEncoder.encode(String(t))}function safeEqual(e,t){if(typeof e=="string"&&typeof t=="string"){const x=textEncoder.encode(e),C=textEncoder.encode(t),D=x.length,Y=new Uint8Array(D);Y.set(x.subarray(0,D));const L=new Uint8Array(D);L.set(C.subarray(0,D));let q=0;for(let N=0;N<D;N++)q|=Y[N]^L[N];return q===0&&C.length===D}const v=toUint8Array(e),w=toUint8Array(t);if(v.length!==w.length)return!1;let T=0;for(const[x,C]of v.entries())T|=C^w[x];return T===0}const base64=new Base64,getRandomString=e=>{const t=(e+1)*6,v=cryptoBrowserifyExports.randomBytes(Math.ceil(t/8));return Buffer$C.from(v.buffer).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"").slice(0,e)};function safeParse(e,t){return parse_1(e,t,{protoAction:"remove",constructorAction:"remove"})}const stringify=configure({bigint:!1,circularValue:void 0,deterministic:!1});function jsonStringifyReplacer(e){return function(t,v){const w=e?e.call(this,t,v):v;return typeof w=="bigint"?w.toString():w}}function safeStringify(e,t,v){return stringify(e,jsonStringifyReplacer(t),v)}const parseMs=e=>{if(typeof e=="number")return e;const t=parse(e);if(t===void 0)throw new Error(`Invalid duration expression "${e}"`);return t},json={safeParse,safeStringify};var Ir,Hr,Kr;class MessageBuilder{constructor(){ir(this,Ir)}build(t,v,w){const T=Dr(this,Ir,Hr).call(this,v);return json.safeStringify({message:t,purpose:w,expiryDate:T})}verify(t,v){const w=json.safeParse(t);return typeof w!="object"||!w||!w.message||w.purpose!==v||Dr(this,Ir,Kr).call(this,w)?null:w.message}}Ir=new WeakSet,Hr=function(e){if(!e)return;const t=parseMs(e);return new Date(Date.now()+t)},Kr=function(e){if(!e.expiryDate)return!1;const t=new Date(e.expiryDate);return Number.isNaN(t.getTime())||t<new Date};var Cr;class Hmac{constructor(t){ir(this,Cr),Br(this,Cr,t)}generate(t){return base64.urlEncode(cryptoBrowserifyExports.createHmac("sha256",Uint8Array.from(tr(this,Cr))).update(t).digest())}compare(t,v){return safeEqual(this.generate(t),v)}}Cr=new WeakMap;var Ar,Tr;class MessageVerifier{constructor(t){ir(this,Ar),ir(this,Tr,"."),Br(this,Ar,cryptoBrowserifyExports.createHash("sha256").update(t).digest())}sign(t,v,w){if(t==null)throw new I(`Cannot sign "${t}" value`);if(!kr$1(t))throw new O(t);const T=base64.urlEncode(new MessageBuilder().build(t,v,w));return`${T}${tr(this,Tr)}${new Hmac(tr(this,Ar)).generate(T)}`}unsign(t,v){if(typeof t!="string")return null;const[w,T]=t.split(tr(this,Tr));if(!w||!T)return null;const x=base64.urlDecode(w,void 0,!1);return x&&new Hmac(tr(this,Ar)).compare(w,T)?new MessageBuilder().verify(x,v):null}encodable(t){return kr$1(t)}static encodable(t){return kr$1(t)}}Ar=new WeakMap,Tr=new WeakMap;var Rr,nr,Mr,kr,Gr;const Lr=class Qa{constructor(t){ir(this,kr),ir(this,Rr),ir(this,nr),ir(this,Mr,"."),qr(this,"verifier"),qr(this,"base64",base64);const v=t.secret&&typeof t.secret=="object"&&"release"in t.secret?t.secret.release():t.secret;Br(this,Rr,{algorithm:"aes-256-cbc",...t}),Dr(this,kr,Gr).call(this,v),Br(this,nr,cryptoBrowserifyExports.createHash("sha256").update(v).digest()),this.verifier=new MessageVerifier(v)}get algorithm(){return tr(this,Rr).algorithm}encrypt(t,v,w){t=Buffer$C.from(ji(t)).toString("base64");const T=getRandomString(16),x=cryptoBrowserifyExports.createCipheriv(this.algorithm,Uint8Array.from(tr(this,nr)),T),C=new MessageBuilder().build(t,v,w),D=Buffer$C.concat([Uint8Array.from(x.update(C,"utf-8")),Uint8Array.from(x.final())]),Y=`${this.base64.urlEncode(D)}${tr(this,Mr)}${this.base64.urlEncode(T)}`;return`${Y}${tr(this,Mr)}${new Hmac(tr(this,nr)).generate(Y)}`}decrypt(t,v){if(typeof t!="string")return null;const[w,T,x]=t.split(tr(this,Mr));if(!w||!T||!x)return null;const C=this.base64.urlDecode(w,"base64");if(!C)return null;const D=this.base64.urlDecode(T);if(!D||!new Hmac(tr(this,nr)).compare(`${w}${tr(this,Mr)}${T}`,x))return null;try{const Y=cryptoBrowserifyExports.createDecipheriv(this.algorithm,Uint8Array.from(tr(this,nr)),D),L=Y.update(C,"base64","utf8")+Y.final("utf8"),q=new MessageBuilder().verify(L,v);if(!q||typeof q!="string")return null;const N=Uint8Array.from(Buffer$C.from(q,"base64"));return Ii(N)}catch{return null}}child(t){return new Qa({...tr(this,Rr),...t})}encodable(t){return kr$1(t)}static encodable(t){return kr$1(t)}};Rr=new WeakMap,nr=new WeakMap,Mr=new WeakMap,kr=new WeakSet,Gr=function(e){if(typeof e!="string")throw new A;if(e.length<16)throw new k};let Encryption=Lr;const REDACTED="[redacted]";var Pr,ar;const Fr=class eu{constructor(t,v){ir(this,Pr),ir(this,ar),Br(this,Pr,t),Br(this,ar,v||REDACTED)}toJSON(){return tr(this,ar)}valueOf(){return tr(this,ar)}toLocaleString(){return tr(this,ar)}toString(){return tr(this,ar)}release(){return tr(this,Pr)}map(t){return new eu(t(tr(this,Pr)))}};Pr=new WeakMap,ar=new WeakMap;let Secret=Fr;const getEncryption=e=>{const t=getGlobal();if(typeof t[FOR_ENCRYPTION]<"u"&&t[FOR_ENCRYPTION]instanceof Encryption)return t[FOR_ENCRYPTION];if(typeof e=="string"||e instanceof Secret)return t[FOR_ENCRYPTION]=new Encryption({secret:e}),t[FOR_ENCRYPTION];throw new errors.MissingEncryptionKey},setPSK=e=>{const t=getGlobal();if(!(typeof t[FOR_ENCRYPTION]<"u"&&t[FOR_ENCRYPTION]instanceof Encryption)&&(typeof e=="string"||e instanceof Secret)){t[FOR_ENCRYPTION]=new Encryption({secret:e});return}},logger=getLogger();var Oa,na,Ba,fa,ua,ca,oa,aa,ta,ia,la,Ia,Co,za,Ga,Va,Ka,Pa,tu,qa,ru,Za;const ra=class ra extends TypedEventEmitter{constructor(v){const w=getGlobal(),T=getEncryption(v);if(typeof w[FOR_SWARM]<"u"&&w[FOR_SWARM]instanceof ra)throw new errors.AlreadyInitializedInContextError;if(isSsrEnvironment()||!isTabEnvironment()&&!isWorkerEnvironment()&&!isWebWorkerEnvironment())throw new errors.UnsupportedEnvironmentError;super();Xo(this,Co);Xo(this,Oa);Xo(this,na);Xo(this,Ba);Xo(this,fa);Xo(this,ua);Xo(this,ca);Xo(this,oa);Xo(this,aa);Xo(this,ta);Xo(this,ia);Xo(this,la);Xo(this,Ia);w[FOR_SWARM]=this,Jo(this,aa,T),Jo(this,Oa,makeRandomId(8)),Jo(this,na,new TypedEventEmitter),Jo(this,Ba,new Map),Jo(this,fa,new Map),Jo(this,ua,new Map),Jo(this,ca,new Map),Jo(this,oa,new Map),Jo(this,Ia,1e3),logger.debug(`Swarm instance initialized with ID "${fo(this,Oa)}"`),Jo(this,la,!1),Jo(this,ta,new BroadcastChannel$1("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{logger.WARNING("Swarm channel closed, reinitializing..."),fo(this,ta).close(),Oo(this,Co,za).call(this,!0)}}})),Jo(this,ia,createLeaderElection(fo(this,ta))),Oo(this,Co,Ka).call(this),Oo(this,Co,Ga).call(this),logger.debug("Swarm instance is ready"),Oo(this,Co,ru).call(this),isTabEnvironment()&&w.addEventListener("beforeunload",()=>{Oo(this,Co,qa).call(this,ra.INTERNAL_OBITUARY,fo(this,Oa))})}get id(){return fo(this,Oa)}get leader(){return fo(this,la)}emit(v,...w){const T={id:makeRandomId(16),event:v,args:w,needsAck:!1,isAck:!1},x=fo(this,aa).encrypt(T);return fo(this,ta).postMessage(x).catch(C=>{logger.error("Got error while sending message",C)}),super.emit(v,...w),this}onLeadershipChange(v){return fo(this,na).on("leadership",v),this}offLeadershipChange(v){return fo(this,na).off("leadership",v),this}onceLeadershipChange(v){return fo(this,na).once("leadership",v),this}collect(v,...w){const T=makeRandomId(16),x=fo(this,ca).get(v),C={responses:[],timer:null,resolve:L=>{}},D=new Promise(L=>{C.resolve=L,C.timer=setTimeout(()=>{fo(this,ua).delete(T),L(C.responses)},fo(this,Ia))});fo(this,ua).set(T,C),x&&Promise.resolve(x(...w)).then(L=>{C.responses.push(L),Oo(this,Co,Za).call(this,T)});const Y={id:T,event:v,args:w,needsCollect:!0};return fo(this,ta).postMessage(fo(this,aa).encrypt(Y)).catch(L=>logger.error(L)),D}onCollect(v,w){return fo(this,ca).set(v,w),this}offCollect(v){return fo(this,ca).delete(v),this}request(v,...w){const T=makeRandomId(16),x={id:T,event:v,args:w,needsAck:!0},C=fo(this,aa).encrypt(x);return fo(this,ta).postMessage(C).catch(D=>{logger.error("Error sending request:",D)}),new Promise((D,Y)=>{const L=setTimeout(()=>{fo(this,fa).delete(T),Y(new errors.RequestTimeoutError(v))},fo(this,Ia));fo(this,fa).set(T,{resolve:D,reject:Y,timer:L})})}onRequest(v,w){return fo(this,Ba).set(v,w),this}offRequest(v){return fo(this,Ba).delete(v),this}setAwaitResponseTimeout(v){return Jo(this,Ia,v),this}static instance(v){const w=getGlobal();return typeof w[FOR_SWARM]<"u"&&w[FOR_SWARM]instanceof ra?w[FOR_SWARM]:new ra(v)}};Oa=new WeakMap,na=new WeakMap,Ba=new WeakMap,fa=new WeakMap,ua=new WeakMap,ca=new WeakMap,oa=new WeakMap,aa=new WeakMap,ta=new WeakMap,ia=new WeakMap,la=new WeakMap,Ia=new WeakMap,Co=new WeakSet,za=function(v=!1){fo(this,ta)&&!v||(Jo(this,ta,new BroadcastChannel$1("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{fo(this,ta).close(),Oo(this,Co,za).call(this,!0)}}})),Jo(this,ia,createLeaderElection(fo(this,ta))),Oo(this,Co,Ga).call(this))},Ga=function(){logger.debug("Hooking swarm channel events"),fo(this,ta).onmessage=v=>Oo(this,Co,tu).call(this,v),logger.debug("Swarm channel events hooked")},Va=function(v){fo(this,la)!==v&&(Jo(this,la,v),fo(this,na).emit("leadership",v),logger.debug(`Swarm instance is now ${v?"the":"not the"} leader`))},Ka=function(){new Promise(async v=>{await fo(this,ia).hasLeader()||(logger.debug("No leader found, trying to elect one"),await fo(this,ia).awaitLeadership(),logger.debug("Leader elected"),Oo(this,Co,Va).call(this,fo(this,ia).isLeader)),v(void 0)}).catch(v=>{logger.error("Got error while checking for leader",v)}).finally(()=>{setTimeout(()=>Oo(this,Co,Ka).call(this),500)})},Pa=function(v){fo(this,ta).postMessage(fo(this,aa).encrypt({id:makeRandomId(16),...v})).catch(w=>logger.error(w))},tu=function(v){const w=fo(this,aa).decrypt(v);if(typeof w!="object"||w===null||typeof w.event!="string"&&typeof w.event!="number"||!Array.isArray(w.args))return;const{id:T,event:x,args:C,needsAck:D,isAck:Y,needsCollect:L,isCollectResponse:q,replyTo:N,result:F,error:ae}=w;if(x===ra.INTERNAL_HEARTBEAT){const[he]=C,tt=!fo(this,oa).has(he);fo(this,oa).set(he,Date.now()),fo(this,na).emit(tt?"peerJoined":"peerHeartbeat",he);return}if(x===ra.INTERNAL_OBITUARY){const[he]=C;fo(this,oa).delete(he)&&fo(this,na).emit("peerLeft",he);return}if(Y&&N){const he=fo(this,fa).get(N);he&&(clearTimeout(he.timer),fo(this,fa).delete(N),typeof ae=="string"?he.reject(new Error(String(ae))):he.resolve(F));return}if(D){fo(this,ia).hasLeader().then(async he=>{if(he||(await fo(this,ia).awaitLeadership(),Oo(this,Co,Va).call(this,fo(this,ia).isLeader)),fo(this,la)){const tt=fo(this,Ba).get(x);tt&&Promise.resolve(tt(...C)).then(br=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isAck:!0,replyTo:T,result:br})}).catch(br=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isAck:!0,replyTo:T,error:br.message})})}});return}if(q&&N){const he=fo(this,ua).get(N);he&&(he.responses.push(F),Oo(this,Co,Za).call(this,N));return}if(L){const he=fo(this,ca).get(x);he&&Promise.resolve(he(...C)).then(tt=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isCollectResponse:!0,replyTo:T,result:tt})}).catch(tt=>{Oo(this,Co,Pa).call(this,{event:x,args:[],isCollectResponse:!0,replyTo:T,error:tt.message})});return}Ja(ra.prototype,this,"emit").call(this,x,...C)},qa=function(v,...w){const T={id:makeRandomId(16),event:v,args:w};fo(this,ta).postMessage(fo(this,aa).encrypt(T)).catch(x=>logger.error(x))},ru=function(){Oo(this,Co,qa).call(this,ra.INTERNAL_HEARTBEAT,this.id),setInterval(()=>{Oo(this,Co,qa).call(this,ra.INTERNAL_HEARTBEAT,this.id)},2e3),setInterval(()=>{const v=Date.now();for(const[w,T]of fo(this,oa))v-T>6e3&&(fo(this,oa).delete(w),fo(this,na).emit("peerLeft",w))},2e3)},Za=function(v){const w=fo(this,ua).get(v);if(!w)return;const T=fo(this,oa).size+1;w.responses.length>=T&&(clearTimeout(w.timer),setTimeout(()=>{fo(this,ua).delete(v)&&w.resolve(w.responses)},100))},Ta(ra,"INTERNAL_HEARTBEAT","__swarm_heartbeat"),Ta(ra,"INTERNAL_OBITUARY","__swarm_obituary");let Swarm=ra;const version="1.20251110.0";exports.types=types$1.types;exports.errors=errors.errors;exports.Secret=Secret;exports.Swarm=Swarm;exports.setLogLevel=setLogLevel;exports.setPSK=setPSK;exports.version=version;
49
49
  //# sourceMappingURL=index.cjs.map