@nhtio/swarm 1.20250424.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/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2025 New Horizon Technology LTD (nht.io)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @nhtio/swarm
2
+
3
+ A library that provides peer communication between browser tabs and service workers
4
+
5
+ For more information, see the [official documentation](https://swarm.nht.io)
@@ -0,0 +1,82 @@
1
+ var u = Object.defineProperty;
2
+ var m = (r, e, t) => e in r ? u(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
+ var o = (r, e, t) => m(r, typeof e != "symbol" ? e + "" : e, t);
4
+ class i extends Error {
5
+ /**
6
+ * Creates a new SwarmError instance.
7
+ * @param message The error message.
8
+ * @param options The error options.
9
+ */
10
+ constructor(t, s) {
11
+ const c = s ? { cause: s.cause } : {};
12
+ super(t, c);
13
+ /** @private */
14
+ o(this, "$__name");
15
+ /** @private */
16
+ o(this, "$__message");
17
+ const n = this.constructor;
18
+ if (Object.setPrototypeOf(this, n), this.$__name = n.name, this.$__message = t, typeof Error.captureStackTrace == "function" && Error.captureStackTrace(this, n), this.stack && s && s.trim && s.trim > 0) {
19
+ const a = this.stack.split(`
20
+ `);
21
+ a.splice(0, s.trim), this.stack = a.join(`
22
+ `);
23
+ }
24
+ }
25
+ get name() {
26
+ return this.$__name;
27
+ }
28
+ get message() {
29
+ return this.$__message;
30
+ }
31
+ get [Symbol.toStringTag]() {
32
+ return this.constructor.name;
33
+ }
34
+ toString() {
35
+ return `${this.name}: ${this.message}`;
36
+ }
37
+ [Symbol.toPrimitive](t) {
38
+ switch (t) {
39
+ case "string":
40
+ return this.toString();
41
+ default:
42
+ return !0;
43
+ }
44
+ }
45
+ static [Symbol.hasInstance](t) {
46
+ if (typeof t == "object" && t !== null || typeof t == "function") {
47
+ const s = Object.getPrototypeOf(t);
48
+ return s.name === this.name || s === this;
49
+ }
50
+ return !1;
51
+ }
52
+ }
53
+ class l extends i {
54
+ constructor() {
55
+ super("Unable to setup instance because Service Workers are not supported in this environment");
56
+ }
57
+ }
58
+ class h extends i {
59
+ constructor() {
60
+ super(
61
+ "Unable to setup instance because another instance is already initialized in this context"
62
+ );
63
+ }
64
+ }
65
+ class p extends i {
66
+ constructor(e) {
67
+ super(`Request timed out while waiting for event "${String(e)}".`);
68
+ }
69
+ }
70
+ const _ = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
71
+ __proto__: null,
72
+ AlreadyInitializedInContextError: h,
73
+ RequestTimeoutError: p,
74
+ UnsupportedEnvironmentError: l
75
+ }, Symbol.toStringTag, { value: "Module" }));
76
+ export {
77
+ h as A,
78
+ p as R,
79
+ l as U,
80
+ _ as e
81
+ };
82
+ //# sourceMappingURL=errors-BsRN4TW4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-BsRN4TW4.mjs","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Easily accessible error classes for Swarm\n * @module @nhtio/swarm/errors\n */\n\n/**\n * Describes the options for the SwarmError class.\n */\nexport interface SwarmErrorOptions {\n /**\n * The cause data property of an Error instance indicates the specific original cause of the error.\n */\n cause?: Error\n /**\n * How many rows to trim from the stack trace.\n * This is useful for removing the stack trace of the current function from the error.\n */\n trim?: number\n}\n\n/**\n * Base class for all Swarm errors.\n * @extends Error\n */\nclass SwarmError extends Error {\n /** @private */\n readonly $__name: string\n /** @private */\n readonly $__message: string\n\n /**\n * Creates a new SwarmError instance.\n * @param message The error message.\n * @param options The error options.\n */\n constructor(message: string, options?: SwarmErrorOptions) {\n const superOptions = options ? { cause: options.cause } : {}\n super(message, superOptions)\n const ErrorConstructor = this.constructor\n Object.setPrototypeOf(this, ErrorConstructor)\n this.$__name = ErrorConstructor.name\n this.$__message = message\n if ('function' === typeof Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorConstructor)\n }\n if (this.stack && options && options.trim && options.trim > 0) {\n const stackLines = this.stack.split('\\n')\n stackLines.splice(0, options.trim)\n this.stack = stackLines.join('\\n')\n }\n }\n\n get name() {\n return this.$__name\n }\n\n get message() {\n return this.$__message\n }\n\n get [Symbol.toStringTag]() {\n return this.constructor.name\n }\n\n toString() {\n return `${this.name}: ${this.message}`\n }\n\n [Symbol.toPrimitive](hint: 'number' | 'string' | 'default') {\n switch (hint) {\n case 'string':\n return this.toString()\n default:\n return true\n }\n }\n\n static [Symbol.hasInstance](instance: unknown) {\n if ((typeof instance === 'object' && instance !== null) || typeof instance === 'function') {\n const proto = Object.getPrototypeOf(instance)\n return proto.name === this.name || proto === this\n }\n return false\n }\n}\n\nexport type { SwarmError }\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialized in an environment that does not support Service Workers.\n */\nexport class UnsupportedEnvironmentError extends SwarmError {\n constructor() {\n super('Unable to setup instance because Service Workers are not supported in this environment')\n }\n}\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialize more than one instance within the same context.\n */\nexport class AlreadyInitializedInContextError extends SwarmError {\n constructor() {\n super(\n 'Unable to setup instance because another instance is already initialized in this context'\n )\n }\n}\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when a request to the leader is not answered.\n */\nexport class RequestTimeoutError extends SwarmError {\n constructor(event: string | number | symbol) {\n super(`Request timed out while waiting for event \"${String(event)}\".`)\n }\n}\n"],"names":["SwarmError","message","options","superOptions","__publicField","ErrorConstructor","stackLines","hint","instance","proto","UnsupportedEnvironmentError","AlreadyInitializedInContextError","RequestTimeoutError","event"],"mappings":";;;AAwBA,MAAMA,UAAmB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW7B,YAAYC,GAAiBC,GAA6B;AACxD,UAAMC,IAAeD,IAAU,EAAE,OAAOA,EAAQ,UAAU;AAC1D,UAAMD,GAASE,CAAY;AAXpB;AAAA,IAAAC,EAAA;AAEA;AAAA,IAAAA,EAAA;AAUP,UAAMC,IAAmB,KAAK;AAO9B,QANO,OAAA,eAAe,MAAMA,CAAgB,GAC5C,KAAK,UAAUA,EAAiB,MAChC,KAAK,aAAaJ,GACC,OAAO,MAAM,qBAA5B,cACI,MAAA,kBAAkB,MAAMI,CAAgB,GAE5C,KAAK,SAASH,KAAWA,EAAQ,QAAQA,EAAQ,OAAO,GAAG;AAC7D,YAAMI,IAAa,KAAK,MAAM,MAAM;AAAA,CAAI;AAC7B,MAAAA,EAAA,OAAO,GAAGJ,EAAQ,IAAI,GAC5B,KAAA,QAAQI,EAAW,KAAK;AAAA,CAAI;AAAA,IACnC;AAAA,EACF;AAAA,EAEA,IAAI,OAAO;AACT,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,KAAK,OAAO,WAAW,IAAI;AACzB,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA,EAEA,WAAW;AACT,WAAO,GAAG,KAAK,IAAI,KAAK,KAAK,OAAO;AAAA,EACtC;AAAA,EAEA,CAAC,OAAO,WAAW,EAAEC,GAAuC;AAC1D,YAAQA,GAAM;AAAA,MACZ,KAAK;AACH,eAAO,KAAK;MACd;AACS,eAAA;AAAA,IACX;AAAA,EACF;AAAA,EAEA,QAAQ,OAAO,WAAW,EAAEC,GAAmB;AAC7C,QAAK,OAAOA,KAAa,YAAYA,MAAa,QAAS,OAAOA,KAAa,YAAY;AACnF,YAAAC,IAAQ,OAAO,eAAeD,CAAQ;AAC5C,aAAOC,EAAM,SAAS,KAAK,QAAQA,MAAU;AAAA,IAC/C;AACO,WAAA;AAAA,EACT;AACF;AAOO,MAAMC,UAAoCV,EAAW;AAAA,EAC1D,cAAc;AACZ,UAAM,wFAAwF;AAAA,EAChG;AACF;AAKO,MAAMW,UAAyCX,EAAW;AAAA,EAC/D,cAAc;AACZ;AAAA,MACE;AAAA,IAAA;AAAA,EAEJ;AACF;AAKO,MAAMY,UAA4BZ,EAAW;AAAA,EAClD,YAAYa,GAAiC;AAC3C,UAAM,8CAA8C,OAAOA,CAAK,CAAC,IAAI;AAAA,EACvE;AACF;;;;;;;"}
@@ -0,0 +1,4 @@
1
+ "use strict";var h=Object.defineProperty;var p=(r,e,t)=>e in r?h(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>p(r,typeof e!="symbol"?e+"":e,t);class i extends Error{constructor(t,s){const l=s?{cause:s.cause}:{};super(t,l);o(this,"$__name");o(this,"$__message");const n=this.constructor;if(Object.setPrototypeOf(this,n),this.$__name=n.name,this.$__message=t,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n),this.stack&&s&&s.trim&&s.trim>0){const a=this.stack.split(`
2
+ `);a.splice(0,s.trim),this.stack=a.join(`
3
+ `)}}get name(){return this.$__name}get message(){return this.$__message}get[Symbol.toStringTag](){return this.constructor.name}toString(){return`${this.name}: ${this.message}`}[Symbol.toPrimitive](t){switch(t){case"string":return this.toString();default:return!0}}static[Symbol.hasInstance](t){if(typeof t=="object"&&t!==null||typeof t=="function"){const s=Object.getPrototypeOf(t);return s.name===this.name||s===this}return!1}}class c extends i{constructor(){super("Unable to setup instance because Service Workers are not supported in this environment")}}class u extends i{constructor(){super("Unable to setup instance because another instance is already initialized in this context")}}class m extends i{constructor(e){super(`Request timed out while waiting for event "${String(e)}".`)}}const d=Object.freeze(Object.defineProperty({__proto__:null,AlreadyInitializedInContextError:u,RequestTimeoutError:m,UnsupportedEnvironmentError:c},Symbol.toStringTag,{value:"Module"}));exports.AlreadyInitializedInContextError=u;exports.RequestTimeoutError=m;exports.UnsupportedEnvironmentError=c;exports.errors=d;
4
+ //# sourceMappingURL=errors-DTZFdRbq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DTZFdRbq.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Easily accessible error classes for Swarm\n * @module @nhtio/swarm/errors\n */\n\n/**\n * Describes the options for the SwarmError class.\n */\nexport interface SwarmErrorOptions {\n /**\n * The cause data property of an Error instance indicates the specific original cause of the error.\n */\n cause?: Error\n /**\n * How many rows to trim from the stack trace.\n * This is useful for removing the stack trace of the current function from the error.\n */\n trim?: number\n}\n\n/**\n * Base class for all Swarm errors.\n * @extends Error\n */\nclass SwarmError extends Error {\n /** @private */\n readonly $__name: string\n /** @private */\n readonly $__message: string\n\n /**\n * Creates a new SwarmError instance.\n * @param message The error message.\n * @param options The error options.\n */\n constructor(message: string, options?: SwarmErrorOptions) {\n const superOptions = options ? { cause: options.cause } : {}\n super(message, superOptions)\n const ErrorConstructor = this.constructor\n Object.setPrototypeOf(this, ErrorConstructor)\n this.$__name = ErrorConstructor.name\n this.$__message = message\n if ('function' === typeof Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorConstructor)\n }\n if (this.stack && options && options.trim && options.trim > 0) {\n const stackLines = this.stack.split('\\n')\n stackLines.splice(0, options.trim)\n this.stack = stackLines.join('\\n')\n }\n }\n\n get name() {\n return this.$__name\n }\n\n get message() {\n return this.$__message\n }\n\n get [Symbol.toStringTag]() {\n return this.constructor.name\n }\n\n toString() {\n return `${this.name}: ${this.message}`\n }\n\n [Symbol.toPrimitive](hint: 'number' | 'string' | 'default') {\n switch (hint) {\n case 'string':\n return this.toString()\n default:\n return true\n }\n }\n\n static [Symbol.hasInstance](instance: unknown) {\n if ((typeof instance === 'object' && instance !== null) || typeof instance === 'function') {\n const proto = Object.getPrototypeOf(instance)\n return proto.name === this.name || proto === this\n }\n return false\n }\n}\n\nexport type { SwarmError }\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialized in an environment that does not support Service Workers.\n */\nexport class UnsupportedEnvironmentError extends SwarmError {\n constructor() {\n super('Unable to setup instance because Service Workers are not supported in this environment')\n }\n}\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialize more than one instance within the same context.\n */\nexport class AlreadyInitializedInContextError extends SwarmError {\n constructor() {\n super(\n 'Unable to setup instance because another instance is already initialized in this context'\n )\n }\n}\n\n/**\n * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when a request to the leader is not answered.\n */\nexport class RequestTimeoutError extends SwarmError {\n constructor(event: string | number | symbol) {\n super(`Request timed out while waiting for event \"${String(event)}\".`)\n }\n}\n"],"names":["SwarmError","message","options","superOptions","__publicField","ErrorConstructor","stackLines","hint","instance","proto","UnsupportedEnvironmentError","AlreadyInitializedInContextError","RequestTimeoutError","event"],"mappings":"iLAwBA,MAAMA,UAAmB,KAAM,CAW7B,YAAYC,EAAiBC,EAA6B,CACxD,MAAMC,EAAeD,EAAU,CAAE,MAAOA,EAAQ,OAAU,GAC1D,MAAMD,EAASE,CAAY,EAXpBC,EAAA,gBAEAA,EAAA,mBAUP,MAAMC,EAAmB,KAAK,YAO9B,GANO,OAAA,eAAe,KAAMA,CAAgB,EAC5C,KAAK,QAAUA,EAAiB,KAChC,KAAK,WAAaJ,EACC,OAAO,MAAM,mBAA5B,YACI,MAAA,kBAAkB,KAAMI,CAAgB,EAE5C,KAAK,OAASH,GAAWA,EAAQ,MAAQA,EAAQ,KAAO,EAAG,CAC7D,MAAMI,EAAa,KAAK,MAAM,MAAM;AAAA,CAAI,EAC7BA,EAAA,OAAO,EAAGJ,EAAQ,IAAI,EAC5B,KAAA,MAAQI,EAAW,KAAK;AAAA,CAAI,CACnC,CACF,CAEA,IAAI,MAAO,CACT,OAAO,KAAK,OACd,CAEA,IAAI,SAAU,CACZ,OAAO,KAAK,UACd,CAEA,IAAK,OAAO,WAAW,GAAI,CACzB,OAAO,KAAK,YAAY,IAC1B,CAEA,UAAW,CACT,MAAO,GAAG,KAAK,IAAI,KAAK,KAAK,OAAO,EACtC,CAEA,CAAC,OAAO,WAAW,EAAEC,EAAuC,CAC1D,OAAQA,EAAM,CACZ,IAAK,SACH,OAAO,KAAK,WACd,QACS,MAAA,EACX,CACF,CAEA,OAAQ,OAAO,WAAW,EAAEC,EAAmB,CAC7C,GAAK,OAAOA,GAAa,UAAYA,IAAa,MAAS,OAAOA,GAAa,WAAY,CACnF,MAAAC,EAAQ,OAAO,eAAeD,CAAQ,EAC5C,OAAOC,EAAM,OAAS,KAAK,MAAQA,IAAU,IAC/C,CACO,MAAA,EACT,CACF,CAOO,MAAMC,UAAoCV,CAAW,CAC1D,aAAc,CACZ,MAAM,wFAAwF,CAChG,CACF,CAKO,MAAMW,UAAyCX,CAAW,CAC/D,aAAc,CACZ,MACE,0FAAA,CAEJ,CACF,CAKO,MAAMY,UAA4BZ,CAAW,CAClD,YAAYa,EAAiC,CAC3C,MAAM,8CAA8C,OAAOA,CAAK,CAAC,IAAI,CACvE,CACF"}
package/errors.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./errors-DTZFdRbq.js");exports.AlreadyInitializedInContextError=r.AlreadyInitializedInContextError;exports.RequestTimeoutError=r.RequestTimeoutError;exports.UnsupportedEnvironmentError=r.UnsupportedEnvironmentError;
2
+ //# sourceMappingURL=errors.cjs.map
package/errors.cjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/errors.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Easily accessible error classes for Swarm
3
+ * @module @nhtio/swarm/errors
4
+ */
5
+ /**
6
+ * Describes the options for the SwarmError class.
7
+ */
8
+ export interface SwarmErrorOptions {
9
+ /**
10
+ * The cause data property of an Error instance indicates the specific original cause of the error.
11
+ */
12
+ cause?: Error;
13
+ /**
14
+ * How many rows to trim from the stack trace.
15
+ * This is useful for removing the stack trace of the current function from the error.
16
+ */
17
+ trim?: number;
18
+ }
19
+ /**
20
+ * Base class for all Swarm errors.
21
+ * @extends Error
22
+ */
23
+ declare class SwarmError extends Error {
24
+ /** @private */
25
+ readonly $__name: string;
26
+ /** @private */
27
+ readonly $__message: string;
28
+ /**
29
+ * Creates a new SwarmError instance.
30
+ * @param message The error message.
31
+ * @param options The error options.
32
+ */
33
+ constructor(message: string, options?: SwarmErrorOptions);
34
+ get name(): string;
35
+ get message(): string;
36
+ get [Symbol.toStringTag](): string;
37
+ toString(): string;
38
+ [Symbol.toPrimitive](hint: 'number' | 'string' | 'default'): string | true;
39
+ static [Symbol.hasInstance](instance: unknown): boolean;
40
+ }
41
+ export type { SwarmError };
42
+ /**
43
+ * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialized in an environment that does not support Service Workers.
44
+ */
45
+ export declare class UnsupportedEnvironmentError extends SwarmError {
46
+ constructor();
47
+ }
48
+ /**
49
+ * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when trying to be initialize more than one instance within the same context.
50
+ */
51
+ export declare class AlreadyInitializedInContextError extends SwarmError {
52
+ constructor();
53
+ }
54
+ /**
55
+ * Thrown by the {@link @nhtio/swarm!Swarm | Swarm} class when a request to the leader is not answered.
56
+ */
57
+ export declare class RequestTimeoutError extends SwarmError {
58
+ constructor(event: string | number | symbol);
59
+ }
package/errors.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { A as o, R as t, U as n } from "./errors-BsRN4TW4.mjs";
2
+ export {
3
+ o as AlreadyInitializedInContextError,
4
+ t as RequestTimeoutError,
5
+ n as UnsupportedEnvironmentError
6
+ };
7
+ //# sourceMappingURL=errors.mjs.map
package/errors.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
package/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";var ht=Object.defineProperty;var pt=Object.getPrototypeOf;var mt=Reflect.get;var Ae=e=>{throw TypeError(e)};var gt=(e,t,r)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var U=(e,t,r)=>gt(e,typeof t!="symbol"?t+"":t,r),me=(e,t,r)=>t.has(e)||Ae("Cannot "+r);var a=(e,t,r)=>(me(e,t,"read from private field"),r?r.call(e):t.get(e)),v=(e,t,r)=>t.has(e)?Ae("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),g=(e,t,r,n)=>(me(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),d=(e,t,r)=>(me(e,t,"access private method"),r);var Ne=(e,t,r)=>mt(pt(e),r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const wt=require("./types-C0eRuyk9.js"),ae=require("./errors-DTZFdRbq.js"),je=()=>typeof window<"u"&&typeof window.navigator<"u"&&typeof window.navigator.userAgent<"u",vt=()=>typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope,bt=()=>typeof process<"u"&&typeof process.versions<"u"&&!!process.versions.node,yt=()=>typeof window<"u"&&typeof window.navigator<"u"&&window.navigator.userAgent.includes("Safari")&&!window.navigator.userAgent.includes("Chrome");function Et(e){return typeof e=="object"&&e!==null&&"Math"in e}const q=()=>{const t=[typeof window<"u"?window:void 0,typeof self<"u"?self:void 0,typeof global<"u"?global:void 0].filter(r=>Et(r));if(t.length===0)throw new Error("No global object found");return t[0]},F=e=>{const t=q(),r=new Uint8Array(e);if(typeof t.crypto<"u"&&typeof t.crypto.getRandomValues=="function")t.crypto.getRandomValues(r);else for(let n=0;n<e;n++)r[n]=Math.floor(Math.random()*256);return Array.from(r).map(n=>n.toString(16).padStart(2,"0")).join("")},j=Symbol("nhtio.swarm"),ie=Symbol("nhtio.swarm.logger"),_t={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 P=(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))(P||{});const Lt={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 Ke=(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))(Ke||{}),ee,te,z,re,H,B,w,ze,y;class Oe{constructor(t=3){v(this,w);v(this,ee);v(this,te);v(this,z);v(this,re);v(this,H);v(this,B);g(this,B,t),g(this,ee,je()),g(this,te,vt()),g(this,z,bt()),g(this,re,yt())}get level(){return P[a(this,B)]}set level(t){g(this,B,P[t.toUpperCase()])}EMERG(...t){d(this,w,y).call(this,"EMERG",...t)}ALERT(...t){d(this,w,y).call(this,"ALERT",...t)}CRIT(...t){d(this,w,y).call(this,"CRIT",...t)}ERROR(...t){d(this,w,y).call(this,"ERROR",...t)}WARNING(...t){d(this,w,y).call(this,"WARNING",...t)}NOTICE(...t){d(this,w,y).call(this,"NOTICE",...t)}INFO(...t){d(this,w,y).call(this,"INFO",...t)}DEBUG(...t){d(this,w,y).call(this,"DEBUG",...t)}emerg(...t){d(this,w,y).call(this,"EMERG",...t)}alert(...t){d(this,w,y).call(this,"ALERT",...t)}crit(...t){d(this,w,y).call(this,"CRIT",...t)}error(...t){d(this,w,y).call(this,"ERROR",...t)}warning(...t){d(this,w,y).call(this,"WARNING",...t)}notice(...t){d(this,w,y).call(this,"NOTICE",...t)}info(...t){d(this,w,y).call(this,"INFO",...t)}debug(...t){d(this,w,y).call(this,"DEBUG",...t)}}ee=new WeakMap,te=new WeakMap,z=new WeakMap,re=new WeakMap,H=new WeakMap,B=new WeakMap,w=new WeakSet,ze=function(){let t;return a(this,ee)?t="BROWSER":a(this,te)?t="WORKER":a(this,z)?t="SSR":t="UNKNOWN",Lt[t](t)},y=function(t,...r){t=t.toUpperCase();const n=P[t],s=P[a(this,B)];if(n>s)return;const[o,i]=d(this,w,ze).call(this),[u,c]=_t[t](t),f=[`${o}${u}${a(this,H)?`%c ${a(this,H)}`:""}`,i,c];for(a(this,H)&&f.push("color: inherit"),f.push(...r);f[f.length-1]===void 0;)f.pop();a(this,re)||a(this,z)?console[Ke[t]](...f):(console.groupCollapsed(...f),console.debug(new Error("stack").stack.split(`
2
+ `).slice(3).join(`
3
+ `)),console.groupEnd())};const Rt=()=>{const e=q();return typeof e.SWARM_LOG_LEVEL=="string"&&e.SWARM_LOG_LEVEL.toUpperCase()in P?e.SWARM_LOG_LEVEL:3},He=()=>{const e=q();if(typeof e[ie]<"u"&&e[ie]instanceof Oe)return e[ie];const t=Rt(),r=P[t],n=new Oe(r);return e[ie]=n,n},Tt=e=>{const t=q(),r=He();t.SWARM_LOG_LEVEL=e.toUpperCase(),r.level=e};var de={exports:{}};de.exports;function Le(){}Le.prototype={on:function(e,t,r){var n=this.e||(this.e={});return(n[e]||(n[e]=[])).push({fn:t,ctx:r}),this},once:function(e,t,r){var n=this;function s(){n.off(e,s),t.apply(r,arguments)}return s._=t,this.on(e,s,r)},emit:function(e){var t=[].slice.call(arguments,1),r=((this.e||(this.e={}))[e]||[]).slice(),n=0,s=r.length;for(n;n<s;n++)r[n].fn.apply(r[n].ctx,t);return this},off:function(e,t){var r=this.e||(this.e={}),n=r[e],s=[];if(n&&t)for(var o=0,i=n.length;o<i;o++)n[o].fn!==t&&n[o].fn._!==t&&s.push(n[o]);return s.length?r[e]=s:delete r[e],this}};de.exports=Le;var kt=de.exports.TinyEmitter=Le;de.exports;class Pe extends kt{on(t,r,n){return super.on(t,r,n),this}once(t,r,n){return super.once(t,r,n),this}emit(t,...r){return super.emit(t,...r),this}off(t,r){return super.off(t,r),this}}function It(e){return e&&typeof e.then=="function"}Promise.resolve(!1);var Mt=Promise.resolve(!0),M=Promise.resolve();function x(e,t){return e||(e=0),new Promise(function(r){return setTimeout(function(){return r(t)},e)})}function Ct(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function ne(){return Math.random().toString(36).substring(2)}var ge=0;function se(){var e=Date.now()*1e3;return e<=ge&&(e=ge+1),ge=e,e}function St(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}var At=se,Nt="native";function Ot(e){var t={time:se(),messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(r){t.messagesCallback&&t.messagesCallback(r.data)},t}function Pt(e){e.bc.close(),e.subFns=[]}function xt(e,t){try{return e.bc.postMessage(t,!1),M}catch(r){return Promise.reject(r)}}function Bt(e,t){e.messagesCallback=t}function Dt(){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 $t(){return 150}var Gt={create:Ot,close:Pt,onMessage:Bt,postMessage:xt,canBeUsed:Dt,type:Nt,averageResponseTime:$t,microSeconds:At};class qe{constructor(t){U(this,"ttl");U(this,"map",new Map);U(this,"_to",!1);this.ttl=t}has(t){return this.map.has(t)}add(t){this.map.set(t,Je()),this._to||(this._to=!0,setTimeout(()=>{this._to=!1,Wt(this)},0))}clear(){this.map.clear()}}function Wt(e){const t=Je()-e.ttl,r=e.map[Symbol.iterator]();for(;;){const n=r.next().value;if(!n)return;const s=n[0];if(n[1]<t)e.map.delete(s);else return}}function Je(){return Date.now()}function Re(){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 Ut=se,Ft="pubkey.broadcast-channel-0-",C="messages",le={durability:"relaxed"},jt="idb";function Qe(){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 Te(e){e.commit&&e.commit()}function Kt(e){var t=Qe(),r=Ft+e,n=t.open(r);return n.onupgradeneeded=function(s){var o=s.target.result;o.createObjectStore(C,{keyPath:"id",autoIncrement:!0})},new Promise(function(s,o){n.onerror=function(i){return o(i)},n.onsuccess=function(){s(n.result)}})}function zt(e,t,r){var n=Date.now(),s={uuid:t,time:n,data:r},o=e.transaction([C],"readwrite",le);return new Promise(function(i,u){o.oncomplete=function(){return i()},o.onerror=function(f){return u(f)};var c=o.objectStore(C);c.add(s),Te(o)})}function Ht(e,t){var r=e.transaction(C,"readonly",le),n=r.objectStore(C),s=[],o=IDBKeyRange.bound(t+1,1/0);if(n.getAll){var i=n.getAll(o);return new Promise(function(c,f){i.onerror=function(h){return f(h)},i.onsuccess=function(h){c(h.target.result)}})}function u(){try{return o=IDBKeyRange.bound(t+1,1/0),n.openCursor(o)}catch{return n.openCursor()}}return new Promise(function(c,f){var h=u();h.onerror=function(p){return f(p)},h.onsuccess=function(p){var m=p.target.result;m?m.value.id<t+1?m.continue(t+1):(s.push(m.value),m.continue()):(Te(r),c(s))}})}function qt(e,t){if(e.closed)return Promise.resolve([]);var r=e.db.transaction(C,"readwrite",le),n=r.objectStore(C);return Promise.all(t.map(function(s){var o=n.delete(s);return new Promise(function(i){o.onsuccess=function(){return i()}})}))}function Jt(e,t){var r=Date.now()-t,n=e.transaction(C,"readonly",le),s=n.objectStore(C),o=[];return new Promise(function(i){s.openCursor().onsuccess=function(u){var c=u.target.result;if(c){var f=c.value;f.time<r?(o.push(f),c.continue()):(Te(n),i(o))}else i(o)}})}function Qt(e){return Jt(e.db,e.options.idb.ttl).then(function(t){return qt(e,t.map(function(r){return r.id}))})}function Yt(e,t){return t=Re(t),Kt(e).then(function(r){var n={closed:!1,lastCursorId:0,channelName:e,options:t,uuid:ne(),eMIs:new qe(t.idb.ttl*2),writeBlockPromise:M,messagesCallback:null,readQueuePromises:[],db:r};return r.onclose=function(){n.closed=!0,t.idb.onclose&&t.idb.onclose()},Ye(n),n})}function Ye(e){e.closed||Ve(e).then(function(){return x(e.options.idb.fallbackInterval)}).then(function(){return Ye(e)})}function Vt(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time<t.messagesCallbackTime)}function Ve(e){return e.closed||!e.messagesCallback?M:Ht(e.db,e.lastCursorId).then(function(t){var r=t.filter(function(n){return!!n}).map(function(n){return n.id>e.lastCursorId&&(e.lastCursorId=n.id),n}).filter(function(n){return Vt(n,e)}).sort(function(n,s){return n.time-s.time});return r.forEach(function(n){e.messagesCallback&&(e.eMIs.add(n.id),e.messagesCallback(n.data))}),M})}function Xt(e){e.closed=!0,e.db.close()}function Zt(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return zt(e.db,e.uuid,t)}).then(function(){Ct(0,10)===0&&Qt(e)}),e.writeBlockPromise}function er(e,t,r){e.messagesCallbackTime=r,e.messagesCallback=t,Ve(e)}function tr(){return!!Qe()}function rr(e){return e.idb.fallbackInterval*2}var nr={create:Yt,close:Xt,onMessage:er,postMessage:Zt,canBeUsed:tr,type:jt,averageResponseTime:rr,microSeconds:Ut},sr=se,ir="pubkey.broadcastChannel-",or="localstorage";function Xe(){var e;if(typeof window>"u")return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch{}return e}function Ze(e){return ir+e}function ar(e,t){return new Promise(function(r){x().then(function(){var n=Ze(e.channelName),s={token:ne(),time:Date.now(),data:t,uuid:e.uuid},o=JSON.stringify(s);Xe().setItem(n,o);var i=document.createEvent("Event");i.initEvent("storage",!0,!0),i.key=n,i.newValue=o,window.dispatchEvent(i),r()})})}function ur(e,t){var r=Ze(e),n=function(o){o.key===r&&t(JSON.parse(o.newValue))};return window.addEventListener("storage",n),n}function cr(e){window.removeEventListener("storage",e)}function fr(e,t){if(t=Re(t),!et())throw new Error("BroadcastChannel: localstorage cannot be used");var r=ne(),n=new qe(t.localstorage.removeTimeout),s={channelName:e,uuid:r,eMIs:n};return s.listener=ur(e,function(o){s.messagesCallback&&o.uuid!==r&&(!o.token||n.has(o.token)||o.data.time&&o.data.time<s.messagesCallbackTime||(n.add(o.token),s.messagesCallback(o.data)))}),s}function dr(e){cr(e.listener)}function lr(e,t,r){e.messagesCallbackTime=r,e.messagesCallback=t}function et(){var e=Xe();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch{return!1}return!0}function hr(){var e=120,t=navigator.userAgent.toLowerCase();return t.includes("safari")&&!t.includes("chrome")?e*2:e}var pr={create:fr,close:dr,onMessage:lr,postMessage:ar,canBeUsed:et,type:or,averageResponseTime:hr,microSeconds:sr},tt=se,mr="simulate",ke=new Set;function gr(e){var t={time:tt(),name:e,messagesCallback:null};return ke.add(t),t}function wr(e){ke.delete(e)}var rt=5;function vr(e,t){return new Promise(function(r){return setTimeout(function(){var n=Array.from(ke);n.forEach(function(s){s.name===e.name&&s!==e&&s.messagesCallback&&s.time<t.time&&s.messagesCallback(t)}),r()},rt)})}function br(e,t){e.messagesCallback=t}function yr(){return!0}function Er(){return rt}var _r={create:gr,close:wr,onMessage:br,postMessage:vr,canBeUsed:yr,type:mr,averageResponseTime:Er,microSeconds:tt},xe=[Gt,nr,pr];function Lr(e){var t=[].concat(e.methods,xe).filter(Boolean);if(e.type){if(e.type==="simulate")return _r;var r=t.find(function(s){return s.type===e.type});if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||(t=t.filter(function(s){return s.type!=="idb"}));var n=t.find(function(s){return s.canBeUsed()});if(n)return n;throw new Error("No usable method found in "+JSON.stringify(xe.map(function(s){return s.type})))}var nt=new Set,Rr=0,ce=function(t,r){this.id=Rr++,nt.add(this),this.name=t,Be&&(r=Be),this.options=Re(r),this.method=Lr(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,Tr(this)};ce._pubkey=!0;var Be;ce.prototype={postMessage:function(t){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(t));return De(this,"message",t)},postInternal:function(t){return De(this,"internal",t)},set onmessage(e){var t=this.method.microSeconds(),r={time:t,fn:e};Ge(this,"message",this._onML),e&&typeof e=="function"?(this._onML=r,$e(this,"message",r)):this._onML=null},addEventListener:function(t,r){var n=this.method.microSeconds(),s={time:n,fn:r};$e(this,t,s)},removeEventListener:function(t,r){var n=this._addEL[t].find(function(s){return s.fn===r});Ge(this,t,n)},close:function(){var t=this;if(!this.closed){nt.delete(this),this.closed=!0;var r=this._prepP?this._prepP:M;return this._onML=null,this._addEL.message=[],r.then(function(){return Promise.all(Array.from(t._uMP))}).then(function(){return Promise.all(t._befC.map(function(n){return n()}))}).then(function(){return t.method.close(t._state)})}},get type(){return this.method.type},get isClosed(){return this.closed}};function De(e,t,r){var n=e.method.microSeconds(),s={time:n,type:t,data:r},o=e._prepP?e._prepP:M;return o.then(function(){var i=e.method.postMessage(e._state,s);return e._uMP.add(i),i.catch().then(function(){return e._uMP.delete(i)}),i})}function Tr(e){var t=e.method.create(e.name,e.options);It(t)?(e._prepP=t,t.then(function(r){e._state=r})):e._state=t}function st(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function $e(e,t,r){e._addEL[t].push(r),kr(e)}function Ge(e,t,r){e._addEL[t]=e._addEL[t].filter(function(n){return n!==r}),Ir(e)}function kr(e){if(!e._iL&&st(e)){var t=function(s){e._addEL[s.type].forEach(function(o){s.time>=o.time&&o.fn(s.data)})},r=e.method.microSeconds();e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,r)}):(e._iL=!0,e.method.onMessage(e._state,t,r))}}function Ir(e){if(e._iL&&!st(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}function Mr(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 Cr(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 Sr=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Ar=Sr?Cr:Mr,X=new Set,We=!1;function Nr(){We||(We=!0,Ar(Pr))}function Or(e){if(Nr(),typeof e!="function")throw new Error("Listener is no function");X.add(e);var t={remove:function(){return X.delete(e)},run:function(){return X.delete(e),e()}};return t}function Pr(){var e=[];return X.forEach(function(t){e.push(t()),X.delete(t)}),Promise.all(e)}function W(e,t){var r={context:"leader",action:t,token:e.token};return e.broadcastChannel.postInternal(r)}function it(e){e.isLeader=!0,e._hasLeader=!0;var t=Or(function(){return e.die()});e._unl.push(t);var r=function(s){s.context==="leader"&&s.action==="apply"&&W(e,"tell"),s.context==="leader"&&s.action==="tell"&&!e._dpLC&&(e._dpLC=!0,e._dpL(),W(e,"tell"))};return e.broadcastChannel.addEventListener("internal",r),e._lstns.push(r),W(e,"tell")}var ot=function(t,r){var n=this;this.broadcastChannel=t,t._befC.push(function(){return n.die()}),this._options=r,this.isLeader=!1,this.isDead=!1,this.token=ne(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+t.method.type+"||"+t.name};ot.prototype={hasLeader:function(){var t=this;return navigator.locks.query().then(function(r){var n=r.held?r.held.filter(function(s){return s.name===t.lN}):[];return!!(n&&n.length>0)})},awaitLeadership:function(){var t=this;if(!this._wLMP){this._wKMC.c=new AbortController;var r=new Promise(function(n,s){t._wKMC.res=n,t._wKMC.rej=s});this._wLMP=new Promise(function(n){navigator.locks.request(t.lN,{signal:t._wKMC.c.signal},function(){return t._wKMC.c=void 0,it(t),n(),r}).catch(function(){})})}return this._wLMP},set onduplicate(e){},die:function(){var t=this;return this._lstns.forEach(function(r){return t.broadcastChannel.removeEventListener("internal",r)}),this._lstns=[],this._unl.forEach(function(r){return r.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"),W(this,"death")}};var at=function(t,r){var n=this;this.broadcastChannel=t,this._options=r,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=ne(),this._aplQ=M,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var s=function(i){i.context==="leader"&&(i.action==="death"&&(n._hasLeader=!1),i.action==="tell"&&(n._hasLeader=!0))};this.broadcastChannel.addEventListener("internal",s),this._lstns.push(s)};at.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(t){var r=this;if(this.isLeader)return x(0,!0);if(this.isDead)return x(0,!1);if(this._aplQC>1)return this._aplQ;var n=function(){if(r.isLeader)return Mt;var o=!1,i,u=new Promise(function(h){i=function(){o=!0,h()}}),c=function(p){p.context==="leader"&&p.token!=r.token&&(p.action==="apply"&&p.token>r.token&&i(),p.action==="tell"&&(i(),r._hasLeader=!0))};r.broadcastChannel.addEventListener("internal",c);var f=t?r._options.responseTime*4:r._options.responseTime;return W(r,"apply").then(function(){return Promise.race([x(f),u.then(function(){return Promise.reject(new Error)})])}).then(function(){return W(r,"apply")}).then(function(){return Promise.race([x(f),u.then(function(){return Promise.reject(new Error)})])}).catch(function(){}).then(function(){return r.broadcastChannel.removeEventListener("internal",c),o?!1:it(r).then(function(){return!0})})};return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then(function(){return n()}).then(function(){r._aplQC=r._aplQC-1}),this._aplQ.then(function(){return r.isLeader})},awaitLeadership:function(){return this._aLP||(this._aLP=xr(this)),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var t=this;return this._lstns.forEach(function(r){return t.broadcastChannel.removeEventListener("internal",r)}),this._lstns=[],this._unl.forEach(function(r){return r.remove()}),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,W(this,"death")}};function xr(e){return e.isLeader?M:new Promise(function(t){var r=!1;function n(){r||(r=!0,e.broadcastChannel.removeEventListener("internal",o),t(!0))}e.applyOnce().then(function(){e.isLeader&&n()});var s=function(){return x(e._options.fallbackInterval).then(function(){if(!(e.isDead||r))if(e.isLeader)n();else return e.applyOnce(!0).then(function(){e.isLeader?n():s()})})};s();var o=function(u){u.context==="leader"&&u.action==="death"&&(e._hasLeader=!1,e.applyOnce().then(function(){e.isLeader&&n()}))};e.broadcastChannel.addEventListener("internal",o),e._lstns.push(o)})}function Br(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 Ue(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=Br(t,e);var r=St()?new ot(e,t):new at(e,t);return e._befC.push(function(){return r.die()}),e._leaderElector=r,r}const ut=-1,he=0,Z=1,fe=2,Ie=3,Me=4,Ce=5,Se=6,ct=7,ft=8,Fe=typeof self=="object"?self:globalThis,Dr=(e,t)=>{const r=(s,o)=>(e.set(o,s),s),n=s=>{if(e.has(s))return e.get(s);const[o,i]=t[s];switch(o){case he:case ut:return r(i,s);case Z:{const u=r([],s);for(const c of i)u.push(n(c));return u}case fe:{const u=r({},s);for(const[c,f]of i)u[n(c)]=n(f);return u}case Ie:return r(new Date(i),s);case Me:{const{source:u,flags:c}=i;return r(new RegExp(u,c),s)}case Ce:{const u=r(new Map,s);for(const[c,f]of i)u.set(n(c),n(f));return u}case Se:{const u=r(new Set,s);for(const c of i)u.add(n(c));return u}case ct:{const{name:u,message:c}=i;return r(new Fe[u](c),s)}case ft:return r(BigInt(i),s);case"BigInt":return r(Object(BigInt(i)),s);case"ArrayBuffer":return r(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:u}=new Uint8Array(i);return r(new DataView(u),i)}}return r(new Fe[o](i),s)};return n},$r=e=>Dr(new Map,e)(0),K="",{toString:Gr}={},{keys:Wr}=Object,Q=e=>{const t=typeof e;if(t!=="object"||!e)return[he,t];const r=Gr.call(e).slice(8,-1);switch(r){case"Array":return[Z,K];case"Object":return[fe,K];case"Date":return[Ie,K];case"RegExp":return[Me,K];case"Map":return[Ce,K];case"Set":return[Se,K];case"DataView":return[Z,r]}return r.includes("Array")?[Z,r]:r.includes("Error")?[ct,r]:[fe,r]},oe=([e,t])=>e===he&&(t==="function"||t==="symbol"),Ur=(e,t,r,n)=>{const s=(i,u)=>{const c=n.push(i)-1;return r.set(u,c),c},o=i=>{if(r.has(i))return r.get(i);let[u,c]=Q(i);switch(u){case he:{let h=i;switch(c){case"bigint":u=ft,h=i.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return s([ut],i)}return s([u,h],i)}case Z:{if(c){let m=i;return c==="DataView"?m=new Uint8Array(i.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(i)),s([c,[...m]],i)}const h=[],p=s([u,h],i);for(const m of i)h.push(o(m));return p}case fe:{if(c)switch(c){case"BigInt":return s([c,i.toString()],i);case"Boolean":case"Number":case"String":return s([c,i.valueOf()],i)}if(t&&"toJSON"in i)return o(i.toJSON());const h=[],p=s([u,h],i);for(const m of Wr(i))(e||!oe(Q(i[m])))&&h.push([o(m),o(i[m])]);return p}case Ie:return s([u,i.toISOString()],i);case Me:{const{source:h,flags:p}=i;return s([u,{source:h,flags:p}],i)}case Ce:{const h=[],p=s([u,h],i);for(const[m,J]of i)(e||!(oe(Q(m))||oe(Q(J))))&&h.push([o(m),o(J)]);return p}case Se:{const h=[],p=s([u,h],i);for(const m of i)(e||!oe(Q(m)))&&h.push(o(m));return p}}const{message:f}=i;return s([u,{name:c,message:f}],i)};return o},Y=(e,{json:t,lossy:r}={})=>{const n=[];return Ur(!(t||r),!!t,new Map,n)(e),n},_=He();var D,R,$,A,I,N,k,E,T,O,G,l,ve,be,ye,Ee,V,dt,ue,lt,_e;const L=class L extends Pe{constructor(){const r=q();if(typeof r[j]<"u"&&r[j]instanceof L)throw new ae.AlreadyInitializedInContextError;if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new ae.UnsupportedEnvironmentError;super();v(this,l);v(this,D);v(this,R);v(this,$);v(this,A);v(this,I);v(this,N);v(this,k);v(this,E);v(this,T);v(this,O);v(this,G);r[j]=this,g(this,D,F(8)),g(this,R,new Pe),g(this,$,new Map),g(this,A,new Map),g(this,I,new Map),g(this,N,new Map),g(this,k,new Map),g(this,G,1e3),_.debug(`Swarm instance initialized with ID "${a(this,D)}"`),g(this,O,!1),g(this,E,new ce("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{_.WARNING("Swarm channel closed, reinitializing..."),a(this,E).close(),d(this,l,ve).call(this,!0)}}})),g(this,T,Ue(a(this,E))),d(this,l,Ee).call(this),d(this,l,be).call(this),_.debug("Swarm instance is ready"),d(this,l,lt).call(this),je()&&r.addEventListener("beforeunload",()=>{d(this,l,ue).call(this,L.INTERNAL_OBITUARY,a(this,D))})}get id(){return a(this,D)}get leader(){return a(this,O)}emit(r,...n){const s={id:F(16),event:r,args:n,needsAck:!1,isAck:!1},o=Y(s);return a(this,E).postMessage(o).catch(i=>{_.error("Got error while sending message",i)}),super.emit(r,...n),this}onLeadershipChange(r){return a(this,R).on("leadership",r),this}offLeadershipChange(r){return a(this,R).off("leadership",r),this}onceLeadershipChange(r){return a(this,R).once("leadership",r),this}collect(r,...n){const s=F(16),o=a(this,N).get(r),i={responses:[],timer:null,resolve:f=>{}},u=new Promise(f=>{i.resolve=f,i.timer=setTimeout(()=>{a(this,I).delete(s),f(i.responses)},a(this,G))});a(this,I).set(s,i),o&&Promise.resolve(o(...n)).then(f=>{i.responses.push(f),d(this,l,_e).call(this,s)});const c={id:s,event:r,args:n,needsCollect:!0};return a(this,E).postMessage(Y(c)).catch(f=>_.error(f)),u}onCollect(r,n){return a(this,N).set(r,n),this}offCollect(r){return a(this,N).delete(r),this}request(r,...n){const s=F(16),i=Y({id:s,event:r,args:n,needsAck:!0});return a(this,E).postMessage(i).catch(u=>{_.error("Error sending request:",u)}),new Promise((u,c)=>{const f=setTimeout(()=>{a(this,A).delete(s),c(new ae.RequestTimeoutError(r))},a(this,G));a(this,A).set(s,{resolve:u,reject:c,timer:f})})}onRequest(r,n){return a(this,$).set(r,n),this}offRequest(r){return a(this,$).delete(r),this}setAwaitResponseTimeout(r){return g(this,G,r),this}static instance(){const r=q();return typeof r[j]<"u"&&r[j]instanceof L?r[j]:new L}};D=new WeakMap,R=new WeakMap,$=new WeakMap,A=new WeakMap,I=new WeakMap,N=new WeakMap,k=new WeakMap,E=new WeakMap,T=new WeakMap,O=new WeakMap,G=new WeakMap,l=new WeakSet,ve=function(r=!1){a(this,E)&&!r||(g(this,E,new ce("nhtio-swarm",{webWorkerSupport:!0,idb:{onclose:()=>{a(this,E).close(),d(this,l,ve).call(this,!0)}}})),g(this,T,Ue(a(this,E))),d(this,l,be).call(this))},be=function(){_.debug("Hooking swarm channel events"),a(this,E).onmessage=r=>d(this,l,dt).call(this,r),_.debug("Swarm channel events hooked")},ye=function(r){a(this,O)!==r&&(g(this,O,r),a(this,R).emit("leadership",r),_.debug(`Swarm instance is now ${r?"the":"not the"} leader`))},Ee=function(){new Promise(async r=>{await a(this,T).hasLeader()||(_.debug("No leader found, trying to elect one"),await a(this,T).awaitLeadership(),_.debug("Leader elected"),d(this,l,ye).call(this,a(this,T).isLeader)),r(void 0)}).catch(r=>{_.error("Got error while checking for leader",r)}).finally(()=>{setTimeout(()=>d(this,l,Ee).call(this),500)})},V=function(r){a(this,E).postMessage(Y({id:F(16),...r})).catch(n=>_.error(n))},dt=function(r){const n=$r(r);if(typeof n!="object"||n===null||typeof n.event!="string"&&typeof n.event!="number"||!Array.isArray(n.args))return;const{id:s,event:o,args:i,needsAck:u,isAck:c,needsCollect:f,isCollectResponse:h,replyTo:p,result:m,error:J}=n;if(o===L.INTERNAL_HEARTBEAT){const[b]=i,S=!a(this,k).has(b);a(this,k).set(b,Date.now()),a(this,R).emit(S?"peerJoined":"peerHeartbeat",b);return}if(o===L.INTERNAL_OBITUARY){const[b]=i;a(this,k).delete(b)&&a(this,R).emit("peerLeft",b);return}if(c&&p){const b=a(this,A).get(p);b&&(clearTimeout(b.timer),a(this,A).delete(p),typeof J=="string"?b.reject(new Error(String(J))):b.resolve(m));return}if(u){a(this,T).hasLeader().then(async b=>{if(b||(await a(this,T).awaitLeadership(),d(this,l,ye).call(this,a(this,T).isLeader)),a(this,O)){const S=a(this,$).get(o);S&&Promise.resolve(S(...i)).then(pe=>{d(this,l,V).call(this,{event:o,args:[],isAck:!0,replyTo:s,result:pe})}).catch(pe=>{d(this,l,V).call(this,{event:o,args:[],isAck:!0,replyTo:s,error:pe.message})})}});return}if(h&&p){const b=a(this,I).get(p);b&&(b.responses.push(m),d(this,l,_e).call(this,p));return}if(f){const b=a(this,N).get(o);b&&Promise.resolve(b(...i)).then(S=>{d(this,l,V).call(this,{event:o,args:[],isCollectResponse:!0,replyTo:s,result:S})}).catch(S=>{d(this,l,V).call(this,{event:o,args:[],isCollectResponse:!0,replyTo:s,error:S.message})});return}Ne(L.prototype,this,"emit").call(this,o,...i)},ue=function(r,...n){const s={id:F(16),event:r,args:n};a(this,E).postMessage(Y(s)).catch(o=>_.error(o))},lt=function(){d(this,l,ue).call(this,L.INTERNAL_HEARTBEAT,this.id),setInterval(()=>{d(this,l,ue).call(this,L.INTERNAL_HEARTBEAT,this.id)},2e3),setInterval(()=>{const r=Date.now();for(const[n,s]of a(this,k))r-s>6e3&&(a(this,k).delete(n),a(this,R).emit("peerLeft",n))},2e3)},_e=function(r){const n=a(this,I).get(r);if(!n)return;const s=a(this,k).size+1;n.responses.length>=s&&(clearTimeout(n.timer),setTimeout(()=>{a(this,I).delete(r)&&n.resolve(n.responses)},100))},U(L,"INTERNAL_HEARTBEAT","__swarm_heartbeat"),U(L,"INTERNAL_OBITUARY","__swarm_obituary");let we=L;const Fr="1.20250424.0";exports.types=wt.types;exports.errors=ae.errors;exports.Swarm=we;exports.setLogLevel=Tt;exports.version=Fr;
4
+ //# sourceMappingURL=index.cjs.map