@streamr/sdk 103.6.0-rc.0 → 103.7.0-rc.2

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.
@@ -65,7 +65,7 @@ const wI=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff
65
65
  * Copyright 2019 Google LLC
66
66
  * SPDX-License-Identifier: Apache-2.0
67
67
  */
68
- const lU=Symbol("Comlink.proxy"),hU=Symbol("Comlink.endpoint"),dU=Symbol("Comlink.releaseProxy"),fU=Symbol("Comlink.finalizer"),pU=Symbol("Comlink.thrown"),gU=e=>"object"==typeof e&&null!==e||"function"==typeof e,mU=new Map([["proxy",{canHandle:e=>gU(e)&&e[lU],serialize(e){const{port1:t,port2:r}=new MessageChannel;return yU(e,t),[r,[r]]},deserialize:e=>(e.start(),wU(e))}],["throw",{canHandle:e=>gU(e)&&pU in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function yU(e,t=globalThis,r=["*"]){t.addEventListener("message",(function n(i){if(!i||!i.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:s,type:o,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(TU);let u;try{const t=a.slice(0,-1).reduce(((e,t)=>e[t]),e),r=a.reduce(((e,t)=>e[t]),e);switch(o){case"GET":u=r;break;case"SET":t[a.slice(-1)[0]]=TU(i.data.value),u=!0;break;case"APPLY":u=r.apply(t,c);break;case"CONSTRUCT":u=IU(new r(...c));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;yU(e,r),u=function(e,t){return CU.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[pU]:0}}Promise.resolve(u).catch((e=>({value:e,[pU]:0}))).then((r=>{const[i,a]=PU(r);t.postMessage(Object.assign(Object.assign({},i),{id:s}),a),"RELEASE"===o&&(t.removeEventListener("message",n),bU(t),fU in e&&"function"==typeof e[fU]&&e[fU]())})).catch((e=>{const[r,n]=PU({value:new TypeError("Unserializable return value"),[pU]:0});t.postMessage(Object.assign(Object.assign({},r),{id:s}),n)}))})),t.start&&t.start()}function bU(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function wU(e,t){const r=new Map;return e.addEventListener("message",(function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}})),kU(e,r,[],t)}function vU(e){if(e)throw new Error("Proxy has been released and is not useable")}function EU(e){return _U(e,new Map,{type:"RELEASE"}).then((()=>{bU(e)}))}const AU=new WeakMap,SU="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(AU.get(e)||0)-1;AU.set(e,t),0===t&&EU(e)}));function kU(e,t,r=[],n=function(){}){let i=!1;const s=new Proxy(n,{get(n,o){if(vU(i),o===dU)return()=>{!function(e){SU&&SU.unregister(e)}(s),EU(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>s};const n=_U(e,t,{type:"GET",path:r.map((e=>e.toString()))}).then(TU);return n.then.bind(n)}return kU(e,t,[...r,o])},set(n,s,o){vU(i);const[a,c]=PU(o);return _U(e,t,{type:"SET",path:[...r,s].map((e=>e.toString())),value:a},c).then(TU)},apply(n,s,o){vU(i);const a=r[r.length-1];if(a===hU)return _U(e,t,{type:"ENDPOINT"}).then(TU);if("bind"===a)return kU(e,t,r.slice(0,-1));const[c,u]=RU(o);return _U(e,t,{type:"APPLY",path:r.map((e=>e.toString())),argumentList:c},u).then(TU)},construct(n,s){vU(i);const[o,a]=RU(s);return _U(e,t,{type:"CONSTRUCT",path:r.map((e=>e.toString())),argumentList:o},a).then(TU)}});return function(e,t){const r=(AU.get(t)||0)+1;AU.set(t,r),SU&&SU.register(e,t,e)}(s,e),s}function RU(e){const t=e.map(PU);return[t.map((e=>e[0])),(r=t.map((e=>e[1])),Array.prototype.concat.apply([],r))];var r}const CU=new WeakMap;function IU(e){return Object.assign(e,{[lU]:!0})}function PU(e){for(const[t,r]of mU)if(r.canHandle(e)){const[n,i]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},i]}return[{type:"RAW",value:e},CU.get(e)||[]]}function TU(e){switch(e.type){case"HANDLER":return mU.get(e.name).deserialize(e.value);case"RAW":return e.value}}function _U(e,t,r,n){return new Promise((i=>{const s=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");t.set(s,i),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)}))}var NU,MU;var xU,OU,DU,BU,LU="1.0.35";var FU=function(){if(BU)return DU;var e;if(BU=1,"object"==typeof globalThis)e=globalThis;else try{e=function(){if(MU)return NU;MU=1;var e=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};return NU=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(t){return e()}try{return __global__||e()}finally{delete Object.prototype.__global__}}()}()}catch(e){}finally{if(e||"undefined"==typeof window||(e=window),!e)throw new Error("Could not determine global this")}var t=e.WebSocket||e.MozWebSocket,r=OU?xU:(OU=1,xU=LU);function n(e,r){return r?new t(e,r):new t(e)}return t&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(n,e,{get:function(){return t[e]}})})),DU={w3cwebsocket:t?n:null,version:r}}();var UU,jU,qU,zU,KU,GU,VU,HU;function $U(){if(jU)return UU;jU=1;var e=BE();return UU=function(t,r){var n=-1,i=t.length,s=i-1;for(r=void 0===r?i:r;++n<r;){var o=e(n,s),a=t[o];t[o]=t[n],t[n]=a}return t.length=r,t},UU}var WU=function(){if(HU)return VU;HU=1;var e=function(){if(zU)return qU;zU=1;var e=Th(),t=$U();return qU=function(r){return t(e(r))},qU}(),t=function(){if(GU)return KU;GU=1;var e=$U(),t=nA();return KU=function(r){return e(t(r))}}(),r=qu();return VU=function(n){return(r(n)?e:t)(n)}}(),JU=n(WU),QU=function(e,t){return QU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},QU(e,t)};function ZU(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}QU(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}"function"==typeof SuppressedError&&SuppressedError;var YU=function(){function e(e,t,r){void 0===r&&(r=1),this.t=void 0,this.i=void 0,this.h=void 0,this.u=e,this.o=t,this.l=r}return e.prototype.v=function(){var e=this,t=e.h.h===e;if(t&&1===e.l)e=e.i;else if(e.t)for(e=e.t;e.i;)e=e.i;else{if(t)return e.h;for(var r=e.h;r.t===e;)r=(e=r).h;e=r}return e},e.prototype.p=function(){var e=this;if(e.i){for(e=e.i;e.t;)e=e.t;return e}for(var t=e.h;t.i===e;)t=(e=t).h;return e.i!==t?t:e},e.prototype.T=function(){var e=this.h,t=this.i,r=t.t;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.t=this,this.h=t,this.i=r,r&&(r.h=this),t},e.prototype.I=function(){var e=this.h,t=this.t,r=t.i;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.i=this,this.h=t,this.t=r,r&&(r.h=this),t},e}(),XU=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.O=1,t}return ZU(t,e),t.prototype.T=function(){var t=e.prototype.T.call(this);return this.M(),t.M(),t},t.prototype.I=function(){var t=e.prototype.I.call(this);return this.M(),t.M(),t},t.prototype.M=function(){this.O=1,this.t&&(this.O+=this.t.O),this.i&&(this.O+=this.i.O)},t}(YU),ej=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.C===e.C},e}(),tj=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ZU(t,e),t}(function(){function e(){this._=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this._},e.prototype.empty=function(){return 0===this._},e}());function rj(){throw new RangeError("Iterator access denied!")}var nj,ij,sj=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.N=void 0,n.g=t,n.enableIndex=r,n.S=r?XU:YU,n.A=new n.S,n}return ZU(t,e),t.prototype.m=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)e=e.i;else{if(!(n>0))return e;r=e,e=e.t}}return r},t.prototype.B=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<=0?e=e.i:(r=e,e=e.t)}return r},t.prototype.j=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)r=e,e=e.i;else{if(!(n>0))return e;e=e.t}}return r},t.prototype.k=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<0?(r=e,e=e.i):e=e.t}return r},t.prototype.R=function(e){for(;;){var t,r=e.h;if(r===this.A)return;if(1===e.l)return void(e.l=0);if(e===r.t)if(1===(t=r.i).l)t.l=0,r.l=1,r===this.N?this.N=r.T():r.T();else{if(t.i&&1===t.i.l)return t.l=r.l,r.l=0,t.i.l=0,void(r===this.N?this.N=r.T():r.T());t.t&&1===t.t.l?(t.l=1,t.t.l=0,t.I()):(t.l=1,e=r)}else if(1===(t=r.t).l)t.l=0,r.l=1,r===this.N?this.N=r.I():r.I();else{if(t.t&&1===t.t.l)return t.l=r.l,r.l=0,t.t.l=0,void(r===this.N?this.N=r.I():r.I());t.i&&1===t.i.l?(t.l=1,t.i.l=0,t.T()):(t.l=1,e=r)}}},t.prototype.G=function(e){if(1!==this._){for(var t=e;t.t||t.i;){if(t.i)for(t=t.i;t.t;)t=t.t;else t=t.t;var r=e.u;e.u=t.u,t.u=r;var n=e.o;e.o=t.o,t.o=n,e=t}this.A.t===t?this.A.t=t.h:this.A.i===t&&(this.A.i=t.h),this.R(t);var i=t.h;if(t===i.t?i.t=void 0:i.i=void 0,this._-=1,this.N.l=0,this.enableIndex)for(;i!==this.A;)i.O-=1,i=i.h}else this.clear()},t.prototype.P=function(e){for(var t="number"==typeof e?e:void 0,r="function"==typeof e?e:void 0,n=void 0===e?[]:void 0,i=0,s=this.N,o=[];o.length||s;)if(s)o.push(s),s=s.t;else{if(s=o.pop(),i===t)return s;n&&n.push(s),r&&r(s,i,this),i+=1,s=s.i}return n},t.prototype.q=function(e){for(;;){var t=e.h;if(0===t.l)return;var r=t.h;if(t===r.t){if((n=r.i)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.i)return t.l=0,r===this.N?this.N=r.I():r.I(),void(r.l=1);e.l=0,e.t&&(e.t.h=t),e.i&&(e.i.h=r),t.i=e.t,r.t=e.i,e.t=t,e.i=r,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}else{var n,i;if((n=r.t)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.t)return t.l=0,r===this.N?this.N=r.T():r.T(),void(r.l=1);e.l=0,e.t&&(e.t.h=r),e.i&&(e.i.h=t),r.i=e.t,t.t=e.i,e.t=r,e.i=t,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}return void(this.enableIndex&&(t.M(),r.M(),e.M()))}},t.prototype.D=function(e,t,r){if(void 0===this.N)return this._+=1,this.N=new this.S(e,t,0),this.N.h=this.A,this.A.h=this.A.t=this.A.i=this.N,this._;var n,i=this.A.t,s=this.g(i.u,e);if(0===s)return i.o=t,this._;if(s>0)i.t=new this.S(e,t),i.t.h=i,n=i.t,this.A.t=n;else{var o=this.A.i,a=this.g(o.u,e);if(0===a)return o.o=t,this._;if(a<0)o.i=new this.S(e,t),o.i.h=o,n=o.i,this.A.i=n;else{if(void 0!==r){var c=r.C;if(c!==this.A){var u=this.g(c.u,e);if(0===u)return c.o=t,this._;if(u>0){var l=c.v(),h=this.g(l.u,e);if(0===h)return l.o=t,this._;h<0&&(n=new this.S(e,t),void 0===l.i?(l.i=n,n.h=l):(c.t=n,n.h=c))}}}if(void 0===n)for(n=this.N;;){var d=this.g(n.u,e);if(d>0){if(void 0===n.t){n.t=new this.S(e,t),n.t.h=n,n=n.t;break}n=n.t}else{if(!(d<0))return n.o=t,this._;if(void 0===n.i){n.i=new this.S(e,t),n.i.h=n,n=n.i;break}n=n.i}}}}if(this.enableIndex)for(var f=n.h;f!==this.A;)f.O+=1,f=f.h;return this.q(n),this._+=1,this._},t.prototype.F=function(e,t){for(;e;){var r=this.g(e.u,t);if(r<0)e=e.i;else{if(!(r>0))return e;e=e.t}}return e||this.A},t.prototype.clear=function(){this._=0,this.N=void 0,this.A.h=void 0,this.A.t=this.A.i=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.C;if(r===this.A&&rj(),1===this._)return r.u=t,!0;var n=r.p().u;if(r===this.A.t)return this.g(n,t)>0&&(r.u=t,!0);var i=r.v().u;return r===this.A.i?this.g(i,t)<0&&(r.u=t,!0):!(this.g(i,t)>=0||this.g(n,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return this.G(t),this._},t.prototype.eraseElementByKey=function(e){if(0===this._)return!1;var t=this.F(this.N,e);return t!==this.A&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.C;t===this.A&&rj();var r=void 0===t.i;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.t||e.next(),this.G(t),e},t.prototype.getHeight=function(){if(0===this._)return 0;return function e(t){return t?Math.max(e(t.t),e(t.i))+1:0}(this.N)},t}(tj),oj=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.C=t,i.A=r,0===i.iteratorType?(i.pre=function(){return this.C===this.A.t&&rj(),this.C=this.C.v(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.p(),this}):(i.pre=function(){return this.C===this.A.i&&rj(),this.C=this.C.p(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.v(),this}),i}return ZU(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.C,t=this.A.h;if(e===this.A)return t?t.O-1:0;var r=0;for(e.t&&(r+=e.t.O);e!==t;){var n=e.h;e===n.i&&(r+=1,n.t&&(r+=n.t.O)),e=n}return r},enumerable:!1,configurable:!0}),t.prototype.isAccessible=function(){return this.C!==this.A},t}(ej),aj=function(e){function t(t,r,n,i){var s=e.call(this,t,r,i)||this;return s.container=n,s}return ZU(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){this.C===this.A&&rj();var e=this;return new Proxy([],{get:function(t,r){return"0"===r?e.C.u:"1"===r?e.C.o:(t[0]=e.C.u,t[1]=e.C.o,t[r])},set:function(t,r,n){if("1"!==r)throw new TypeError("prop must be 1");return e.C.o=n,!0}})},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.C,this.A,this.container,this.iteratorType)},t}(oj),cj=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,s=i;return t.forEach((function(e){s.setElement(e[0],e[1])})),i}return ZU(t,e),t.prototype.begin=function(){return new aj(this.A.t||this.A,this.A,this)},t.prototype.end=function(){return new aj(this.A,this.A,this)},t.prototype.rBegin=function(){return new aj(this.A.i||this.A,this.A,this,1)},t.prototype.rEnd=function(){return new aj(this.A,this.A,this,1)},t.prototype.front=function(){if(0!==this._){var e=this.A.t;return[e.u,e.o]}},t.prototype.back=function(){if(0!==this._){var e=this.A.i;return[e.u,e.o]}},t.prototype.lowerBound=function(e){var t=this.m(this.N,e);return new aj(t,this.A,this)},t.prototype.upperBound=function(e){var t=this.B(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseLowerBound=function(e){var t=this.j(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseUpperBound=function(e){var t=this.k(this.N,e);return new aj(t,this.A,this)},t.prototype.forEach=function(e){this.P((function(t,r,n){e([t.u,t.o],r,n)}))},t.prototype.setElement=function(e,t,r){return this.D(e,t,r)},t.prototype.getElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return[t.u,t.o]},t.prototype.find=function(e){var t=this.F(this.N,e);return new aj(t,this.A,this)},t.prototype.getElementByKey=function(e){return this.F(this.N,e).o},t.prototype.union=function(e){var t=this;return e.forEach((function(e){t.setElement(e[0],e[1])})),this._},t.prototype[Symbol.iterator]=function(){var e,t,r,n;return function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}}(this,(function(i){switch(i.label){case 0:e=this._,t=this.P(),r=0,i.label=1;case 1:return r<e?[4,[(n=t[r]).u,n.o]]:[3,4];case 2:i.sent(),i.label=3;case 3:return++r,[3,1];case 4:return[2]}}))},t}(sj);function uj(){if(ij)return nj;return ij=1,nj=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0},nj}var lj,hj,dj,fj,pj,gj,mj,yj,bj=n(uj());function wj(){if(fj)return dj;fj=1;var e=Jc(),t=Hc(),r=(hj||(hj=1,lj=function(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}),lj),n=Qc(),i=Th(),s=Array.prototype.splice;return dj=function(o,a,c,u){var l=u?r:t,h=-1,d=a.length,f=o;for(o===a&&(a=i(a)),c&&(f=e(o,n(c)));++h<d;)for(var p=0,g=a[h],m=c?c(g):g;(p=l(f,m,p,u))>-1;)f!==o&&s.call(f,p,1),s.call(o,p,1);return o},dj}var vj=function(){if(yj)return mj;yj=1;var e=nu(),t=function(){if(gj)return pj;gj=1;var e=wj();return pj=function(t,r){return t&&t.length&&r&&r.length?e(t,r):t},pj}(),r=e(t);return mj=r}(),Ej=n(vj);const Aj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,Sj=new Set,kj="object"==typeof process&&process?process:{},Rj=(e,t,r,n)=>{"function"==typeof kj.emitWarning?kj.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let Cj=globalThis.AbortController,Ij=globalThis.AbortSignal;if(void 0===Cj){Ij=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Cj=class{constructor(){t()}signal=new Ij;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==kj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,Rj("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const Pj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Tj=e=>Pj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?_j:null:null;class _j extends Array{constructor(e){super(e),this.fill(0)}}class Nj{heap;length;static#Lt=!1;static create(e){const t=Tj(e);if(!t)return[];Nj.#Lt=!0;const r=new Nj(e,t);return Nj.#Lt=!1,r}constructor(e,t){if(!Nj.#Lt)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Mj{#Ft;#Ut;#jt;#qt;#zt;#Kt;#Gt;#Vt;get perf(){return this.#Vt}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Ht;#$t;#Wt;#Jt;#Qt;#Zt;#Yt;#Xt;#er;#tr;#rr;#nr;#ir;#sr;#or;#ar;#cr;#ur;static unsafeExposeInternals(e){return{starts:e.#ir,ttls:e.#sr,sizes:e.#nr,keyMap:e.#Wt,keyList:e.#Jt,valList:e.#Qt,next:e.#Zt,prev:e.#Yt,get head(){return e.#Xt},get tail(){return e.#er},free:e.#tr,isBackgroundFetch:t=>e.#lr(t),backgroundFetch:(t,r,n,i)=>e.#hr(t,r,n,i),moveToTail:t=>e.#dr(t),indexes:t=>e.#fr(t),rindexes:t=>e.#pr(t),isStale:t=>e.#gr(t)}}get max(){return this.#Ft}get maxSize(){return this.#Ut}get calculatedSize(){return this.#$t}get size(){return this.#Ht}get fetchMethod(){return this.#Kt}get memoMethod(){return this.#Gt}get dispose(){return this.#jt}get onInsert(){return this.#qt}get disposeAfter(){return this.#zt}constructor(e){const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:o,allowStale:a,dispose:c,onInsert:u,disposeAfter:l,noDisposeOnSet:h,noUpdateTTL:d,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:g,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:A,perf:S}=e;if(void 0!==S&&"function"!=typeof S?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#Vt=S??Aj,0!==t&&!Pj(t))throw new TypeError("max option must be a nonnegative integer");const k=t?Tj(t):Array;if(!k)throw new Error("invalid max value: "+t);if(this.#Ft=t,this.#Ut=f,this.maxEntrySize=p||this.#Ut,this.sizeCalculation=g,this.sizeCalculation){if(!this.#Ut&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==y&&"function"!=typeof y)throw new TypeError("memoMethod must be a function if defined");if(this.#Gt=y,void 0!==m&&"function"!=typeof m)throw new TypeError("fetchMethod must be a function if specified");if(this.#Kt=m,this.#ar=!!m,this.#Wt=new Map,this.#Jt=new Array(t).fill(void 0),this.#Qt=new Array(t).fill(void 0),this.#Zt=new k(t),this.#Yt=new k(t),this.#Xt=0,this.#er=0,this.#tr=Nj.create(t),this.#Ht=0,this.#$t=0,"function"==typeof c&&(this.#jt=c),"function"==typeof u&&(this.#qt=u),"function"==typeof l?(this.#zt=l,this.#rr=[]):(this.#zt=void 0,this.#rr=void 0),this.#or=!!this.#jt,this.#ur=!!this.#qt,this.#cr=!!this.#zt,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#Ut&&!Pj(this.#Ut))throw new TypeError("maxSize must be a positive integer if specified");if(!Pj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#mr()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!o,this.ttlResolution=Pj(n)||0===n?n:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Pj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#yr()}if(0===this.#Ft&&0===this.ttl&&0===this.#Ut)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Ft&&!this.#Ut){const e="LRU_CACHE_UNBOUNDED";if((e=>!Sj.has(e))(e)){Sj.add(e);Rj("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,Mj)}}}getRemainingTTL(e){return this.#Wt.has(e)?1/0:0}#yr(){const e=new _j(this.#Ft),t=new _j(this.#Ft);this.#sr=e,this.#ir=t,this.#br=(r,n,i=this.#Vt.now())=>{if(t[r]=0!==n?i:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{this.#gr(r)&&this.#wr(this.#Jt[r],"expire")}),n+1);e.unref&&e.unref()}},this.#vr=r=>{t[r]=0!==e[r]?this.#Vt.now():0},this.#Er=(i,s)=>{if(e[s]){const o=e[s],a=t[s];if(!o||!a)return;i.ttl=o,i.start=a,i.now=r||n();const c=i.now-a;i.remainingTTL=o-c}};let r=0;const n=()=>{const e=this.#Vt.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const s=this.#Wt.get(i);if(void 0===s)return 0;const o=e[s],a=t[s];if(!o||!a)return 1/0;return o-((r||n())-a)},this.#gr=i=>{const s=t[i],o=e[i];return!!o&&!!s&&(r||n())-s>o}}#vr=()=>{};#Er=()=>{};#br=()=>{};#gr=()=>!1;#mr(){const e=new _j(this.#Ft);this.#$t=0,this.#nr=e,this.#Ar=t=>{this.#$t-=e[t],e[t]=0},this.#Sr=(e,t,r,n)=>{if(this.#lr(t))return 0;if(!Pj(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!Pj(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#kr=(t,r,n)=>{if(e[t]=r,this.#Ut){const r=this.#Ut-e[t];for(;this.#$t>r;)this.#Rr(!0)}this.#$t+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#$t)}}#Ar=e=>{};#kr=(e,t,r)=>{};#Sr=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#fr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#er;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#Xt);)t=this.#Yt[t]}*#pr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#Xt;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#er);)t=this.#Zt[t]}#Cr(e){return void 0!==e&&this.#Wt.get(this.#Jt[e])===e}*entries(){for(const e of this.#fr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*rentries(){for(const e of this.#pr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*keys(){for(const e of this.#fr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*rkeys(){for(const e of this.#pr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*values(){for(const e of this.#fr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}*rvalues(){for(const e of this.#pr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#Jt[r],this))return this.get(this.#Jt[r],t)}}forEach(e,t=this){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}rforEach(e,t=this){for(const r of this.#pr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}purgeStale(){let e=!1;for(const t of this.#pr({allowStale:!0}))this.#gr(t)&&(this.#wr(this.#Jt[t],"expire"),e=!0);return e}info(e){const t=this.#Wt.get(e);if(void 0===t)return;const r=this.#Qt[t],n=this.#lr(r)?r.__staleWhileFetching:r;if(void 0===n)return;const i={value:n};if(this.#sr&&this.#ir){const e=this.#sr[t],r=this.#ir[t];if(e&&r){const t=e-(this.#Vt.now()-r);i.ttl=t,i.start=Date.now()}}return this.#nr&&(i.size=this.#nr[t]),i}dump(){const e=[];for(const t of this.#fr({allowStale:!0})){const r=this.#Jt[t],n=this.#Qt[t],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0===i||void 0===r)continue;const s={value:i};if(this.#sr&&this.#ir){s.ttl=this.#sr[t];const e=this.#Vt.now()-this.#ir[t];s.start=Math.floor(Date.now()-e)}this.#nr&&(s.size=this.#nr[t]),e.unshift([r,s])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#Vt.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const u=this.#Sr(e,t,r.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#wr(e,"set"),this;let l=0===this.#Ht?void 0:this.#Wt.get(e);if(void 0===l)l=0===this.#Ht?this.#er:0!==this.#tr.length?this.#tr.pop():this.#Ht===this.#Ft?this.#Rr(!1):this.#Ht,this.#Jt[l]=e,this.#Qt[l]=t,this.#Wt.set(e,l),this.#Zt[this.#er]=l,this.#Yt[l]=this.#er,this.#er=l,this.#Ht++,this.#kr(l,u,a),a&&(a.set="add"),c=!1,this.#ur&&this.#qt?.(t,e,"add");else{this.#dr(l);const r=this.#Qt[l];if(t!==r){if(this.#ar&&this.#lr(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||s||(this.#or&&this.#jt?.(t,e,"set"),this.#cr&&this.#rr?.push([t,e,"set"]))}else s||(this.#or&&this.#jt?.(r,e,"set"),this.#cr&&this.#rr?.push([r,e,"set"]));if(this.#Ar(l),this.#kr(l,u,a),this.#Qt[l]=t,a){a.set="replace";const e=r&&this.#lr(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#ur&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#sr||this.#yr(),this.#sr&&(c||this.#br(l,n,i),a&&this.#Er(a,l)),!s&&this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return this}pop(){try{for(;this.#Ht;){const e=this.#Qt[this.#Xt];if(this.#Rr(!0),this.#lr(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}#Rr(e){const t=this.#Xt,r=this.#Jt[t],n=this.#Qt[t];return this.#ar&&this.#lr(n)?n.__abortController.abort(new Error("evicted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(n,r,"evict"),this.#cr&&this.#rr?.push([n,r,"evict"])),this.#Ar(t),e&&(this.#Jt[t]=void 0,this.#Qt[t]=void 0,this.#tr.push(t)),1===this.#Ht?(this.#Xt=this.#er=0,this.#tr.length=0):this.#Xt=this.#Zt[t],this.#Wt.delete(r),this.#Ht--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#Wt.get(e);if(void 0!==i){const e=this.#Qt[i];if(this.#lr(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#gr(i))return r&&this.#vr(i),n&&(n.has="hit",this.#Er(n,i)),!0;n&&(n.has="stale",this.#Er(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#Wt.get(e);if(void 0===n||!r&&this.#gr(n))return;const i=this.#Qt[n];return this.#lr(i)?i.__staleWhileFetching:i}#hr(e,t,r,n){const i=void 0===t?void 0:this.#Qt[t];if(this.#lr(i))return i;const s=new Cj,{signal:o}=r;o?.addEventListener("abort",(()=>s.abort(o.reason)),{signal:s.signal});const a={signal:s.signal,options:r,context:n},c=(n,i=!1)=>{const{aborted:o}=s.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(o&&!i?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),o&&!c&&!i)return u(s.signal.reason);const h=l,d=this.#Qt[t];return(d===l||c&&i&&void 0===d)&&(void 0===n?void 0!==h.__staleWhileFetching?this.#Qt[t]=h.__staleWhileFetching:this.#wr(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,a.options))),n},u=n=>{const{aborted:i}=s.signal,o=i&&r.allowStaleOnFetchAbort,a=o||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,u=l;if(this.#Qt[t]===l){!c||void 0===u.__staleWhileFetching?this.#wr(e,"fetch"):o||(this.#Qt[t]=u.__staleWhileFetching)}if(a)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const l=new Promise(((t,n)=>{const o=this.#Kt?.(e,i,a);o&&o instanceof Promise&&o.then((e=>t(void 0===e?void 0:e)),n),s.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),h=Object.assign(l,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...a.options,status:void 0}),t=this.#Wt.get(e)):this.#Qt[t]=h,h}#lr(e){if(!this.#ar)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Cj}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:p,forceRefresh:g=!1,status:m,signal:y}=t;if(!this.#ar)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const b={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:d,status:m,signal:y};let w=this.#Wt.get(e);if(void 0===w){m&&(m.fetch="miss");const t=this.#hr(e,w,b,p);return t.__returned=t}{const t=this.#Qt[w];if(this.#lr(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#gr(w);if(!g&&!i)return m&&(m.fetch="hit"),this.#dr(w),n&&this.#vr(w),m&&this.#Er(m,w),t;const s=this.#hr(e,w,b,p),o=void 0!==s.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",o&&i&&(m.returnedStale=!0)),o?s.__staleWhileFetching:s.__returned=s}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#Gt;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...s}=t,o=this.get(e,s);if(!i&&void 0!==o)return o;const a=r(e,o,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,o=this.#Wt.get(e);if(void 0!==o){const t=this.#Qt[o],a=this.#lr(t);return s&&this.#Er(s,o),this.#gr(o)?(s&&(s.get="stale"),a?(s&&r&&void 0!==t.__staleWhileFetching&&(s.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#wr(e,"expire"),s&&r&&(s.returnedStale=!0),r?t:void 0)):(s&&(s.get="hit"),a?t.__staleWhileFetching:(this.#dr(o),n&&this.#vr(o),t))}s&&(s.get="miss")}#Et(e,t){this.#Yt[t]=e,this.#Zt[e]=t}#dr(e){e!==this.#er&&(e===this.#Xt?this.#Xt=this.#Zt[e]:this.#Et(this.#Yt[e],this.#Zt[e]),this.#Et(this.#er,e),this.#er=e)}delete(e){return this.#wr(e,"delete")}#wr(e,t){let r=!1;if(0!==this.#Ht){const n=this.#Wt.get(e);if(void 0!==n)if(r=!0,1===this.#Ht)this.#Ir(t);else{this.#Ar(n);const r=this.#Qt[n];if(this.#lr(r)?r.__abortController.abort(new Error("deleted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(r,e,t),this.#cr&&this.#rr?.push([r,e,t])),this.#Wt.delete(e),this.#Jt[n]=void 0,this.#Qt[n]=void 0,n===this.#er)this.#er=this.#Yt[n];else if(n===this.#Xt)this.#Xt=this.#Zt[n];else{const e=this.#Yt[n];this.#Zt[e]=this.#Zt[n];const t=this.#Zt[n];this.#Yt[t]=this.#Yt[n]}this.#Ht--,this.#tr.push(n)}}if(this.#cr&&this.#rr?.length){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return r}clear(){return this.#Ir("delete")}#Ir(e){for(const t of this.#pr({allowStale:!0})){const r=this.#Qt[t];if(this.#lr(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#Jt[t];this.#or&&this.#jt?.(r,n,e),this.#cr&&this.#rr?.push([r,n,e])}}if(this.#Wt.clear(),this.#Qt.fill(void 0),this.#Jt.fill(void 0),this.#sr&&this.#ir&&(this.#sr.fill(0),this.#ir.fill(0)),this.#nr&&this.#nr.fill(0),this.#Xt=0,this.#er=0,this.#tr.length=0,this.#$t=0,this.#Ht=0,this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}var xj,Oj={exports:{}};var Dj=(xj||(xj=1,function(e){var t,r,n,i=(t={km:6371,mile:3960,meter:6371e3,nmi:3440},r=function(e){return e*Math.PI/180},n=function(e,t){switch(e){case"[lat,lon]":return{latitude:t[0],longitude:t[1]};case"[lon,lat]":return{latitude:t[1],longitude:t[0]};case"{lon,lat}":return{latitude:t.lat,longitude:t.lon};case"{lat,lng}":return{latitude:t.lat,longitude:t.lng};case"geojson":return{latitude:t.geometry.coordinates[1],longitude:t.geometry.coordinates[0]};default:return t}},function(e,i,s){var o=(s=s||{}).unit in t?t[s.unit]:t.km,a=n(s.format,e),c=n(s.format,i),u=r(c.latitude-a.latitude),l=r(c.longitude-a.longitude),h=r(a.latitude),d=r(c.latitude),f=Math.sin(u/2)*Math.sin(u/2)+Math.sin(l/2)*Math.sin(l/2)*Math.cos(h)*Math.cos(d),p=2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f));return s.threshold?s.threshold>o*p:o*p});e.exports&&(e.exports=i)}(Oj)),Oj.exports),Bj=n(Dj);const Lj={JFK:[100,40.639447,-73.779317],LGA:[200,40.777199,-73.872597],EWR:[300,40.692501,-74.168701],BUF:[400,42.94049835,-78.73220062],BFI:[500,47.529999,-122.302002],SEA:[600,47.449162,-122.311134],PDX:[700,45.58869934,-122.5979996],HIO:[800,45.540401,-122.949997],SMF:[900,38.69540023803711,-121.59100341796875],SFO:[1e3,37.61899948120117,-122.375],PAO:[1100,37.461101532,-122.114997864],SJC:[1200,37.362452,-121.929188],WVI:[1300,36.9356994629,-121.790000916],BUR:[1400,34.197703,-118.356378],LAX:[1500,33.942501,-118.407997],SAN:[1600,32.7336006165,-117.190002441],LAS:[1700,36.083361,-115.151817],PHX:[1800,33.435302,-112.005905],ABQ:[1900,35.040199,-106.609001],DEN:[2e3,39.861698150635,-104.672996521],SLC:[2100,40.785749,-111.979746],STP:[2200,44.93479,-93.060036],MSP:[2300,44.882,-93.221802],FSD:[2400,43.585463,-96.741152],OMA:[2500,41.3032,-95.894096],MCI:[2600,39.2976,-94.713898],OKC:[2700,35.393101,-97.6007],ADS:[2800,32.9686012268,-96.8364028931],DFW:[2900,32.896801,-97.038002],IAH:[3e3,29.984399795532227,-95.34140014648438],AUS:[3100,30.197535,-97.662015],SAT:[3200,29.533701,-98.469803],MFE:[3300,26.176141,-98.237965],HNL:[3400,21.32062,-157.924228],ANC:[3500,61.1744,-149.996002],BOS:[3600,42.3643,-71.005203],BGR:[3700,44.8074,-68.828102],YTO:[3800,43.6772,-79.6306],YYZ:[3900,43.6772,-79.6306],YOW:[4e3,45.322498,-75.669197],YUL:[4100,45.4706,-73.740799],YHZ:[4200,44.8807983398,-63.5085983276],YVR:[4300,49.193901062,-123.183998108],YYC:[4400,51.113899231,-114.019996643],YXE:[4500,52.170799255371094,-106.69999694824219],YWG:[4600,49.909999847399995,-97.2398986816],KEF:[4700,63.985001,-22.6056],DUB:[4800,53.428713,-6.262121],ORK:[4900,51.841301,-8.49111],MAN:[5e3,53.349375,-2.279521],LHR:[5100,51.4706,-.461941],LON:[5200,51.4706,-.461941],LCY:[5300,51.505299,.055278],EDI:[5400,55.950145,-3.372288],BRU:[5500,50.901402,4.48444],AMS:[5600,52.308601,4.76389],DUS:[5700,51.289501,6.76678],FRA:[5800,50.036521,8.561268],WIE:[5900,50.049800872802734,8.325400352478027],STR:[6e3,48.689899,9.22196],MUC:[6100,48.353802,11.7861],TXL:[6200,52.362247,13.500672],HAM:[6300,53.630402,9.98823],LUX:[6400,49.6233333,6.2044444],DLP:[6500,49.012798,2.55],CDG:[6600,49.012798,2.55],PAR:[6700,49.012798,2.55],BOD:[6800,44.8283,-.715556],MRS:[6900,43.438088,5.2125],LYS:[7e3,45.725556,5.081111],GVA:[7100,46.238098,6.10895],ZRH:[7200,47.458056,8.548056],MXP:[7300,45.6306,8.72811],LIN:[7400,45.445099,9.27674],FCO:[7500,41.804532,12.251998],PMO:[7600,38.175999,13.091],PRG:[7700,50.103514,14.256992],CPH:[7800,55.617900848389,12.656000137329],OSL:[7900,60.193901,11.1004],ARN:[8e3,59.651901245117,17.918600082397],BMA:[8100,59.354400634765625,17.941699981689453],GOT:[8200,57.662799835205,12.279800415039],RIX:[8300,56.923599,23.9711],TLL:[8400,59.41329956049999,24.832799911499997],HEL:[8500,60.3172,24.963301],LED:[8600,59.80030059814453,30.262500762939453],KLD:[8700,56.82469940185547,35.7577018737793],DME:[8800,55.40879821777344,37.90629959106445],SVX:[8900,56.743099212646,60.802700042725],KJA:[9e3,56.173077,92.492437],KHV:[9100,48.528338,135.188588],MSQ:[9200,53.888071,28.039964],VNO:[9300,54.634102,25.285801],WAW:[9400,52.1656990051,20.967100143399996],KBP:[9500,50.345001,30.894699],KIV:[9600,46.9277,28.931],OTP:[9700,44.572127,26.103396],IST:[9800,41.261297,28.741951],ADB:[9900,38.2924,27.157],ATH:[1e4,37.936401,23.9445],SKG:[10100,40.51928,22.970009],SOF:[10200,42.696357,23.417671],TIA:[10300,41.4147,19.7206],BEG:[10400,44.818401,20.309099],BUD:[10500,47.43018,19.262393],BTS:[10600,48.1702,17.2127],VIE:[10700,48.110298,16.5697],ZAG:[10800,45.742901,16.0688],TUN:[10900,36.851002,10.2272],AAE:[11e3,36.826781,7.81334],ALG:[11100,36.693886,3.214531],ORN:[11200,35.623901,-.621183],MAD:[11300,40.471926,-3.56264],BCN:[11400,41.2971,2.07846],LIS:[11500,38.7813,-9.13592],CMN:[11600,33.3675,-7.58997],DKR:[11700,14.7397,-17.4902],OUA:[11800,12.3532,-1.51242],ACC:[11900,5.605189800262451,-.16678600013256073],LOS:[12e3,6.5773701667785645,3.321160078048706],FIH:[12100,-4.38575,15.4446],LAD:[12200,-8.85837,13.2312],CPT:[12300,-33.9648017883,18.6016998291],DUR:[12400,-29.6144444444,31.1197222222],JNB:[12500,-26.1392,28.246],MPM:[12600,-25.920799,32.572601],GBE:[12700,-24.555201,25.9182],HRE:[12800,-17.931801,31.0928],TNR:[12900,-18.7969,47.478802],RUN:[13e3,-20.890087,55.518894],MRU:[13100,-20.430201,57.683601],DAR:[13200,-6.87811,39.202599],MBA:[13300,-4.03483,39.5942],NBO:[13400,-1.31923997402,36.9277992249],KGL:[13500,-1.96863,30.1395],JIB:[13600,11.5473,43.1595],CAI:[13700,30.111534,31.396694],TLV:[13800,32.011398,34.8867],HFA:[13900,32.80939865112305,35.04309844970703],ZDM:[14e3,31.91123,35.20756],AMM:[14100,31.7226009369,35.9931983948],BEY:[14200,33.820899963378906,35.488399505615234],LCA:[14300,34.875099,33.624901],EVN:[14400,40.1473007202,44.3959007263],TBS:[14500,41.669201,44.9547],GYD:[14600,40.467498779296875,50.04669952392578],LLK:[14700,38.757919,48.807042],EBL:[14800,36.23759841918945,43.963199615478516],ISU:[14900,35.5617485046,45.316738128699996],BGW:[15e3,33.262501,44.2346],NJF:[15100,31.989853,44.404317],XNH:[15200,30.935801,46.090099],BSR:[15300,30.549101,47.662102],KWI:[15400,29.226601,47.968899],RUH:[15500,24.9576,46.698799],DMM:[15600,26.471200942993164,49.79790115356445],JED:[15700,21.6796,39.156502],BAH:[15800,26.267295,50.63764],DOH:[15900,25.273056,51.608056],DXB:[16e3,25.2527999878,55.3643989563],FJR:[16100,25.1122,56.324001],MCT:[16200,23.593299865722656,58.284400939941406],MLE:[16300,4.191830158233643,73.52909851074219],CMB:[16400,7.180759906768799,79.88410186767578],MAA:[16500,12.990005,80.169296],BLR:[16600,13.1979,77.706299],HYD:[16700,17.231318,78.429855],NAG:[16800,21.092199,79.047203],BBI:[16900,20.244400024399997,85.8178024292],CCU:[17e3,22.654699325561523,88.44670104980469],AMD:[17100,23.0772,72.634697],BOM:[17200,19.0886993408,72.8678970337],PNQ:[17300,18.5821,73.919701],CNN:[17400,11.918614,75.547211],COK:[17500,10.152,76.401901],PAT:[17600,25.591299,85.087997],KNU:[17700,26.404301,80.410103],DEL:[17800,28.55563,77.09519],IXC:[17900,30.6735,76.788498],JSR:[18e3,23.1838,89.160797],CGP:[18100,22.249599,91.813301],DAC:[18200,23.843347,90.397783],PBH:[18300,27.4032,89.424599],KTM:[18400,27.6966,85.3591],LHE:[18500,31.521601,74.403603],ISB:[18600,33.549,72.82566],KHI:[18700,24.9065,67.160797],TAS:[18800,41.257900238,69.2811965942],ALA:[18900,43.354267,77.042828],ULN:[19e3,47.843102,106.766998],ICN:[19100,37.46910095214844,126.45099639892578],TYO:[19200,35.764702,140.386002],NRT:[19300,35.764702,140.386002],HND:[19400,35.552299,139.779999],ITM:[19500,34.785499572753906,135.43800354003906],KIX:[19600,34.427299,135.244003],FUK:[19700,33.585899353027344,130.4510040283203],OKA:[19800,26.195801,127.646004],GUM:[19900,13.4834,144.796005],CGY:[2e4,8.612203,124.456496],CEB:[20100,10.309261,123.97974],MNL:[20200,14.5086,121.019997],BWN:[20300,4.9442,114.928001],SGN:[20400,10.8188,106.652],HAN:[20500,21.221201,105.806999],PNH:[20600,11.5466,104.844002],VTE:[20700,17.988300323500003,102.56300354],MFM:[20800,22.149599,113.592003],HKG:[20900,22.308901,113.915001],KHH:[21e3,22.577101,120.349998],TPE:[21100,25.0777,121.233002],FOC:[21200,25.934669,119.66318],HYN:[21300,28.562201,121.429001],HGH:[21400,30.23609,120.428865],SHA:[21500,31.198104,121.33426],CZX:[21600,31.919701,119.778999],WHU:[21700,31.3906,118.408997],KHN:[21800,28.864815,115.90271],CGD:[21900,28.9189,111.639999],KWE:[22e3,26.541466,106.803331],KMG:[22100,25.110313,102.936743],LHW:[22200,36.515202,103.620003],ZHY:[22300,37.573125,105.154454],SJW:[22400,38.280701,114.696999],PKX:[22500,39.509945,116.41092],BJS:[22600,40.080101013183594,116.58499908447266],TSN:[22700,39.124401092499994,117.346000671],TNA:[22800,36.857201,117.216003],TAO:[22900,36.361953,120.088171],HAK:[23e3,19.9349,110.459],FUO:[23100,23.0833,113.07],ZGN:[23200,23.392401,113.299004],CAN:[23300,23.392401,113.299004],SZX:[23400,22.639299,113.810997],MDL:[23500,21.702199935913086,95.97789764404297],RGN:[23600,16.907300949099998,96.1332015991],CNX:[23700,18.766799926799997,98.962600708],BKK:[23800,13.681099891662598,100.74700164794922],URT:[23900,9.13259983063,99.135597229],KUL:[24e3,2.74558,101.709999],JHB:[24100,1.64131,103.669998],QPG:[24200,1.36042,103.910004],SIN:[24300,1.35019,103.994003],CGK:[24400,-6.1255698204,106.65599823],JOG:[24500,-7.78818,110.431999],DPS:[24600,-8.74817,115.167],DEX:[24700,-4.8557,139.482006],PER:[24800,-31.94029998779297,115.96700286865234],ADL:[24900,-34.947512,138.533393],MEL:[25e3,-37.673302,144.843002],HBA:[25100,-42.836101532,147.509994507],CBR:[25200,-35.3069,149.195007],SYD:[25300,-33.94609832763672,151.177001953125],BNE:[25400,-27.384199142456055,153.11700439453125],CHC:[25500,-43.48939895629883,172.53199768066406],WLG:[25600,-41.3272018433,174.804992676],AKL:[25700,-37.01199,174.786331],NOU:[25800,-22.014601,166.212997],SUV:[25900,-18.04330062866211,178.5590057373047],PPT:[26e3,-17.553699,-149.606995],GDL:[26100,20.52504,-103.301557],QRO:[26200,20.6173,-100.185997],MEX:[26300,19.435433,-99.082432],GUA:[26400,14.5833,-90.527496],TGU:[26500,14.0609,-87.217201],SJO:[26600,9.99386,-84.208801],PTY:[26700,9.0713596344,-79.3834991455],MDE:[26800,6.16454,-75.4231],BOG:[26900,4.70159,-74.1469],UIO:[27e3,-.125399,-78.354306],GYE:[27100,-2.15742,-79.883598],LIM:[27200,-12.0219,-77.114305],ARI:[27300,-18.348499,-70.338699],SCL:[27400,-33.393001556396484,-70.78579711914062],COR:[27500,-31.323601,-64.208],NQN:[27600,-38.949001,-68.155701],EZE:[27700,-34.8222,-58.5358],ASU:[27800,-25.240156,-57.519227],CGB:[27900,-15.6529,-56.116699],GYN:[28e3,-16.632,-49.220699],BSB:[28100,-15.869167,-47.920834],UDI:[28200,-18.883579,-48.225936],SJP:[28300,-20.817113,-49.406963],RAO:[28400,-21.134314,-47.774053],VCP:[28500,-23.007404,-47.134502],SOD:[28600,-23.478001,-47.490002],GRU:[28700,-23.431944,-46.467778],QWJ:[28800,-23.431944,-46.467778],SJK:[28900,-23.2292,-45.8615],GIG:[29e3,-22.809999,-43.250557],CNF:[29100,-19.63571,-43.966928],CAW:[29200,-21.698299,-41.301701],VIX:[29300,-20.258,-40.285],SSA:[29400,-12.908611,-38.322498],REC:[29500,-8.125984,-34.923316],JDO:[29600,-7.21932,-39.269096],FOR:[29700,-3.775833,-38.532222],BEL:[29800,-1.379279,-48.476207],MAO:[29900,-3.03861,-60.049702],POA:[3e4,-29.994712,-51.166592],FLN:[30100,-27.670279,-48.552502],ITJ:[30200,-26.879431,-48.650979],NVT:[30300,-26.879431,-48.650979],BNU:[30400,-26.831661,-49.093569],JOI:[30500,-26.224501,-48.797401],CWB:[30600,-25.5285,-49.1758],CFC:[30700,-26.787423,-50.939942],XAP:[30800,-27.134199,-52.656601],PBM:[30900,5.45283,-55.187801],GEO:[31e3,6.49855,-58.254101],BGI:[31100,13.0746,-59.4925],GND:[31200,12.0042,-61.786201],CUR:[31300,12.1889,-68.959801],SDQ:[31400,18.42970085144,-69.668899536133],STI:[31500,19.406099319458008,-70.60469818115234],KIN:[31600,17.935699462890625,-76.7874984741211],MIA:[31700,25.79319953918457,-80.29060363769531],TPA:[31800,27.975500106811523,-82.533203125],GNV:[31900,29.6900997162,-82.2717971802],JAX:[32e3,30.49410057067871,-81.68789672851562],TLH:[32100,30.3965,-84.350304],MGM:[32200,32.300598,-86.393997],ATL:[32300,33.6367,-84.428101],PDK:[32400,33.8755989075,-84.3020019531],BNA:[32500,36.1245002746582,-86.6781997680664],MEM:[32600,35.04240036010742,-89.97669982910156],STL:[32700,38.748697,-90.370003],IND:[32800,39.7173,-86.294403],CHI:[32900,41.9786,-87.9048],ORD:[33e3,41.9786,-87.9048],DTW:[33100,42.212398529052734,-83.35340118408203],CLE:[33200,41.411701,-81.8498],PIT:[33300,40.49150085,-80.23290253],CMH:[33400,39.998001,-82.891899],LCK:[33500,39.813801,-82.927803],CLT:[33600,35.2140007019043,-80.94309997558594],RDU:[33700,35.877602,-78.787498],ORF:[33800,36.8946,-76.201202],RIC:[33900,37.50519943237305,-77.3197021484375],IAD:[34e3,38.9445,-77.455803],DCA:[34100,38.8521,-77.037697],PHL:[34200,39.87189865112305,-75.24109649658203],NYC:[34300,40.639447,-73.779317]},Fj=new Bv("fetchAirportCodeFromCdn"),Uj=async(e,t,r)=>(await Xv(fetch(e,{method:"HEAD"}),r)).headers.get(t),jj=async()=>{const e=2e3;try{return await(async(e,t)=>{const r=await Uj(e,"X-Amz-Cf-Pop",t);if(!r||r.length<3)throw new Error("Could not get airport code from Amazon");return r.substring(0,3)})("https://d47ahk2wrqweh.cloudfront.net/cdn-location",e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.fastly.com","X-Served-By",e);if(!t||t.length<3)throw new Error("Could not get airport code from Fastly");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.cloudflare.com","CF-RAY",e);if(!t||t.length<3)throw new Error("Could not get airport code from Cloudflare");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}throw new Error("Could not get airport code from any CDN")},qj=new Bv("getLocalRegion");let zj,Kj;const Gj=async()=>{let e;return e=await(async()=>{let e;try{e=await jj()}catch{return}return e})(),void 0!==e&&Lj[e]?Lj[e][0]:(()=>{const e=Object.keys(Lj),t=e[Math.floor(Math.random()*e.length)],r=Lj[t][0]+99;return qj.warn(`Could not get airport code, using random region: ${r}`),r})()};var Vj,Hj,$j={exports:{}},Wj=$j.exports;function Jj(){return Vj||(Vj=1,function(e){(function(){var t,r,n,i,s,o,a,c,u,l,h,d,f,p,g;n=Math.floor,l=Math.min,r=function(e,t){return e<t?-1:e>t?1:0},u=function(e,t,i,s,o){var a;if(null==i&&(i=0),null==o&&(o=r),i<0)throw new Error("lo must be non-negative");for(null==s&&(s=e.length);i<s;)o(t,e[a=n((i+s)/2)])<0?s=a:i=a+1;return[].splice.apply(e,[i,i-i].concat(t)),t},o=function(e,t,n){return null==n&&(n=r),e.push(t),p(e,0,e.length-1,n)},s=function(e,t){var n,i;return null==t&&(t=r),n=e.pop(),e.length?(i=e[0],e[0]=n,g(e,0,t)):i=n,i},c=function(e,t,n){var i;return null==n&&(n=r),i=e[0],e[0]=t,g(e,0,n),i},a=function(e,t,n){var i;return null==n&&(n=r),e.length&&n(e[0],t)<0&&(t=(i=[e[0],t])[0],e[0]=i[1],g(e,0,n)),t},i=function(e,t){var i,s,o,a,c,u;for(null==t&&(t=r),c=[],s=0,o=(a=function(){u=[];for(var t=0,r=n(e.length/2);0<=r?t<r:t>r;0<=r?t++:t--)u.push(t);return u}.apply(this).reverse()).length;s<o;s++)i=a[s],c.push(g(e,i,t));return c},f=function(e,t,n){var i;if(null==n&&(n=r),-1!==(i=e.indexOf(t)))return p(e,0,i,n),g(e,i,n)},h=function(e,t,n){var s,o,c,u,l;if(null==n&&(n=r),!(o=e.slice(0,t)).length)return o;for(i(o,n),c=0,u=(l=e.slice(t)).length;c<u;c++)s=l[c],a(o,s,n);return o.sort(n).reverse()},d=function(e,t,n){var o,a,c,h,d,f,p,g,m;if(null==n&&(n=r),10*t<=e.length){if(!(c=e.slice(0,t).sort(n)).length)return c;for(a=c[c.length-1],h=0,f=(p=e.slice(t)).length;h<f;h++)n(o=p[h],a)<0&&(u(c,o,0,null,n),c.pop(),a=c[c.length-1]);return c}for(i(e,n),m=[],d=0,g=l(t,e.length);0<=g?d<g:d>g;0<=g?++d:--d)m.push(s(e,n));return m},p=function(e,t,n,i){var s,o,a;for(null==i&&(i=r),s=e[n];n>t&&i(s,o=e[a=n-1>>1])<0;)e[n]=o,n=a;return e[n]=s},g=function(e,t,n){var i,s,o,a,c;for(null==n&&(n=r),s=e.length,c=t,o=e[t],i=2*t+1;i<s;)(a=i+1)<s&&!(n(e[i],e[a])<0)&&(i=a),e[t]=e[i],i=2*(t=i)+1;return e[t]=o,p(e,c,t,n)},t=function(){function e(e){this.cmp=null!=e?e:r,this.nodes=[]}return e.push=o,e.pop=s,e.replace=c,e.pushpop=a,e.heapify=i,e.updateItem=f,e.nlargest=h,e.nsmallest=d,e.prototype.push=function(e){return o(this.nodes,e,this.cmp)},e.prototype.pop=function(){return s(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return c(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return a(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return i(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return f(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var t;return(t=new e).nodes=this.nodes.slice(0),t},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),e.exports=t}).call(Wj)}($j)),$j.exports}Hj||(Hj=1,Jj());const Qj=(e,t)=>yL.distance(e,t),Zj=e=>gw(e),Yj=e=>mw(e),Xj=e=>Zj(e.nodeId),eq=(e,t)=>yw(e.nodeId,t.nodeId),tq=()=>Zj(so(20));class rq extends Sl{options;contactsById=new Map;contactIds=[];constructor(e){super(),this.options=e,this.compareIds=this.compareIds.bind(this)}getClosestContactId(){return this.contactIds[0]}getContactIds(){return this.contactIds}addContact(e){const t=e.getNodeId();if(!this.options.excludedNodeIds?.has(t)&&!(!this.options.allowToContainReferenceId&&this.options.referenceId===t||void 0!==this.options.nodeIdDistanceLimit&&this.compareIds(this.options.nodeIdDistanceLimit,t)<0||this.contactsById.has(t)))if(void 0===this.options.maxSize||this.contactIds.length<this.options.maxSize){this.contactsById.set(t,e);const r=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(r,0,t),this.hasEventListeners()&&this.emit("contactAdded",e)}else if(this.compareIds(this.contactIds[this.options.maxSize-1],t)>0){const r=this.contactIds.pop(),n=this.contactsById.get(r);this.contactsById.delete(r),this.contactsById.set(t,e);const i=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(i,0,t),this.hasEventListeners()&&(this.emit("contactRemoved",n),this.emit("contactAdded",e))}}addContacts(e){e.forEach((e=>this.addContact(e)))}getContact(e){return this.contactsById.get(e)}has(e){return this.contactsById.has(e)}getClosestContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}getFurthestContacts(e){const t=[...this.getClosestContacts()].reverse();return void 0===e?t:t.slice(0,Math.max(e,0))}compareIds(e,t){return this.distanceToReferenceId(e)-this.distanceToReferenceId(t)}distanceToReferenceId(e){return Qj(Yj(this.options.referenceId),Yj(e))}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.hasEventListeners()&&this.emit("contactRemoved",t),!0}return!1}getAllContactsInUndefinedOrder(){return this.contactsById.values()}getSize(e){let t=0;if(void 0!==e)for(const r of e)this.has(r)&&t++;return this.contactIds.length-t}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}hasEventListeners(){return this.eventNames().length>0}}class nq{values=new Set;queue=[];maxItemCount;constructor(e){this.maxItemCount=e}add(e){if(this.values.add(e),this.queue.push(e),this.queue.length>this.maxItemCount){const e=this.queue.shift();this.values.delete(e)}}isMostLikelyDuplicate(e){return this.values.has(e)}size(){return this.values.size}clear(){this.values.clear(),this.queue=[]}}var iq;!function(e){e.CONNECTION_FAILED="CONNECTION_FAILED",e.COULD_NOT_ROUTE="COULD_NOT_ROUTE",e.STARTING_WEBSOCKET_SERVER_FAILED="STARTING_WEBSOCKET_SERVER_FAILED",e.WEBSOCKET_CONNECTION_REQUEST_REJECTED="WEBSOCKET_CONNECTION_REQUEST_REJECTED",e.COULD_NOT_START="COULD_NOT_START",e.COULD_NOT_STOP="COULD_NOT_STOP",e.CANNOT_CONNECT_TO_SELF="CANNOT_CONNECT_TO_SELF",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.ILLEGAL_RTC_PEER_CONNECTION_STATE="ILLEGAL_RTC_PEER_CONNECTION_STATE",e.ILLEGAL_ARGUMENTS="ILLEGAL_ARGUMENTS",e.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT="CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT",e.CONNECTION_LOCKER="CONNECTION_LOCKER",e.DHT_JOIN_TIMEOUT="DHT_JOIN_TIMEOUT",e.SEND_FAILED="SEND_FAILED",e.GETTING_DATA_FAILED="GETTING_DATA_FAILED",e.CONNECTION_NOT_OPEN="CONNECTION_NOT_OPEN"}(iq||(iq={}));class sq extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}}class oq extends sq{constructor(e,t){super(iq.CONNECTION_FAILED,e,t)}}class aq extends sq{constructor(e,t){super(iq.STARTING_WEBSOCKET_SERVER_FAILED,e,t)}}class cq extends sq{constructor(e,t){super(iq.COULD_NOT_START,e,t)}}class uq extends sq{constructor(e,t){super(iq.CANNOT_CONNECT_TO_SELF,e,t)}}class lq extends sq{constructor(e,t){super(iq.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT,e,t)}}class hq extends sq{constructor(e,t){super(iq.SEND_FAILED,e,t)}}const dq=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const fq=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var pq;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(pq||(pq={}));const gq=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>fq},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",pq]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>dq}])}};const mq=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var yq,bq,wq,vq,Eq,Aq;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(yq||(yq={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(bq||(bq={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(wq||(wq={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(vq||(vq={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(Eq||(Eq={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(Aq||(Aq={}));const Sq=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"ttl",kind:"scalar",T:13}])}};const kq=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const Rq=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq}])}};const Cq=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>Fq}])}};const Iq=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>Pq}])}};const Pq=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"storedAt",kind:"message",T:()=>mq},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const Tq=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const _q=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Nq=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Mq=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>Fq},{no:3,name:"requestId",kind:"scalar",T:9}])}};const xq=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",yq]}])}};const Oq=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>Pq},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>Fq}])}};const Dq=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Bq=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Lq=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const Fq=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",bq]},{no:3,name:"udp",kind:"message",T:()=>Uq},{no:4,name:"tcp",kind:"message",T:()=>Uq},{no:5,name:"websocket",kind:"message",T:()=>Uq},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const Uq=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const jq=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>Fq},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>Hq},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>Fq},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>Fq},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const qq=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",vq]}])}};const zq=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const Kq=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>Uq},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const Gq=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>Fq},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Vq=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",Eq]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Hq=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>Fq},{no:3,name:"targetDescriptor",kind:"message",T:()=>Fq},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>gq},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>zq},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>Kq},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>Gq},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>Vq},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>xq}])}};const $q=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const Wq=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const Jq=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Qq=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Zq=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const Yq=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const Xq=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const ez=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const tz=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",Aq]}])}};const rz=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const nz=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const iz=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>Pq}])}};const sz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const oz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>Fq}])}},az=new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:Tq,O:_q},{name:"getClosestRingPeers",options:{},I:Nq,O:Mq},{name:"ping",options:{},I:Dq,O:Bq},{name:"leaveNotice",options:{},I:Lq,O:dq}]),cz=new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:jq,O:qq},{name:"forwardMessage",options:{},I:jq,O:qq}]),uz=new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:jq,O:qq}]),lz=new vF("dht.StoreRpc",[{name:"storeData",options:{},I:Sq,O:kq},{name:"replicateData",options:{},I:Iq,O:dq}]),hz=new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:Oq,O:dq}]),dz=new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:$q,O:dq}]),fz=new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:Wq,O:dq},{name:"rtcOffer",options:{},I:Jq,O:dq},{name:"rtcAnswer",options:{},I:Qq,O:dq},{name:"iceCandidate",options:{},I:Zq,O:dq}]),pz=new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:Yq,O:ez},{name:"unlockRequest",options:{},I:Xq,O:dq},{name:"gracefulDisconnect",options:{},I:tz,O:dq},{name:"setPrivate",options:{},I:rz,O:dq}]),gz=new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:nz,O:iz},{name:"externalStoreData",options:{},I:Rq,O:Cq},{name:"externalFindClosestNodes",options:{},I:sz,O:oz}]);class mz{_transport;typeName=az.typeName;methods=az.methods;options=az.options;constructor(e){this._transport=e}getClosestPeers(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}getClosestRingPeers(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}ping(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveNotice(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class yz{_transport;typeName=cz.typeName;methods=cz.methods;options=cz.options;constructor(e){this._transport=e}routeMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}forwardMessage(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class bz{_transport;typeName=uz.typeName;methods=uz.methods;options=uz.options;constructor(e){this._transport=e}routeRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class wz{_transport;typeName=lz.typeName;methods=lz.methods;options=lz.options;constructor(e){this._transport=e}storeData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}replicateData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class vz{_transport;typeName=hz.typeName;methods=hz.methods;options=hz.options;constructor(e){this._transport=e}sendResponse(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Ez{_transport;typeName=dz.typeName;methods=dz.methods;options=dz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Az{_transport;typeName=fz.typeName;methods=fz.methods;options=fz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcOffer(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcAnswer(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}iceCandidate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Sz{_transport;typeName=pz.typeName;methods=pz.methods;options=pz.options;constructor(e){this._transport=e}lockRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}unlockRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}gracefulDisconnect(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}setPrivate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class kz{_transport;typeName=gz.typeName;methods=gz.methods;options=gz.options;constructor(e){this._transport=e}externalFetchData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalStoreData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalFindClosestNodes(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const Rz={connect:!0,sendIfStopped:!1,bufferWhileConnecting:!0};class Cz extends WF{targetDescriptor;sourceDescriptor;clientId;connect;sendIfStopped;bufferWhileConnecting;incomingSourceDescriptor}class Iz extends nU{ownServiceId;constructor(e,t,r){super(r),this.ownServiceId=e,this.setOutgoingMessageListener(((e,r,n)=>{let i;i=n.targetDescriptor?n.targetDescriptor:n.incomingSourceDescriptor;const s={messageId:xF(),serviceId:this.ownServiceId,body:{oneofKind:"rpcMessage",rpcMessage:e},targetDescriptor:i},o=void 0!==e.header.response?{connect:!1,sendIfStopped:!0,bufferWhileConnecting:!0}:{connect:n?.connect??Rz.connect,sendIfStopped:n?.sendIfStopped??Rz.sendIfStopped,bufferWhileConnecting:n?.bufferWhileConnecting??Rz.bufferWhileConnecting};return t(s,o)}))}handleMessageFromPeer(e){if(e.serviceId===this.ownServiceId&&"rpcMessage"===e.body.oneofKind){const t=new Cz;t.incomingSourceDescriptor=e.sourceDescriptor,this.handleIncomingMessage(e.body.rpcMessage,t)}}}class Pz{localLocks=new Map;remoteLocks=new Map;weakLocks=new Map;remotePrivateConnections=new Set;getLocalLockedConnectionCount(){return this.localLocks.size}getRemoteLockedConnectionCount(){return this.remoteLocks.size}getWeakLockedConnectionCount(){return this.weakLocks.size}isLocalLocked(e,t){return void 0===t?this.localLocks.has(e):this.localLocks.has(e)&&this.localLocks.get(e).has(t)}isRemoteLocked(e,t){return void 0===t?this.remoteLocks.has(e):!(!this.remoteLocks.has(e)||!this.remoteLocks.get(e).has(t))}isWeakLocked(e){return this.weakLocks.has(e)}isLocked(e){return this.isLocalLocked(e)||this.isRemoteLocked(e)||this.isWeakLocked(e)}addLocalLocked(e,t){this.localLocks.has(e)||this.localLocks.set(e,new Set),this.localLocks.get(e).add(t)}addRemoteLocked(e,t){this.remoteLocks.has(e)||this.remoteLocks.set(e,new Set),this.remoteLocks.get(e).add(t)}addWeakLocked(e,t){this.weakLocks.has(e)||this.weakLocks.set(e,new Set),this.weakLocks.get(e).add(t)}removeLocalLocked(e,t){this.localLocks.has(e)&&(this.localLocks.get(e)?.delete(t),0===this.localLocks.get(e)?.size&&this.localLocks.delete(e))}removeRemoteLocked(e,t){this.remoteLocks.has(e)&&(this.remoteLocks.get(e)?.delete(t),0===this.remoteLocks.get(e)?.size&&this.remoteLocks.delete(e))}removeWeakLocked(e,t){this.weakLocks.has(e)&&(this.weakLocks.get(e)?.delete(t),0===this.weakLocks.get(e)?.size&&this.weakLocks.delete(e))}addPrivate(e){this.remotePrivateConnections.add(e)}removePrivate(e){this.remotePrivateConnections.delete(e)}getPrivateConnections(){return this.remotePrivateConnections}isPrivate(e){return this.remotePrivateConnections.has(e)}clearAllLocks(e){this.localLocks.delete(e),this.remoteLocks.delete(e),this.weakLocks.delete(e)}clear(){this.localLocks.clear(),this.remoteLocks.clear(),this.weakLocks.clear()}}const Tz=e=>void 0!==e?Xj(e):"unknown",_z=()=>xF(),Nz=new Bv("ManagedConnection");class Mz extends Sl{connection;connectionId;remotePeerDescriptor;lastUsedTimestamp=Date.now();replacedAsDuplicate=!1;stopped=!1;openedAt=Date.now();bytesSent=0;bytesReceived=0;messagesSent=0;messagesReceived=0;constructor(e,t){super(),this.connectionId=_z(),this.connection=t,t.on("data",(e=>{this.lastUsedTimestamp=Date.now(),this.messagesReceived+=1,this.bytesReceived+=e.length,this.emit("managedData",e,this.getPeerDescriptor())})),t.on("disconnected",(e=>this.onDisconnected(e))),this.lastUsedTimestamp=Date.now(),this.remotePeerDescriptor=e}onDisconnected(e){Nz.trace(Tz(this.remotePeerDescriptor)+" onDisconnected() "+e),this.replacedAsDuplicate||this.emit("disconnected",e),this.removeAllListeners()}replaceAsDuplicate(){Nz.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}send(e){if(this.stopped)throw new hq("ManagedConnection is stopped");this.lastUsedTimestamp=Date.now(),this.messagesSent+=1,this.bytesSent+=e.length,this.connection.send(e)}async close(e){this.stopped||(await this.connection.close(e),this.removeAllListeners())}getNodeId(){return Xj(this.remotePeerDescriptor)}getLastUsedTimestamp(){return this.lastUsedTimestamp}getPeerDescriptor(){return this.remotePeerDescriptor}getDiagnosticInfo(){return{remotePeerDescriptor:this.remotePeerDescriptor,lastUsedTimestamp:this.lastUsedTimestamp,replacedAsDuplicate:this.replacedAsDuplicate,stopped:this.stopped,openedAt:this.openedAt,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}}var xz;!function(e){e.WEBSOCKET_SERVER="websocket-server",e.WEBSOCKET_CLIENT="websocket-client",e.WEBRTC="webrtc",e.SIMULATOR_SERVER="simulator-server",e.SIMULATOR_CLIENT="simulator-client"}(xz||(xz={}));const Oz=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8"].map((e=>uU.parseCIDR(e)));function Dz(e){if(uU.IPv4.isValid(e)){const t=uU.IPv4.parse(e);for(const e of Oz)if(t.match(e))return!0}return!1}const Bz=e=>{const t="localhost"===e.host||Dz(e.host);return e.tls||t},Lz=(e,t)=>t.websocket&&(e.type!==bq.BROWSER||Bz(t.websocket))?xz.WEBSOCKET_CLIENT:e.websocket&&(t.type!==bq.BROWSER||Bz(e.websocket))?xz.WEBSOCKET_SERVER:xz.WEBRTC,Fz=5e3,Uz=(e,t)=>{const r=Lz(e,t);return r===xz.WEBSOCKET_CLIENT?5e3:r===xz.WEBSOCKET_SERVER?7500:(xz.WEBRTC,1e4)};class jz{localPeerDescriptor;remotePeerDescriptor;client;timeout;constructor(e,t,r,n,i){this.localPeerDescriptor=e,this.remotePeerDescriptor=t,this.client=iU(new n(r.getRpcClientTransport())),this.timeout=i}getPeerDescriptor(){return this.remotePeerDescriptor}getLocalPeerDescriptor(){return this.localPeerDescriptor}getClient(){return this.client}formDhtRpcOptions(e){return{sourceDescriptor:this.localPeerDescriptor,targetDescriptor:this.remotePeerDescriptor,timeout:this.timeout??Uz(this.localPeerDescriptor,this.remotePeerDescriptor),...e}}}const qz=new Bv("ConnectionLockRpcRemote");class zz extends jz{async lockRequest(e){qz.trace(`Requesting locked connection to ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions();try{return(await this.getClient().lockRequest(t,r)).accepted}catch(e){return qz.debug("Connection lock rejected",{err:e}),!1}}unlockRequest(e){qz.trace(`Requesting connection to be unlocked from ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions({notification:!0});this.getClient().unlockRequest(t,r).catch((e=>{qz.trace("failed to send unlockRequest")}))}async gracefulDisconnect(e){qz.trace(`Notifying a graceful disconnect to ${Xj(this.getPeerDescriptor())}`);const t={disconnectMode:e},r=this.formDhtRpcOptions({connect:!1,sendIfStopped:!0,timeout:2e3});await this.getClient().gracefulDisconnect(t,r)}async setPrivate(e){qz.trace(`Setting isPrivate: ${e} for ${Xj(this.getPeerDescriptor())}`);const t={isPrivate:e},r=this.formDhtRpcOptions({connect:!1,notification:!0});await this.getClient().setPrivate(t,r)}}const Kz=new Bv("ConnectionLockRpcLocal");class Gz{options;constructor(e){this.options=e}async lockRequest(e,t){const r=t.incomingSourceDescriptor;if(eq(r,this.options.getLocalPeerDescriptor())){return{accepted:!1}}const n=Xj(r);this.options.addRemoteLocked(n,e.lockId);return{accepted:!0}}async unlockRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.removeRemoteLocked(n,e.lockId),{}}async gracefulDisconnect(e,t){const r=t.incomingSourceDescriptor;return Kz.trace(Tz(r)+" received gracefulDisconnect notice"),e.disconnectMode===Aq.LEAVING?await this.options.closeConnection(r,!0,"graceful leave notified"):await this.options.closeConnection(r,!1,"graceful disconnect notified"),{}}async setPrivate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.setPrivate(n,e.isPrivate),{}}}const Vz=(e,t)=>Hz(e+","+t)<Hz(t+","+e)?"local":"remote",Hz=e=>_v(e).readInt32LE(0);class $z{buffer=[];deferredPromise=new eb;push(e){return this.buffer.push(e),this.deferredPromise}getBuffer(){return this.buffer}resolve(){this.buffer.length=0,this.deferredPromise.resolve()}reject(){this.buffer.length=0,this.deferredPromise.reject(new hq("Could not send buffered messages"))}}var Wz;!function(e){e.OPEN_INTERNET="open_internet",e.UNKNOWN="unknown"}(Wz||(Wz={}));const Jz=new Bv("ConnectionManager");var Qz;!function(e){e.IDLE="idle",e.RUNNING="running",e.STOPPING="stopping",e.STOPPED="stopped"}(Qz||(Qz={}));const Zz="system/connection-manager";class Yz extends Sl{options;metricsContext;duplicateMessageDetector=new nq(1e4);metrics;locks=new Pz;endpoints=new Map;connectorFacade;rpcCommunicator;disconnectorIntervalRef;state=Qz.IDLE;privateClientMode=!1;constructor(e){super(),this.options=e,this.onData=this.onData.bind(this),this.send=this.send.bind(this),this.onNewConnection=this.onNewConnection.bind(this),this.metricsContext=this.options.metricsContext??new $v,this.metrics={sendMessagesPerSecond:new Hv,sendBytesPerSecond:new Hv,receiveMessagesPerSecond:new Hv,receiveBytesPerSecond:new Hv,connectionAverageCount:new Gv(0),connectionTotalFailureCount:new qv},this.metricsContext.addMetrics("node",this.metrics),this.connectorFacade=this.options.createConnectorFacade(),this.send=this.send.bind(this),this.rpcCommunicator=new Iz(Zz,this.send,{rpcRequestTimeout:1e4});const t=new Gz({addRemoteLocked:(e,t)=>this.locks.addRemoteLocked(e,t),removeRemoteLocked:(e,t)=>this.locks.removeRemoteLocked(e,t),closeConnection:(e,t,r)=>this.closeConnection(e,t,r),getLocalPeerDescriptor:()=>this.getLocalPeerDescriptor(),setPrivate:(e,t)=>{this.options.allowIncomingPrivateConnections?t?this.locks.addPrivate(e):this.locks.removePrivate(e):Jz.debug(`node ${e} attemted to set a connection as private, but it is not allowed`)}});this.rpcCommunicator.registerRpcMethod(Yq,ez,"lockRequest",((e,r)=>t.lockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(Xq,"unlockRequest",((e,r)=>t.unlockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(tz,"gracefulDisconnect",((e,r)=>t.gracefulDisconnect(e,r))),this.rpcCommunicator.registerRpcNotification(rz,"setPrivate",((e,r)=>t.setPrivate(e,r)))}garbageCollectConnections(e,t){if(this.endpoints.size<=e)return;const r=new rq({referenceId:Xj(this.getLocalPeerDescriptor()),maxSize:1e5,allowToContainReferenceId:!1});this.endpoints.forEach((e=>{if(e.connected){const n=e.connection,i=n.getNodeId();!this.locks.isLocked(i)&&!this.locks.isPrivate(i)&&Date.now()-n.getLastUsedTimestamp()>t&&(Jz.trace("disconnecting in timeout interval: "+Tz(n.getPeerDescriptor())),r.addContact(n))}}));const n=r.getFurthestContacts(this.endpoints.size-e);for(const e of n){const t=e.getPeerDescriptor();Jz.trace("garbageCollecting "+Xj(t)),this.gracefullyDisconnectAsync(t,Aq.NORMAL).catch((e=>{}))}}async start(){if(this.state===Qz.RUNNING||this.state===Qz.STOPPED)throw new cq(`Cannot start already ${this.state} module`);this.state=Qz.RUNNING,Jz.trace("Starting ConnectionManager..."),await this.connectorFacade.start((e=>this.onNewConnection(e)),(e=>this.hasConnection(e)),this),this.disconnectorIntervalRef=setInterval((()=>{Jz.trace("disconnectorInterval");this.garbageCollectConnections(this.options.maxConnections??80,2e4)}),5e3)}async stop(){this.state!==Qz.STOPPED&&this.state!==Qz.STOPPING&&(this.state=Qz.STOPPING,Jz.trace("Stopping ConnectionManager"),this.disconnectorIntervalRef&&clearInterval(this.disconnectorIntervalRef),await Promise.all(Array.from(this.endpoints.values()).map((async e=>{if(e.connected)try{await this.gracefullyDisconnectAsync(e.connection.getPeerDescriptor(),Aq.LEAVING)}catch(e){Jz.error(e)}else{const t=e.connection;Jz.trace("handshake of connection not completed, force-closing");const r=eE(t,"disconnected",2e3);t.close(!0);try{await r,Jz.trace("resolving after receiving disconnected event from non-handshaked connection")}catch(t){e.buffer.reject(),Jz.trace("force-closing non-handshaked connection timed out "+t)}}}))),await this.connectorFacade.stop(),this.state=Qz.STOPPED,this.rpcCommunicator.stop(),this.duplicateMessageDetector.clear(),this.locks.clear(),this.removeAllListeners())}getLocalLockedConnectionCount(){return this.locks.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.locks.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.locks.getWeakLockedConnectionCount()}async send(e,t=Rz){if((this.state===Qz.STOPPED||this.state===Qz.STOPPING)&&!t.sendIfStopped)return;const r=e.targetDescriptor;if(this.isConnectionToSelf(r))throw new uq("Cannot send to self");const n=Xj(r);Jz.trace(`Sending message to: ${n}`),e={...e,sourceDescriptor:this.getLocalPeerDescriptor()};let i=this.endpoints.get(n)?.connection;if(!i&&t.connect)i=this.connectorFacade.createConnection(r),this.onNewConnection(i);else if(!i||i&&!this.endpoints.get(n).connected&&!t.connect)throw new hq("No connection to target, connect flag is false");const s=Hq.toBinary(e);if(this.metrics.sendBytesPerSecond.record(s.byteLength),this.metrics.sendMessagesPerSecond.record(1),this.endpoints.get(n).connected)i.send(s);else if(t.bufferWhileConnecting)return this.endpoints.get(n).buffer.push(s)}isConnectionToSelf(e){return eq(e,this.getLocalPeerDescriptor())||this.isOwnWebsocketServer(e)}isOwnWebsocketServer(e){const t=this.getLocalPeerDescriptor();return void 0!==e.websocket&&void 0!==t.websocket&&(e.websocket.port===t.websocket.port&&e.websocket.host===t.websocket.host)}getLocalPeerDescriptor(){return this.connectorFacade.getLocalPeerDescriptor()}hasConnection(e){return this.getConnections().some((t=>Xj(t)==e))}getConnectionCount(){return this.getConnections().length}hasLocalLockedConnection(e){return this.locks.isLocalLocked(e)}hasRemoteLockedConnection(e){return this.locks.isRemoteLocked(e)}handleMessage(e){const t=e.body.oneofKind;Jz.trace("Received message of type "+t),"rpcMessage"===t?this.duplicateMessageDetector.isMostLikelyDuplicate(e.messageId)?Jz.trace("handleMessage filtered duplicate "+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId):(this.duplicateMessageDetector.add(e.messageId),e.serviceId===Zz?this.rpcCommunicator?.handleMessageFromPeer(e):(Jz.trace('emit "message" '+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId),this.emit("message",e))):Jz.trace("Filtered out non-RPC message of type "+t)}onData(e,t){if(this.state===Qz.STOPPED)return;let r;this.metrics.receiveBytesPerSecond.record(e.byteLength),this.metrics.receiveMessagesPerSecond.record(1);try{r=Hq.fromBinary(e)}catch(e){return void Jz.debug(`Parsing incoming data into Message failed: ${e}`)}r.sourceDescriptor=t;try{this.handleMessage(r)}catch(e){Jz.debug(`Handling incoming data failed: ${e}`)}}onConnected(e,t){const r=new Mz(e,t);r.on("managedData",this.onData),r.once("disconnected",(t=>this.onDisconnected(e,t)));const n=Xj(e),i=this.endpoints.get(n),s=i.buffer,o=i.connection,a=s.getBuffer();for(;a.length>0;)Jz.trace("emptying buffer"),r.send(a.shift());s.resolve(),o.destroy(),this.endpoints.set(n,{connected:!0,connection:r}),this.privateClientMode&&this.setPrivateForConnection(e,this.privateClientMode).catch((()=>{})),this.emit("connected",e),this.onConnectionCountChange()}onDisconnected(e,t){const r=Xj(e);Jz.trace(r+" onDisconnected() gracefulLeave: "+t);const n=this.endpoints.get(r);n&&(this.locks.clearAllLocks(r),!1===n.connected&&n.buffer.reject(),this.endpoints.delete(r),Jz.trace(r+" deleted connection in onDisconnected() gracefulLeave: "+t),this.emit("disconnected",e,t),this.onConnectionCountChange())}onNewConnection(e){return this.state!==Qz.STOPPED&&(Jz.trace("onNewConnection()"),!!this.acceptNewConnection(e)&&(e.once("connected",((e,t)=>this.onConnected(e,t))),e.once("disconnected",(t=>this.onDisconnected(e.getPeerDescriptor(),t))),!0))}acceptNewConnection(e){const t=Xj(e.getPeerDescriptor());if(Jz.trace(t+" acceptNewConnection()"),this.endpoints.has(t)){if("remote"===Vz(Xj(this.getLocalPeerDescriptor()),t)){let r;const n=this.endpoints.get(t);this.endpoints.get(t).connected?(Jz.debug("replacing connected connection",{nodeId:t}),r=new $z):r=n.buffer;const i=n.connection;return Jz.trace("replaced: "+t),i.replaceAsDuplicate(),this.endpoints.set(t,{connected:!1,connection:e,buffer:r}),!0}return!1}return Jz.trace(t+" added to connections at acceptNewConnection"),this.endpoints.set(t,{connected:!1,buffer:new $z,connection:e}),!0}async closeConnection(e,t,r){const n=Xj(e);if(Jz.trace(n+" closeConnection() "+r),this.locks.clearAllLocks(n),this.endpoints.has(n)){const e=this.endpoints.get(n).connection;await e.close(t)}else Jz.trace(n+" closeConnection() this.endpoints did not have the id"),this.emit("disconnected",e,!1)}lockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e),n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.locks.addLocalLocked(r,t),n.lockRequest(t).then((e=>Jz.trace("LockRequest successful"))).catch((e=>{Jz.debug(e)}))}unlockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e);this.locks.removeLocalLocked(r,t);const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.endpoints.has(r)&&n.unlockRequest(t)}weakLockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.addWeakLocked(e,t)}weakUnlockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.removeWeakLocked(e,t)}async enablePrivateClientMode(){this.privateClientMode=!0,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!0)})))}async disablePrivateClientMode(){this.privateClientMode=!1,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!1)})))}getConnectedEndpoints(){return Array.from(this.endpoints.values()).filter((e=>e.connected))}isPrivateClientMode(){return this.privateClientMode}async setPrivateForConnection(e,t){const r=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);await r.setPrivate(t)}async gracefullyDisconnectAsync(e,t){const r=this.endpoints.get(Xj(e));if(r)if(r.connected){const n=r.connection,i=new Promise(((e,t)=>{eE(n,"disconnected",2e3).then((()=>{Jz.trace("disconnected event received in gracefullyDisconnectAsync()")})).catch((e=>{Jz.trace("force-closing connection after timeout "+e),n.close(!0)})).finally((()=>{Jz.trace("resolving after receiving disconnected event"),e()}))}));await Promise.all([i,this.doGracefullyDisconnectAsync(e,t)])}else r.connection.close(!0);else Jz.debug("gracefullyDisconnectedAsync() tried on a non-existing connection")}async doGracefullyDisconnectAsync(e,t){const r=Xj(e);Jz.trace(r+" gracefullyDisconnectAsync()");const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);try{await n.gracefulDisconnect(t)}catch(e){Jz.trace(r+" remote.gracefulDisconnect() failed"+e)}}getConnections(){return Array.from(this.endpoints.values()).map((e=>e)).filter((e=>e.connected&&!this.locks.isPrivate(Xj(e.connection.getPeerDescriptor())))).map((e=>e.connection.getPeerDescriptor()))}onConnectionCountChange(){this.metrics.connectionAverageCount.record(this.endpoints.size)}getDiagnosticInfo(){return{connections:Array.from(this.endpoints.values()).filter((e=>e.connected)).map((e=>e.connection)).map((e=>e.getDiagnosticInfo())),connectionCount:this.endpoints.size}}}new Bv("SimulatorConnection");const Xz="1.1",eK=e=>{const t=tK(Xz).major,r=tK(e)?.major;return!(void 0===r||r<t)},tK=e=>{const t=e.split(".");if(2===t.length){const e=t.map((e=>Number(e)));if(!e.some((e=>isNaN(e))))return{major:e[0],minor:e[1]}}};var rK="103.6.0-rc.0";const nK=new Bv("Handshaker"),iK=(e,t,r,n)=>{const i=new aK(e,r),s=()=>{i.stop(),r.off("disconnected",u),r.off("connected",c),i.off("handshakeCompleted",a),i.off("handshakeFailed",o),t.off("disconnected",l)},o=e=>{e!==Eq.INVALID_TARGET_PEER_DESCRIPTOR&&e!==Eq.UNSUPPORTED_PROTOCOL_VERSION||(t.close(!1),s())},a=e=>{nK.trace("handshake completed for outgoing connection, "+Xj(e)),t.onHandshakeCompleted(r),s()},c=()=>i.sendHandshakeRequest(n),u=e=>{t.close(e),s()},l=()=>{r.close(!1),s()};return i.once("handshakeFailed",o),i.once("handshakeCompleted",a),r.once("connected",c),r.once("disconnected",u),t.once("disconnected",l),i},sK=(e,t,r,n)=>{r.sendHandshakeResponse(n),t.destroy(),e.destroy()},oK=(e,t,r)=>{e.sendHandshakeResponse(),t.onHandshakeCompleted(r)};let aK=class extends Sl{static HANDSHAKER_SERVICE_ID="system/handshaker";localPeerDescriptor;connection;onDataListener;constructor(e,t){super(),this.localPeerDescriptor=e,this.connection=t,this.onDataListener=e=>this.onData(e),this.connection.on("data",this.onDataListener)}onData(e){try{const t=Hq.fromBinary(e);if("handshakeRequest"===t.body.oneofKind){nK.trace("handshake request received");const e=t.body.handshakeRequest;this.emit("handshakeRequest",e.sourcePeerDescriptor,e.protocolVersion,e.targetPeerDescriptor)}if("handshakeResponse"===t.body.oneofKind){nK.trace("handshake response received");const e=t.body.handshakeResponse,r=eK(e.protocolVersion)?e.error:Eq.UNSUPPORTED_PROTOCOL_VERSION;void 0!==r?this.emit("handshakeFailed",r):this.emit("handshakeCompleted",e.sourcePeerDescriptor)}}catch(e){nK.debug("error while parsing handshake message",e)}}sendHandshakeRequest(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,targetPeerDescriptor:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeRequest",handshakeRequest:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake request sent")}sendHandshakeResponse(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,error:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeResponse",handshakeResponse:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake response sent")}stop(){this.connection.off("data",this.onDataListener),this.removeAllListeners()}};const cK=new Bv("PendingConnection");class uK extends Sl{connectingAbortController=new AbortController;remotePeerDescriptor;replacedAsDuplicate=!1;stopped=!1;constructor(e,t=15e3){super(),this.remotePeerDescriptor=e,Yy((()=>{this.close(!1)}),t,this.connectingAbortController.signal)}replaceAsDuplicate(){cK.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}onHandshakeCompleted(e){this.replacedAsDuplicate||this.emit("connected",this.remotePeerDescriptor,e)}close(e){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.replacedAsDuplicate||this.emit("disconnected",e))}destroy(){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.removeAllListeners())}getPeerDescriptor(){return this.remotePeerDescriptor}}new Bv("SimulatorConnector");class lK extends Iz{transport;messageListener;disconnectedListener;constructor(e,t,r){super(e,((e,r)=>t.send(e,r)),r),this.messageListener=e=>{this.handleMessageFromPeer(e)},this.disconnectedListener=e=>{this.getRequestIds((t=>eq(e,t.getCallContext().targetDescriptor))).forEach((e=>this.handleClientError(e,new qF.Disconnected("Peer disconnected"))))},this.transport=t,t.on("message",this.messageListener),t.on("disconnected",this.disconnectedListener)}destroy(){this.transport.off("message",this.messageListener),this.transport.off("disconnected",this.disconnectedListener),this.stop()}}const hK="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;var dK;!function(e){e.OFFER="offer",e.ANSWER="answer"}(dK||(dK={}));var fK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(fK||(fK={}));const pK=new Bv("DirectWebrtcConnection (browser)");let gK;const mK=new Promise((e=>{gK=e}));if(hK){const e=t=>{if("streamr-webrtc-bridge-port"===t.data?.type&&t.data.port){const r=wU(t.data.port);gK(r),self.removeEventListener("message",e)}};self.addEventListener("message",e)}var yK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(yK||(yK={}));const bK=new Bv("WorkerWebrtcConnection");const wK=hK?class extends Sl{connectionId;connectionType=xz.WEBRTC;iceServers;bufferThresholdHigh;bufferThresholdLow;dataChannel;bridge;closed=!1;connected=!1;earlyTimeout;messageQueue=[];startPromise;constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.bufferThresholdHigh=e.bufferThresholdHigh??2**17,this.bufferThresholdLow=e.bufferThresholdLow??32768,this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.startPromise=this.doStart(e),this.startPromise.catch((e=>{bK.warn("Failed to start worker WebRTC connection",{err:e}),this.doClose(!1,"Failed to start")}))}async doStart(e){this.bridge=await mK;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));await this.bridge.start(this.connectionId,t,e,IU({onLocalCandidate:(e,t)=>{this.closed||this.emit("localCandidate",e,t)},onLocalDescription:(e,t)=>{this.closed||this.emit("localDescription",e,t)},onConnectionStateChange:e=>{e!==yK.CLOSED&&e!==yK.DISCONNECTED&&e!==yK.FAILED||this.doClose(!1)},onDataChannel:e=>{this.closed||(this.setupDataChannel(e),"open"===e.readyState&&this.onDataChannelOpen())}}))}async setRemoteDescription(e,t){if(this.startPromise&&await this.startPromise,!this.bridge||this.closed)return;await this.bridge.setRemoteDescription(this.connectionId,e,t)&&clearTimeout(this.earlyTimeout)}addRemoteCandidate(e,t){this.doAddRemoteCandidate(e,t).catch((e=>{bK.warn("Failed to add remote candidate via bridge",{err:e})}))}async doAddRemoteCandidate(e,t){this.startPromise&&await this.startPromise,this.bridge&&!this.closed&&await this.bridge.addRemoteCandidate(this.connectionId,e,t)}isOpen(){return this.connected}async close(e,t){this.doClose(e,t)}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){this.connected&&this.dataChannel?this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel.send(e):this.closed||this.messageQueue.push(e)}setConnectionId(e){const t=this.connectionId;this.connectionId=e,this.bridge&&t!==e&&this.bridge.renameConnection(t,e).catch((()=>{}))}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{bK.trace("dc.onOpen (worker)"),this.onDataChannelOpen()},e.onclose=()=>{bK.trace("dc.onClosed (worker)"),this.doClose(!1)},e.onerror=e=>{bK.warn("Data channel error (worker)",{err:e})},e.onmessage=e=>{bK.trace("dc.onmessage (worker)"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(bK.trace("dc.onBufferedAmountLow (worker)");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}onDataChannelOpen(){this.connected=!0,this.flushMessageQueue(),this.emit("connected")}flushMessageQueue(){for(;this.messageQueue.length>0&&this.dataChannel&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}doClose(e,t){if(!this.closed){if(this.closed=!0,this.connected=!1,this.messageQueue.length=0,clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){bK.warn("Failed to close data channel (worker)",{err:e})}this.dataChannel=void 0,this.bridge?.close(this.connectionId).catch((()=>{}))}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null)}}:class extends Sl{connectionId;connectionType=xz.WEBRTC;lastState="connecting";iceServers;peerConnection;bufferThresholdHigh=2**17;bufferThresholdLow=32768;dataChannel;makingOffer=!1;isOffering=!1;closed=!1;earlyTimeout;messageQueue=[];constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.isOffering=e;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));if(this.peerConnection=new RTCPeerConnection({iceServers:t}),this.peerConnection.onicecandidate=e=>{null!==e.candidate&&null!==e.candidate.sdpMid&&this.emit("localCandidate",e.candidate.candidate,e.candidate.sdpMid)},this.peerConnection.onicegatheringstatechange=()=>{pK.trace(`conn.onGatheringStateChange: ${this.peerConnection?.iceGatheringState}`)},this.peerConnection.onconnectionstatechange=()=>this.onStateChange(),e){this.peerConnection.onnegotiationneeded=async()=>{if(void 0!==this.peerConnection){this.makingOffer=!0;try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription?.sdp,this.peerConnection.localDescription?.type)}this.makingOffer=!1};const e=this.peerConnection.createDataChannel("streamrDataChannel");this.setupDataChannel(e)}else this.peerConnection.ondatachannel=e=>{this.setupDataChannel(e.channel)}}async setRemoteDescription(e,t){const r=t.toLowerCase()===dK.OFFER&&(this.makingOffer||"stable"!=this.peerConnection?.signalingState);if(!(this.isOffering&&r)){try{await(this.peerConnection?.setRemoteDescription({sdp:e,type:t.toLowerCase()})),clearTimeout(this.earlyTimeout)}catch(e){pK.warn("Failed to set remote description",{err:e})}if(t.toLowerCase()===dK.OFFER&&void 0!==this.peerConnection){try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription.sdp,this.peerConnection.localDescription.type)}}}addRemoteCandidate(e,t){this.peerConnection?.addIceCandidate({candidate:e,sdpMid:t}).catch((e=>{pK.warn("Failed to add ICE candidate",{err:e})}))}isOpen(){return"connected"===this.lastState}async close(e,t){this.doClose(e,t)}doClose(e,t){if(!this.closed){if(this.closed=!0,this.lastState="closed",clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){pK.warn("Failed to close data channel",{err:e})}if(this.dataChannel=void 0,void 0!==this.peerConnection)try{this.peerConnection.close()}catch(e){pK.warn("Failed to close connection",{err:e})}this.peerConnection=void 0}}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){"connected"===this.lastState?this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel?.send(e):pK.warn("Tried to send on a connection with last state "+this.lastState)}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{pK.trace("dc.onOpen"),this.onDataChannelOpen()},e.onclose=()=>{pK.trace("dc.onClosed"),this.doClose(!1)},e.onerror=e=>{pK.warn("Data channel error",{err:e})},e.onmessage=e=>{pK.trace("dc.onmessage"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(pK.trace("dc.onBufferedAmountLow");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null),void 0!==this.peerConnection&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.onicecandidate=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.ondatachannel=null)}onDataChannelOpen(){this.lastState="connected",this.emit("connected")}onStateChange(){this.peerConnection.connectionState!==fK.CLOSED&&this.peerConnection.connectionState!==fK.DISCONNECTED&&this.peerConnection.connectionState!==fK.FAILED||this.doClose(!1)}setConnectionId(e){this.connectionId=e}},vK=new Bv("WebrtcConnectorRpcRemote");class EK extends jz{requestConnection(){const e=this.formDhtRpcOptions({notification:!0});this.getClient().requestConnection({},e).catch((e=>{vK.trace("Failed to send requestConnection")}))}sendRtcOffer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcOffer(r,n).catch((e=>{vK.trace("Failed to send rtcOffer")}))}sendRtcAnswer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcAnswer(r,n).catch((e=>{vK.trace("Failed to send rtcAnswer")}))}sendIceCandidate(e,t,r){const n={connectionId:r,mid:t,candidate:e},i=this.formDhtRpcOptions();this.getClient().iceCandidate(n,i).catch((e=>{vK.trace("Failed to send iceCandidate")}))}}const AK=new Bv("WebrtcConnectorRpcLocal");class SK{options;constructor(e){this.options=e}async requestConnection(e){const t=e.incomingSourceDescriptor;if(this.options.ongoingConnectAttempts.has(Xj(t)))return{};const r=this.options.connect(t,!1);return this.options.onNewConnection(r),{}}async rtcOffer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);let i,s;return this.options.ongoingConnectAttempts.has(n)?(s=this.options.ongoingConnectAttempts.get(n).managedConnection,i=this.options.ongoingConnectAttempts.get(n).connection):(s=this.options.connect(r,!0),i=this.options.ongoingConnectAttempts.get(n).connection,this.options.onNewConnection(s)),i.setConnectionId(e.connectionId),i.setRemoteDescription(e.description,"offer"),{}}async rtcAnswer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring RTC answer due to connectionId mismatch"),{}):(i.setRemoteDescription(e.description,"answer"),{}):{}}async iceCandidate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring remote candidate due to connectionId mismatch"),{}):(this.isIceCandidateAllowed(e.candidate)&&i.addRemoteCandidate(e.candidate,e.mid),{}):{}}isIceCandidateAllowed(e){if(!this.options.allowPrivateAddresses){const t=function(e){const t=e.split(" ").filter((e=>e.length>0));return t.length>=5&&uU.isValid(t[4])?t[4]:void 0}(e);if(void 0!==t&&Dz(t))return!1}return!0}}const kK=new Bv("WebrtcConnector");class RK{static WEBRTC_CONNECTOR_SERVICE_ID="system/webrtc-connector";rpcCommunicator;ongoingConnectAttempts=new Map;localPeerDescriptor;stopped=!1;options;constructor(e){this.options=e,this.rpcCommunicator=new lK(RK.WEBRTC_CONNECTOR_SERVICE_ID,e.transport,{rpcRequestTimeout:15e3}),this.registerLocalRpcMethods(e)}registerLocalRpcMethods(e){const t=new SK({connect:(e,t)=>this.connect(e,t),onNewConnection:e=>this.options.onNewConnection(e),ongoingConnectAttempts:this.ongoingConnectAttempts,rpcCommunicator:this.rpcCommunicator,getLocalPeerDescriptor:()=>this.localPeerDescriptor,allowPrivateAddresses:e.allowPrivateAddresses??!0});this.rpcCommunicator.registerRpcNotification(Wq,"requestConnection",(async(e,r)=>this.stopped?{}:t.requestConnection(r))),this.rpcCommunicator.registerRpcNotification(Jq,"rtcOffer",(async(e,r)=>this.stopped?{}:t.rtcOffer(e,r))),this.rpcCommunicator.registerRpcNotification(Qq,"rtcAnswer",(async(e,r)=>this.stopped?{}:t.rtcAnswer(e,r))),this.rpcCommunicator.registerRpcNotification(Zq,"iceCandidate",(async(e,r)=>this.stopped?{}:t.iceCandidate(e,r)))}connect(e,t){if(eq(e,this.localPeerDescriptor))throw new uq("Cannot open WebRTC Connection to self");kK.trace(`Opening WebRTC connection to ${Xj(e)}`);const r=Xj(e),n=this.ongoingConnectAttempts.get(r);if(n)return n.managedConnection;const i=this.createConnection(e),s=Xj(this.localPeerDescriptor),o=Xj(e),a="local"===Vz(s,o);let c;const u=new EK(this.localPeerDescriptor,e,this.rpcCommunicator,Az),l=()=>{this.ongoingConnectAttempts.delete(r),i.off("disconnected",l),c.off("disconnected",l),c.off("connected",l)};if(a)c=new uK(e),iK(this.localPeerDescriptor,c,i,e),i.once("localDescription",(e=>{kK.trace("Sending offer to remote peer"),u.sendRtcOffer(e,i.connectionId)}));else{c=new uK(e);const t=((e,t,r)=>{const n=new aK(e,r),i=()=>{n.stop(),t.off("disconnected",s),r.off("disconnected",s)},s=e=>{t.close(e),i()};return n.on("handshakeRequest",(()=>{i()})),r.once("disconnected",s),t.once("disconnected",(()=>{r.close(!1),i()})),n})(this.localPeerDescriptor,c,i);i.once("localDescription",(e=>{u.sendRtcAnswer(e,i.connectionId)})),t.on("handshakeRequest",((e,r)=>{eK(r)?oK(t,c,i):sK(c,i,t,Eq.UNSUPPORTED_PROTOCOL_VERSION),l()}))}return this.ongoingConnectAttempts.set(o,{managedConnection:c,connection:i}),i.on("disconnected",l),c.on("disconnected",l),c.on("connected",l),i.on("localCandidate",((e,t)=>{void 0!==this.options.externalIp&&(e=((e,t)=>{const r=e.split(" ");return"host"===r[7]&&(r[4]=t),r.join(" ")})(e,this.options.externalIp),kK.debug(`onLocalCandidate injected external ip ${e} ${t}`)),u.sendIceCandidate(e,t,i.connectionId)})),i.start(a),t||a||u.requestConnection(),c}createConnection(e){return new wK({remotePeerDescriptor:e,iceServers:this.options.iceServers,bufferThresholdLow:this.options.bufferThresholdLow,bufferThresholdHigh:this.options.bufferThresholdHigh,portRange:this.options.portRange})}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async stop(){kK.trace("stop()"),this.stopped=!0;const e=Array.from(this.ongoingConnectAttempts.values());await Promise.allSettled(e.map((async e=>{e.connection.destroy(),e.managedConnection.close(!1)}))),this.rpcCommunicator.destroy()}}const CK=new Bv("AbstractWebsocketClientConnection");class IK extends Sl{connectionId;connectionType=xz.WEBSOCKET_CLIENT;destroyed=!1;constructor(){super(),this.connectionId=_z()}send(e){this.destroyed?CK.debug("Tried to send() on stopped connection"):1===this.socket?.readyState?(CK.trace(`Sending data with size ${e.byteLength}`),this.socket?.send(e)):CK.debug("Tried to send data on a non-open connection",{id:this.connectionId,readyState:this.socket.readyState,destroyed:this.destroyed})}async close(e){this.emit("disconnected",e,void 0,"close() called"),this.removeAllListeners(),this.destroyed?CK.debug("Tried to close() a stopped connection",{id:this.connectionId}):(CK.trace(`Closing socket for connection ${this.connectionId}`),this.socket?.close(e?3001:void 0))}destroy(){CK.trace("destroy() a connection"),this.destroyed?CK.debug("Tried to destroy() a stopped connection"):(this.removeAllListeners(),this.socket&&(this.stopListening(),this.socket.close(),this.socket=void 0),this.destroyed=!0)}onOpen(){this.destroyed||(CK.trace("WebSocket Client Connected"),1===this.socket?.readyState&&this.emit("connected"))}onMessage(e){this.emit("data",e)}onClose(e,t){this.destroyed||(CK.trace("Websocket Closed"),this.doDisconnect(e,t))}onError(e){this.destroyed||(CK.trace("WebSocket Client error: "+e?.message,{error:e}),this.emit("error",e.name))}doDisconnect(e,t){this.destroyed=!0,this.stopListening(),this.socket=void 0;const r=1001===e||3001===e;this.emit("disconnected",r,e,t),this.removeAllListeners()}}const PK=new Bv("WebsocketClientConnection (browser)");class TK extends IK{socket;connect(e,t){this.destroyed?PK.debug("Tried to connect() a stopped connection"):(this.socket=new FU.w3cwebsocket(e,void 0,void 0,void 0,{rejectUnauthorized:!t}),this.socket.binaryType="arraybuffer",this.socket.onerror=e=>this.onError(e),this.socket.onopen=()=>this.onOpen(),this.socket.onclose=e=>this.onClose(e.code,e.reason),this.socket.onmessage=e=>{this.destroyed||("string"==typeof e.data?PK.debug("Received string data, only binary data is supported"):this.onMessage(new Uint8Array(e.data)))})}stopListening(){this.socket&&(this.socket.onopen=void 0,this.socket.onclose=void 0,this.socket.onerror=void 0,this.socket.onmessage=void 0)}}class _K{options;constructor(e){this.options=e}async requestConnection(e,t){if(this.options.abortSignal.aborted)return{};const r=t.incomingSourceDescriptor;if(!this.options.hasConnection(Xj(r))){const e=this.options.connect(r);this.options.onNewConnection(e)}return{}}}const NK=(e,t)=>(e.tls?"wss://":"ws://")+e.host+":"+e.port+(void 0!==t?"?action="+t:"");class MK{static WEBSOCKET_CONNECTOR_SERVICE_ID="system/websocket-connector";websocketServer;geoIpLocator;localPeerDescriptor;connectingConnections=new Map;abortController=new AbortController;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new _K({connect:e=>this.connect(e),hasConnection:e=>this.connectingConnections.has(e)||this.options.hasConnection(e),onNewConnection:e=>this.options.onNewConnection(e),abortSignal:this.abortController.signal});this.options.rpcCommunicator.registerRpcNotification($q,"requestConnection",(async(t,r)=>this.abortController.signal.aborted?{}:e.requestConnection(t,r)))}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_CLIENT}connect(e){const t=Xj(e),r=this.connectingConnections.get(t);if(r)return r;const n=new TK,i=NK(e.websocket),s=new uK(e);iK(this.localPeerDescriptor,s,n,e),this.connectingConnections.set(t,s);const o=()=>{this.connectingConnections.has(t)&&this.connectingConnections.delete(t),n.off("disconnected",o),s.off("disconnected",o),s.off("connected",o)};return n.on("disconnected",o),s.on("disconnected",o),s.on("connected",o),n.connect(i,!1),s}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.connectingConnections.values()).forEach((e=>e.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}class xK extends Sl{constructor(e){super()}async start(){throw new Error("WebsocketServer is not supported in browser environment")}async stop(){throw new Error("WebsocketServer is not supported in browser environment")}updateCertificate(e,t){throw new Error("WebsocketServer is not supported in browser environment")}}const OK=new Bv("AutoCertifierClientFacade");class DK{autoCertifierClient;rpcCommunicator;options;constructor(e){this.options=e,this.rpcCommunicator=new lK("system/auto-certificer",e.transport),this.autoCertifierClient=e.createClientFactory?e.createClientFactory():(()=>{throw new Error("AutoCertifierClient is not supported in browser environment")})(e.configFile,e.url,this.rpcCommunicator,e.wsServerPort)}async start(){this.autoCertifierClient.on("updatedCertificate",(e=>{this.options.setHost(e.fqdn),this.options.updateCertificate(e.certificate,e.privateKey),OK.trace("Updated certificate")})),await Promise.all([eE(this.autoCertifierClient,"updatedCertificate",6e4),this.autoCertifierClient.start()])}stop(){this.autoCertifierClient.stop(),this.rpcCommunicator.destroy()}}const BK=new Bv("connectivityChecker"),LK=async({url:e,allowSelfSignedCertificate:t,timeoutMs:r=1e3})=>{const n=new TK;let i;try{const s=tE(n,["connected","error"],r);n.connect(e,t),i=await s}catch{throw new oq("WebSocket connection timed out")}if("error"===i.winnerName)throw new oq("Could not open WebSocket connection");return n},FK="system/connectivity-checker",UK=async(e,t)=>{let r;const n={host:t.websocket.host,port:t.websocket.port,tls:t.websocket.tls},i=NK(n,"connectivityRequest");BK.debug(`Attempting connectivity check with entrypoint ${i}`);try{r=await LK({url:i,allowSelfSignedCertificate:e.allowSelfSignedCertificate})}catch(e){throw new oq(`Failed to connect to entrypoint for connectivity check: ${i}`,e)}const s={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityRequest",connectivityRequest:e}};try{const e=new Promise(((e,t)=>{const n=setTimeout((()=>{r.close(!1),t(new lq("timeout"))}),5e3),i=s=>{r.close(!1);try{const o=Hq.fromBinary(s);if("connectivityResponse"===o.body.oneofKind){BK.debug("ConnectivityResponse received: "+JSON.stringify(Hq.toJson(o)));const s=o.body.connectivityResponse,a=s.protocolVersion;r.off("data",i),clearTimeout(n),eK(a)?e(s):t(`Unsupported version: ${a}`)}}catch(e){BK.trace("Could not parse message",{err:e})}};r.on("data",i)}));return r.send(Hq.toBinary(s)),BK.trace("ConnectivityRequest sent: "+JSON.stringify(Hq.toJson(s))),await e}catch(e){throw BK.error("error getting connectivityresponse"),e}},jK=new Bv("connectivityRequestHandler"),qK=async(e,t,r)=>{const n=t.host??e.getRemoteIpAddress(),i=e.getRemoteIpAddress();let s;if(0!==t.port?s=await zK(t,i,n):(jK.trace("ConnectivityRequest port is 0, replying without connectivityProbe"),s={host:n,natType:Wz.UNKNOWN,ipAddress:mE(i),protocolVersion:Xz}),void 0!==r){const e=r.lookup(i);void 0!==e&&(s.latitude=e.latitude,s.longitude=e.longitude)}const o={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityResponse",connectivityResponse:s}};e.send(Hq.toBinary(o)),jK.trace("ConnectivityResponse sent: "+JSON.stringify(Hq.toJson(o)))},zK=async(e,t,r)=>{let n,i;try{const s={host:r,port:e.port,tls:e.tls},o=NK(s,"connectivityProbe");jK.trace(`Attempting Connectivity Check to ${o}`),n=await LK({url:o,allowSelfSignedCertificate:e.allowSelfSignedCertificate}),jK.trace("Connectivity test produced positive result, communicating reply to the requester "+r+":"+e.port),i={host:r,natType:Wz.OPEN_INTERNET,websocket:{host:r,port:e.port,tls:e.tls},ipAddress:mE(t),protocolVersion:Xz}}catch(e){jK.debug("error",{err:e}),i={host:r,natType:Wz.UNKNOWN,ipAddress:mE(t),protocolVersion:Xz}}return n&&n.close(!1),i},KK=new Bv("WebsocketClientConnectorRpcRemote");class GK extends jz{async requestConnection(){KK.trace(`Requesting WebSocket connection from ${Xj(this.getLocalPeerDescriptor())}`);const e=this.formDhtRpcOptions();return this.getClient().requestConnection({},e)}}const VK=new Bv("WebsocketServerConnector");class HK{websocketServer;geoIpLocator;ongoingConnectRequests=new Map;host;autoCertifierClient;selectedPort;localPeerDescriptor;abortController=new AbortController;options;constructor(e){this.options=e,this.websocketServer=e.portRange?new xK({portRange:e.portRange,tlsCertificate:e.tlsCertificate,maxMessageSize:e.maxMessageSize,enableTls:e.serverEnableTls}):void 0,this.host=e.host}async start(){if(!this.abortController.signal.aborted&&this.websocketServer){if(this.websocketServer.on("connected",(e=>{const t=e,r=new URLSearchParams(t.resourceURL.query??"").get("action");var n,i;VK.trace("WebSocket client connected",{action:r,remoteAddress:t.getRemoteIpAddress()}),"connectivityRequest"===r?(n=t,i=this.geoIpLocator,n.on("data",(async e=>{jK.trace("server received data");try{const t=Hq.fromBinary(e);if("connectivityRequest"===t.body.oneofKind){jK.trace("ConnectivityRequest received: "+JSON.stringify(Hq.toJson(t)));try{await qK(n,t.body.connectivityRequest,i),jK.trace("handleIncomingConnectivityRequest ok")}catch(e){jK.error("handleIncomingConnectivityRequest",{err:e})}}}catch(e){jK.trace("Could not parse message",{err:e})}}))):"connectivityProbe"===r||(void 0!==this.localPeerDescriptor?this.attachHandshaker(e):(VK.trace("incoming Websocket connection before localPeerDescriptor was set, closing connection"),e.close(!1).catch((()=>{}))))})),this.options.geoIpDatabaseFolder)try{this.geoIpLocator=await(()=>{throw new Error("GeoIpLocator is not supported in browser environment")})(this.options.geoIpDatabaseFolder)}catch(e){VK.error("Failed to start GeoIpLocator",{err:e})}const e=await this.websocketServer.start();this.selectedPort=e}}attachHandshaker(e){const t=new aK(this.localPeerDescriptor,e);t.once("handshakeRequest",((r,n,i)=>{this.onServerSocketHandshakeRequest(r,e,t,n,i)}))}onServerSocketHandshakeRequest(e,t,r,n,i){const s=Xj(e);if(this.ongoingConnectRequests.has(s)){const{pendingConnection:e,delFunc:o}=this.ongoingConnectRequests.get(s);eK(n)?i&&!eq(this.localPeerDescriptor,i)?(sK(e,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR),o()):oK(r,e,t):(sK(e,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION),o())}else{const s=new uK(e);eK(n)?i&&!eq(this.localPeerDescriptor,i)?sK(s,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR):this.options.onNewConnection(s)?oK(r,s,t):sK(s,t,r,Eq.DUPLICATE_CONNECTION):sK(s,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION)}}async checkConnectivity(e){if(this.abortController.signal.aborted)return{host:"127.0.0.1",natType:Wz.UNKNOWN,ipAddress:mE("127.0.0.1"),protocolVersion:Xz};if(!this.options.entrypoints||0===this.options.entrypoints.length)return{host:this.host,natType:Wz.OPEN_INTERNET,websocket:{host:this.host,port:this.selectedPort,tls:void 0!==this.options.tlsCertificate},ipAddress:mE("127.0.0.1"),protocolVersion:Xz};const t=JU(this.options.entrypoints);for(;t.length>0&&!this.abortController.signal.aborted;){const r=t[0];try{const t={port:this.selectedPort??0,host:this.host,tls:!!this.websocketServer&&this.options.serverEnableTls,allowSelfSignedCertificate:e};if(this.abortController.signal.aborted)throw new oq("ConnectivityChecker is destroyed");return await UK(t,r)}catch(e){const n=`Failed to connect to entrypoint with id ${Xj(r)} and URL ${NK(r.websocket)}`;VK.error(n,{err:e}),t.shift(),await Qv(2e3,this.abortController.signal)}}throw new aq(`Failed to connect to the entrypoints after ${this.options.entrypoints.length} attempts\nAttempted hosts: ${this.options.entrypoints.map((e=>`${e.websocket.host}:${e.websocket.port}`)).join(", ")}`)}async autoCertify(){this.autoCertifierClient=new DK({configFile:this.options.autoCertifierConfigFile,transport:this.options.autoCertifierTransport,url:this.options.autoCertifierUrl,wsServerPort:this.selectedPort,setHost:e=>this.setHost(e),updateCertificate:(e,t)=>this.websocketServer.updateCertificate(e,t)}),VK.trace("AutoCertifying subdomain..."),await this.autoCertifierClient.start()}setHost(e){VK.trace(`Setting host name to ${e}`),this.host=e}connect(e){const t=Xj(e);return this.ongoingConnectRequests.has(t)?this.ongoingConnectRequests.get(t).pendingConnection:this.requestConnectionFromPeer(this.localPeerDescriptor,e)}requestConnectionFromPeer(e,t){setImmediate((()=>{new GK(e,t,this.options.rpcCommunicator,Ez).requestConnection().then((()=>{VK.trace("Sent WebsocketConnectionRequest notification to peer",{targetPeerDescriptor:t})}),(e=>{VK.debug("Failed to send WebsocketConnectionRequest notification to peer ",{error:e,targetPeerDescriptor:t})}))}));const r=new uK(t),n=Xj(t),i=()=>{r.off("connected",i),r.off("disconnected",i),this.ongoingConnectRequests.delete(n)};return r.on("connected",i),r.on("disconnected",i),this.ongoingConnectRequests.set(n,{pendingConnection:r,delFunc:i}),r}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_SERVER}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.ongoingConnectRequests.values()).forEach((e=>e.pendingConnection.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}const $K=new Bv("ConnectorFacade");class WK{options;localPeerDescriptor;websocketConnectorRpcCommunicator;websocketClientConnector;websocketServerConnector;webrtcConnector;constructor(e){this.options=e}async start(e,t,r){$K.trace("Creating WebsocketConnectorRpcLocal"),this.websocketConnectorRpcCommunicator=new lK(MK.WEBSOCKET_CONNECTOR_SERVICE_ID,this.options.transport,{rpcRequestTimeout:15e3});const n={onNewConnection:e,hasConnection:t,rpcCommunicator:this.websocketConnectorRpcCommunicator};this.websocketClientConnector=new MK(n);const i={rpcCommunicator:this.websocketConnectorRpcCommunicator,onNewConnection:e,hasConnection:t,portRange:this.options.websocketPortRange,host:this.options.websocketHost,entrypoints:this.options.entryPoints,tlsCertificate:this.options.tlsCertificate,serverEnableTls:this.options.websocketServerEnableTls,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,autoCertifierTransport:r,maxMessageSize:this.options.maxMessageSize,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder};this.websocketServerConnector=new HK(i),this.webrtcConnector=new RK({onNewConnection:e,transport:this.options.transport,iceServers:this.options.iceServers,allowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,bufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,bufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,externalIp:this.options.externalIp,portRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize}),await this.websocketServerConnector.start();const s=!this.options.tlsCertificate&&!0===this.options.websocketServerEnableTls,o=await this.websocketServerConnector.checkConnectivity(s),a=await this.options.createLocalPeerDescriptor(o);if(this.setLocalPeerDescriptor(a),a.websocket&&!this.options.tlsCertificate&&this.options.websocketServerEnableTls)try{await this.websocketServerConnector.autoCertify();const e=await this.websocketServerConnector.checkConnectivity(!1),t=await this.options.createLocalPeerDescriptor(e);void 0!==t.websocket?this.setLocalPeerDescriptor(t):($K.warn("Connectivity check failed after auto-certification, disabling WebSocket server TLS"),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1}))}catch(e){$K.warn("Failed to auto-certify, disabling WebSocket server TLS",{err:e}),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1})}}setLocalPeerDescriptor(e){this.localPeerDescriptor=e,this.websocketServerConnector.setLocalPeerDescriptor(e),this.websocketClientConnector.setLocalPeerDescriptor(e),this.webrtcConnector.setLocalPeerDescriptor(e)}async restartWebsocketServerConnector(e){await this.websocketServerConnector.destroy(),this.websocketServerConnector=new HK(e),await this.websocketServerConnector.start();const t=await this.websocketServerConnector.checkConnectivity(!1),r=await this.options.createLocalPeerDescriptor(t);this.setLocalPeerDescriptor(r)}createConnection(e){return this.websocketClientConnector.isPossibleToFormConnection(e)?this.websocketClientConnector.connect(e):this.websocketServerConnector.isPossibleToFormConnection(e)?this.websocketServerConnector.connect(e):this.webrtcConnector.connect(e,!1)}getLocalPeerDescriptor(){return this.localPeerDescriptor}async stop(){this.websocketConnectorRpcCommunicator.destroy(),await this.websocketServerConnector.destroy(),await this.websocketClientConnector.destroy(),await this.webrtcConnector.stop()}}function JK(e){const t=Buffer.alloc(4);return t.writeUInt32BE(e),t}const QK=new TE,ZK=async(e,t,r)=>{const n=so(32),i=so(20);let s;s=void 0!==r?Yj(r):await(async(e,t)=>{const r=Buffer.alloc(4);r.writeUInt32BE(e);const n=QK.keccakHash(r),i=await QK.createSignature(r,t);return Buffer.concat([n.subarray(n.length-13,n.length),i.subarray(i.length-7,i.length)])})(e.ipAddress,n);const o={nodeId:s,type:bq.BROWSER,ipAddress:e.ipAddress,region:t,publicKey:i};return e.websocket&&(o.websocket={host:e.websocket.host,port:e.websocket.port,tls:e.websocket.tls}),o.signature=await QK.createSignature((e=>{const t=Buffer.from(","),r=[void 0!==e.type?JK(e.type):new Uint8Array(0),t,void 0!==e.udp?Uq.toBinary(e.udp):new Uint8Array(0),t,void 0!==e.tcp?Uq.toBinary(e.tcp):new Uint8Array(0),t,void 0!==e.websocket?Uq.toBinary(e.websocket):new Uint8Array(0),t,void 0!==e.region?JK(e.region):new Uint8Array(0),t,void 0!==e.ipAddress?JK(e.ipAddress):new Uint8Array(0),t,void 0!==e.publicKey?Buffer.from(e.publicKey):new Uint8Array(0)];return Buffer.concat(r)})(o),n),o};class YK{peerDescriptor;constructor(e){this.peerDescriptor=e}getPeerDescriptor(){return this.peerDescriptor}getNodeId(){return Xj(this.peerDescriptor)}}const XK=(e,t,r)=>{const n=new rq({referenceId:e,allowToContainReferenceId:!0,excludedNodeIds:r?.excludedNodeIds,maxSize:r?.maxCount});for(const e of t)n.addContact(new YK(e));return n.getClosestContacts().map((e=>e.getPeerDescriptor()))},eG=new Bv("DhtNodeRpcLocal");class tG{options;constructor(e){this.options=e}async getClosestPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);return{peers:XK(Zj(e.nodeId),this.options.getNeighbors(),{maxCount:this.options.peerDiscoveryQueryBatchSize}),requestId:e.requestId}}async getClosestRingPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);const r=this.options.getClosestRingContactsTo(e.ringId,this.options.peerDiscoveryQueryBatchSize);return{leftPeers:r.left,rightPeers:r.right,requestId:e.requestId}}async ping(e,t){eG.trace("received ping request: "+Xj(t.incomingSourceDescriptor)),setImmediate((()=>{this.options.addContact(t.incomingSourceDescriptor)}));return{requestId:e.requestId}}async leaveNotice(e){const t=e.incomingSourceDescriptor,r=Xj(t);return eG.trace("received leave notice: "+r),this.options.removeContact(r),{}}}const rG=new Bv("DhtNodeRpcRemote");class nG extends jz{static counter=0;vectorClock;id;serviceId;constructor(e,t,r,n,i){super(e,t,n,mz,i),this.id=this.getPeerDescriptor().nodeId,this.vectorClock=nG.counter++,this.serviceId=r}async getClosestPeers(e){rG.trace(`Requesting getClosestPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={nodeId:Yj(e),requestId:xF()};try{return(await this.getClient().getClosestPeers(t,this.formDhtRpcOptions())).peers}catch(e){throw rG.trace(`getClosestPeers error ${this.serviceId}`,{err:e}),e}}async getClosestRingPeers(e){rG.trace(`Requesting getClosestRingPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={ringId:e,requestId:xF()};try{const e=await this.getClient().getClosestRingPeers(t,this.formDhtRpcOptions());return{left:e.leftPeers??[],right:e.rightPeers??[]}}catch(e){throw rG.trace(`getClosestRingPeers error ${this.serviceId}`,{err:e}),e}}async ping(){rG.trace(`Requesting ping on ${this.serviceId} from ${this.getNodeId()}`);const e={requestId:xF()},t=this.formDhtRpcOptions();try{if((await this.getClient().ping(e,t)).requestId===e.requestId)return!0}catch(e){rG.trace(`ping failed on ${this.serviceId} to ${this.getNodeId()}`,{err:e})}return!1}leaveNotice(){rG.trace(`Sending leaveNotice on ${this.serviceId} from ${this.getNodeId()}`);const e=this.formDhtRpcOptions({notification:!0});this.getClient().leaveNotice({},e).catch((e=>{rG.trace("Failed to send leaveNotice"+e)}))}getNodeId(){return Xj(this.getPeerDescriptor())}}class iG{options;constructor(e){this.options=e}async externalFetchData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.key),yq.FETCH_DATA,Xj(r));return iz.create({entries:n.dataEntries??[]})}async externalStoreData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.storeDataToDht(Zj(e.key),e.data,Xj(r));return Cq.create({storers:n})}async externalFindClosestNodes(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.nodeId),yq.FIND_CLOSEST_NODES,Xj(r));return oz.create({closestNodes:n.closestNodes})}}const sG=1e4;class oG extends jz{async externalFetchData(e){const t={key:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFetchData(t,r)).entries}catch{return[]}}async storeData(e,t){const r={key:Yj(e),data:t},n=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalStoreData(r,n)).storers}catch{return[]}}async externalFindClosestNode(e){const t={nodeId:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFindClosestNodes(t,r)).closestNodes}catch{return[]}}}class aG extends Sl{contactsById=new Map;contactIds=[];localNodeId;maxSize;constructor(e,t){super(),this.localNodeId=e,this.maxSize=t}getContact(e){return this.contactsById.get(e)}getSize(){return this.contactIds.length}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}}class cG extends aG{randomness;constructor(e,t,r=.2){super(e,t),this.randomness=r}addContact(e){if(this.localNodeId!==e.getNodeId()&&!this.contactsById.has(e.getNodeId())){if(Math.random()<this.randomness){if(this.getSize()===this.maxSize&&this.getSize()>0){const e=this.contactIds[0];this.removeContact(e)}this.contactIds.push(e.getNodeId()),this.contactsById.set(e.getNodeId(),e),this.emit("contactAdded",e)}}}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.emit("contactRemoved",t),!0}return!1}getContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}}const uG=2**120-1,lG=e=>e.reduce(((e,t)=>e<<BigInt(8)|BigInt(t)),BigInt(0)),hG=e=>Number(lG(e)),dG=e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e.region??0,0);const r=Buffer.alloc(4);r.writeUInt32BE(e.ipAddress??0,0);const n=[t,r,Buffer.from(e.nodeId.subarray(e.nodeId.length-7,e.nodeId.length))],i=Buffer.concat(n);return new Uint8Array(i)},fG=e=>{const t=dG(e);return Number(lG(t))},pG=(e,t)=>{const r=Math.abs(e-t);return e>t?r:uG-r},gG=(e,t)=>{const r=Math.abs(e-t);return e>t?uG-r:r};class mG extends Sl{numNeighborsPerSide=5;referenceId;excludedIds;leftNeighbors;rightNeighbors;constructor(e,t){super(),this.referenceId=hG(e),this.excludedIds=t??new Set,this.leftNeighbors=new cj,this.rightNeighbors=new cj}addContact(e){const t=fG(e.getPeerDescriptor());if(t===this.referenceId||this.excludedIds.has(Xj(e.getPeerDescriptor())))return;let r=!1,n=!1;const i=pG(this.referenceId,t),s=this.leftNeighbors.back();(void 0===s||i<s[0])&&(this.leftNeighbors.setElement(i,e),r=!0,this.leftNeighbors.size()>this.numNeighborsPerSide&&(this.leftNeighbors.eraseElementByIterator(this.leftNeighbors.rBegin()),n=!0));const o=gG(this.referenceId,t),a=this.rightNeighbors.back();(void 0===a||o<a[0])&&(this.rightNeighbors.setElement(o,e),r=!0,this.rightNeighbors.size()>this.numNeighborsPerSide&&(this.rightNeighbors.eraseElementByIterator(this.rightNeighbors.rBegin()),n=!0)),this.hasEventListeners()&&(r||n)&&(r&&this.emit("contactAdded",e),n&&this.emit("contactRemoved",e))}removeContact(e){if(void 0===e)return;const t=fG(e.getPeerDescriptor()),r=pG(this.referenceId,t),n=gG(this.referenceId,t);let i=!1;this.leftNeighbors.eraseElementByKey(r)&&(i=!0),this.rightNeighbors.eraseElementByKey(n)&&(i=!0),this.hasEventListeners()&&i&&this.emit("contactRemoved",e)}getContact(e){const t=fG(e),r=pG(this.referenceId,t),n=gG(this.referenceId,t);return this.leftNeighbors.getElementByKey(r)?this.leftNeighbors.getElementByKey(r):this.rightNeighbors.getElementByKey(n)?this.rightNeighbors.getElementByKey(n):void 0}getClosestContacts(e){const t=[],r=[];let n=0;for(const r of this.leftNeighbors){if(null!=e&&n>=e)break;t.push(r[1]),n++}let i=0;for(const t of this.rightNeighbors){if(null!=e&&i>=e)break;r.push(t[1]),i++}return{left:t,right:r}}getAllContacts(){const e=[];for(const t of this.leftNeighbors)e.push(t[1]);for(const t of this.rightNeighbors)e.push(t[1]);return e}hasEventListeners(){return this.eventNames().length>0}}const yG=new Bv("PeerManager");class bG extends Sl{neighbors;nearbyContacts;activeContacts;ringContacts;randomContacts;stopped=!1;options;constructor(e){super(),this.options=e,this.neighbors=new yL({localNodeId:Yj(this.options.localNodeId),numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,numberOfNodesToPing:this.options.numberOfNodesPerKBucket}),this.ringContacts=new mG(dG(this.options.localPeerDescriptor)),this.ringContacts.on("contactAdded",(e=>{this.emit("ringContactAdded",e.getPeerDescriptor())})),this.ringContacts.on("contactRemoved",(e=>{this.emit("ringContactRemoved",e.getPeerDescriptor())})),this.neighbors.on("ping",((e,t)=>this.onKBucketPing(e,t))),this.neighbors.on("removed",(e=>this.onKBucketRemoved(Xj(e.getPeerDescriptor())))),this.neighbors.on("added",(e=>this.onKBucketAdded(e))),this.neighbors.on("updated",(()=>{})),this.nearbyContacts=new rq({referenceId:this.options.localNodeId,maxSize:this.options.maxContactCount,allowToContainReferenceId:!1}),this.nearbyContacts.on("contactRemoved",(e=>{this.stopped||(this.emit("nearbyContactRemoved",e.getPeerDescriptor()),this.randomContacts.addContact(this.options.createDhtNodeRpcRemote(e.getPeerDescriptor())))})),this.nearbyContacts.on("contactAdded",(e=>this.emit("nearbyContactAdded",e.getPeerDescriptor()))),this.activeContacts=new Set,this.randomContacts=new cG(this.options.localNodeId,this.options.maxContactCount),this.randomContacts.on("contactRemoved",(e=>this.emit("randomContactRemoved",e.getPeerDescriptor()))),this.randomContacts.on("contactAdded",(e=>this.emit("randomContactAdded",e.getPeerDescriptor())))}onKBucketPing(e,t){if(this.stopped)return;const r=new rq({referenceId:this.options.localNodeId,allowToContainReferenceId:!1});r.addContacts(e);const n=r.getFurthestContacts(1)[0].getNodeId();this.options.connectionLocker?.weakUnlockConnection(n,this.options.lockId),this.neighbors.remove(Yj(n)),this.neighbors.add(t)}onKBucketRemoved(e){this.stopped||(this.options.connectionLocker?.weakUnlockConnection(e,this.options.lockId),yG.trace(`Removed contact ${e}`),0===this.neighbors.count()&&this.emit("kBucketEmpty"))}onKBucketAdded(e){if(!this.stopped&&e.getNodeId()!==this.options.localNodeId){const t=e.getPeerDescriptor(),r=Xj(t);this.options.connectionLocker?.weakLockConnection(r,this.options.lockId),this.options.hasConnection(e.getNodeId())||void 0!==this.options.neighborPingLimit&&this.neighbors.count()>this.options.neighborPingLimit?yG.trace(`Added new contact ${r}`):(yG.trace("starting ping "+r),e.ping().then((e=>{e?yG.trace(`Added new contact ${r}`):(yG.trace("ping failed "+r),this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors())})).catch((e=>{this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors()})))}}addNearbyContactToNeighbors(){if(this.stopped)return;const e=this.getNearbyActiveContactNotInNeighbors();e&&this.addContact(e.getPeerDescriptor())}getNearbyActiveContactNotInNeighbors(){for(const e of this.nearbyContacts.getContactIds())if(!this.neighbors.get(Yj(e))&&this.activeContacts.has(e))return this.nearbyContacts.getContact(e)}removeContact(e){this.stopped||(yG.trace(`Removing contact ${e}`),this.ringContacts.removeContact(this.nearbyContacts.getContact(e)),this.neighbors.remove(Yj(e)),this.nearbyContacts.removeContact(e),this.activeContacts.delete(e),this.randomContacts.removeContact(e))}removeNeighbor(e){this.neighbors.remove(Yj(e))}async pruneOfflineNodes(e){yG.trace("Pruning offline nodes",{nodes:e.length});const t=await(async(e,t)=>{const r=[];return await Promise.allSettled(e.map((async e=>{await e.ping()?t.add(e.getNodeId()):(t.delete(e.getNodeId()),r.push(e.getPeerDescriptor()))}))),r})(e,this.activeContacts);t.forEach((e=>{yG.trace("Removing offline node",{node:Xj(e)}),this.removeContact(Xj(e))}))}stop(){this.stopped=!0,this.neighbors.toArray().forEach((e=>{e.leaveNotice(),this.neighbors.remove(e.id)})),this.neighbors.removeAllListeners(),this.ringContacts.getAllContacts().forEach((e=>{e.leaveNotice(),this.ringContacts.removeContact(e)})),this.nearbyContacts.stop(),this.randomContacts.stop()}getNearbyContacts(){return this.nearbyContacts}getClosestRingContactsTo(e,t,r){const n=new mG(e,r);return this.ringContacts.getAllContacts().map((e=>n.addContact(e))),n.getClosestContacts(t??8)}getRandomContacts(){return this.randomContacts}getRingContacts(){return this.ringContacts}getNearbyContactCount(e){return this.nearbyContacts.getSize(e)}getNeighborCount(){return this.neighbors.count()}getNeighbors(){return this.neighbors.toArray()}setContactActive(e){this.activeContacts.add(e)}addContact(e){if(this.stopped)return;const t=Xj(e);if(t!==this.options.localNodeId){yG.trace(`Adding new contact ${t}`);const r=this.options.createDhtNodeRpcRemote(e),n=null!==this.neighbors.get(e.nodeId),i=void 0!==this.nearbyContacts.getContact(t),s=void 0!==this.ringContacts.getContact(e);(n||i)&&this.randomContacts.addContact(r),n||this.neighbors.add(r),i||this.nearbyContacts.addContact(r),s||this.ringContacts.addContact(r)}}}const wG=new Bv("DiscoverySession");class vG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;constructor(e){this.options=e}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestNeighborsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return[];const t=Xj(e);wG.trace(`Getting closest neighbors from remote: ${t}`),this.options.contactedPeers.add(t);const r=this.options.createDhtNodeRpcRemote(e),n=await r.getClosestPeers(this.options.targetId);return this.options.peerManager.setContactActive(t),n}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=Yj(this.options.targetId),n=this.getClosestNeighbor(),i=Qj(r,n.nodeId);this.addContacts(t);const s=this.getClosestNeighbor();Qj(r,s.nodeId)>=i&&this.noProgressCounter++}getClosestNeighbor(){return XK(this.options.targetId,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:1})[0]}onRequestFailed(e){this.ongoingRequests.has(e)&&(this.ongoingRequests.delete(e),this.options.peerManager.removeContact(e))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=XK(this.options.targetId,Array.from(this.options.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder(),(e=>e.getPeerDescriptor())),{maxCount:this.options.parallelism,excludedNodeIds:this.options.contactedPeers});if(0===e.length&&0===this.ongoingRequests.size||this.noProgressCounter>=this.options.noProgressLimit)this.doneGate.open();else for(const t of e){if(this.ongoingRequests.size>=this.options.parallelism)break;const e=Xj(t);this.ongoingRequests.add(e),this.fetchClosestNeighborsFromRemote(t).then((t=>this.onRequestSucceeded(e,t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const EG=new Bv("RingDiscoverySession");class AG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;numContactedPeers=0;targetIdAsRingId;constructor(e){this.options=e,this.targetIdAsRingId=hG(this.options.targetId)}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestContactsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return{left:[],right:[]};EG.trace(`Getting closest ring peers from contact: ${Xj(e.getPeerDescriptor())}`),this.numContactedPeers++,this.options.contactedPeers.add(e.getNodeId());const t=await e.getClosestRingPeers(this.options.targetId);return this.options.peerManager.setContactActive(e.getNodeId()),t}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),n=pG(this.targetIdAsRingId,fG(r.left[0].getPeerDescriptor())),i=pG(this.targetIdAsRingId,fG(r.right[0].getPeerDescriptor()));this.addContacts(t.left.concat(t.right));const s=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),o=pG(this.targetIdAsRingId,fG(s.left[0].getPeerDescriptor())),a=pG(this.targetIdAsRingId,fG(s.right[0].getPeerDescriptor()));o>=n&&a>=i&&this.noProgressCounter++}onRequestFailed(e){this.ongoingRequests.has(e.getNodeId())&&(this.ongoingRequests.delete(e.getNodeId()),this.options.peerManager.removeContact(e.getNodeId()))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,this.options.parallelism,this.options.contactedPeers);if(0===e.left.length&&0===e.right.length||this.noProgressCounter>=this.options.noProgressLimit)return void this.doneGate.open();const t=[],r=new Set,n=Math.max(e.left.length,e.right.length);for(let i=0;i<n;i++)i<e.left.length&&(r.has(e.left[i].getNodeId())||(t.push(e.left[i]),r.add(e.left[i].getNodeId()))),i<e.right.length&&(r.has(e.right[i].getNodeId())||(t.push(e.right[i]),r.add(e.right[i].getNodeId())));for(const e of t){if(this.ongoingRequests.size>=this.options.parallelism)break;this.ongoingRequests.add(e.getNodeId()),this.fetchClosestContactsFromRemote(e).then((t=>this.onRequestSucceeded(e.getNodeId(),t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const SG="layer0",kG=new Bv("PeerDiscovery");class RG{ongoingDiscoverySessions=new Map;ongoingRingDiscoverySessions=new Map;rejoinOngoing=!1;joinCalled=!1;recoveryIntervalStarted=!1;options;constructor(e){this.options=e}async joinDht(e,t=!0,r=!0){const n=new Set,i=t?{enabled:!0,contactedPeers:new Set}:{enabled:!1};await Promise.all(e.map((e=>this.joinThroughEntryPoint(e,n,i,r))))}async joinThroughEntryPoint(e,t,r,n=!0){if(this.isStopped())return;if(this.joinCalled=!0,kG.debug("Joining "+(this.options.serviceId===SG?"The Streamr Network":`Control Layer for ${this.options.serviceId}`)+` via entrypoint ${Xj(e)}`),eq(e,this.options.localPeerDescriptor))return;this.options.connectionLocker?.lockConnection(e,`${this.options.serviceId}::joinDht`),this.options.peerManager.addContact(e);const i=Xj(this.options.localPeerDescriptor),s=[this.createSession(i,t)];r.enabled&&s.push(this.createSession((e=>{const t=Yj(e).map((e=>~e));return Zj(t)})(i),r.contactedPeers)),await this.runSessions(s,e,n),this.options.connectionLocker?.unlockConnection(e,`${this.options.serviceId}::joinDht`)}async joinRing(){const e=new Set,t=[this.createRingSession(dG(this.options.localPeerDescriptor),e)];await this.runRingSessions(t)}createSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new vG(r)}createRingSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new AG(r)}async runSessions(e,t,r){try{for(const t of e)this.ongoingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`DHT join on ${this.options.serviceId} timed out`)}finally{this.isStopped()||(0===this.options.peerManager.getNeighborCount()?r&&Yy((()=>this.rejoinDht(t)),1e3,this.options.abortSignal):await this.ensureRecoveryIntervalIsRunning()),e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async runRingSessions(e){try{for(const t of e)this.ongoingRingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`Ring join on ${this.options.serviceId} timed out`)}finally{e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async rejoinDht(e,t=new Set,r=new Set){if(!this.isStopped()&&!this.rejoinOngoing){kG.debug(`Rejoining DHT ${this.options.serviceId}`),this.rejoinOngoing=!0;try{await this.joinThroughEntryPoint(e,t,{enabled:!0,contactedPeers:r}),kG.debug(`Rejoined DHT successfully ${this.options.serviceId}!`)}catch{kG.warn(`Rejoining DHT ${this.options.serviceId} failed`),this.isStopped()||Yy((()=>this.rejoinDht(e)),5e3,this.options.abortSignal)}finally{this.rejoinOngoing=!1}}}async ensureRecoveryIntervalIsRunning(){this.recoveryIntervalStarted||(this.recoveryIntervalStarted=!0,await Jv((()=>this.fetchClosestAndRandomNeighbors()),6e4,!0,this.options.abortSignal))}async fetchClosestAndRandomNeighbors(){if(this.isStopped())return;const e=Xj(this.options.localPeerDescriptor),t=this.getClosestNeighbors(e,this.options.parallelism),r=this.getClosestNeighbors(tq(),1);await Promise.allSettled([...t.map((async t=>{const r=this.options.createDhtNodeRpcRemote(t),n=await r.getClosestPeers(e);for(const e of n)this.options.peerManager.addContact(e)})),...r.map((async e=>{const t=this.options.createDhtNodeRpcRemote(e),r=await t.getClosestPeers(tq());for(const e of r)this.options.peerManager.addContact(e)}))])}getClosestNeighbors(e,t){return XK(e,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:t})}isJoinOngoing(){return!this.joinCalled||this.ongoingDiscoverySessions.size>0}isJoinCalled(){return this.joinCalled}isStopped(){return this.options.abortSignal.aborted}}const CG=e=>bj(e.routingPath),IG=new Bv("RouterRpcRemote");class PG extends jz{async routeMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const n=await this.getClient().routeMessage(t,r);if(n.error===vq.DUPLICATE&&yw(e.target,this.getPeerDescriptor().nodeId))return!0;if(void 0!==n.error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send routeMessage from ${n} to ${i}`,{err:t}),!1}return!0}async forwardMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{if(void 0!==(await this.getClient().forwardMessage(t,r)).error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send forwardMessage from ${n} to ${i}`,{err:t}),!1}return!0}}const TG=new Bv("RecursiveOperationRpcRemote");class _G extends jz{async routeRequest(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const e=await this.getClient().routeRequest(t,r);if(void 0!==e.error)return TG.trace("Next hop responded with error "+e.error),!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return TG.debug(`Failed to send routeRequest message from ${n} to ${i}`,{err:t}),!1}return!0}}const NG=new Bv("RoutingSession");class MG extends YK{routerRpcRemote;recursiveOperationRpcRemote;constructor(e,t,r){super(e),this.routerRpcRemote=new PG(t,e,r,yz,2e3),this.recursiveOperationRpcRemote=new _G(t,e,r,bz,2e3)}getRouterRpcRemote(){return this.routerRpcRemote}getRecursiveOperationRpcRemote(){return this.recursiveOperationRpcRemote}}var xG;!function(e){e[e.ROUTE=0]="ROUTE",e[e.FORWARD=1]="FORWARD",e[e.RECURSIVE=2]="RECURSIVE"}(xG||(xG={}));class OG extends Sl{sessionId=xF();ongoingRequests=new Set;contactedPeers=new Set;failedHopCounter=0;successfulHopCounter=0;stopped=!1;options;constructor(e){super(),this.options=e}onRequestFailed(e){if(NG.trace("onRequestFailed() sessionId: "+this.sessionId),this.stopped)return;if(this.ongoingRequests.has(e)&&this.ongoingRequests.delete(e),this.deleteParallelRootIfSource(e),this.failedHopCounter+=1,this.failedHopCounter>=2)return NG.trace(`Stopping routing after 2 failed attempts for sessionId: ${this.sessionId}`),void this.emitFailure();const t=this.updateAndGetRoutablePeers();0===t.length&&0===this.ongoingRequests.size?(NG.trace("routing failed, emitting routingFailed sessionId: "+this.sessionId),this.emitFailure()):(NG.trace("routing failed, retrying to route sessionId: "+this.sessionId+" failedHopCounter: "+this.failedHopCounter),this.sendMoreRequests(t))}emitFailure(){this.successfulHopCounter>=1?this.emit("partialSuccess"):this.emit("routingFailed")}onRequestSucceeded(){if(NG.trace("onRequestSucceeded() sessionId: "+this.sessionId),this.stopped)return;if(this.successfulHopCounter+=1,this.successfulHopCounter>=this.options.parallelism)return void this.emit("routingSucceeded");const e=this.updateAndGetRoutablePeers();0===e.length?this.emit("routingSucceeded"):e.length>0&&0===this.ongoingRequests.size&&this.sendMoreRequests(e)}async sendRouteMessageRequest(e){if(this.stopped)return!1;const t={...this.options.routedMessage,routingPath:this.options.routedMessage.routingPath.concat([this.options.localPeerDescriptor])};return this.options.mode===xG.FORWARD?e.getRouterRpcRemote().forwardMessage(t):this.options.mode===xG.RECURSIVE?e.getRecursiveOperationRpcRemote().routeRequest(t):e.getRouterRpcRemote().routeMessage(t)}updateAndGetRoutablePeers(){NG.trace("getRoutablePeers() sessionId: "+this.sessionId);const e=CG(this.options.routedMessage),t=e?Xj(e):void 0,r=Zj(this.options.routedMessage.target);let n;if(this.options.routingTablesCache.has(r,t)&&this.options.routingTablesCache.get(r,t).getSize()>0)n=this.options.routingTablesCache.get(r,t);else{n=new rq({referenceId:Zj(this.options.routedMessage.target),maxSize:5,allowToContainReferenceId:!0,nodeIdDistanceLimit:t});const e=this.options.getConnections().map((e=>new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator)));n.addContacts(e),this.options.routingTablesCache.set(r,n,t)}return n.getClosestContacts().filter((e=>!this.contactedPeers.has(e.getNodeId())&&!this.options.excludedNodeIds.has(e.getNodeId())))}sendMoreRequests(e){if(NG.trace("sendMoreRequests() sessionId: "+this.sessionId),!this.stopped)if(0!==e.length)for(;this.ongoingRequests.size<this.options.parallelism&&e.length>0&&!this.stopped;){const t=e.shift();NG.trace(`Sending routeMessage request to contact: ${Xj(t.getPeerDescriptor())} (sessionId=${this.sessionId})`),this.contactedPeers.add(t.getNodeId()),this.ongoingRequests.add(t.getNodeId()),this.addParallelRootIfSource(t.getNodeId()),setImmediate((async()=>{try{await this.sendRouteMessageRequest(t)?this.onRequestSucceeded():this.onRequestFailed(t.getNodeId())}catch(e){NG.debug("Unable to route message ",{err:e})}finally{NG.trace("sendRouteMessageRequest returned")}}))}else this.emitFailure()}addParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&this.options.routedMessage.parallelRootNodeIds.push(e)}deleteParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&Ej(this.options.routedMessage.parallelRootNodeIds,e)}stop(){this.stopped=!0,this.emit("stopped"),this.removeAllListeners()}}const DG=new Bv("RecursiveOperationSessionRpcRemote");class BG extends jz{sendResponse(e,t,r,n){const i={routingPath:e,closestConnectedNodes:t,dataEntries:r,noCloserNodesFound:n};this.getClient().sendResponse(i,this.formDhtRpcOptions()).catch((e=>{DG.trace("Failed to send RecursiveOperationResponse")}))}}const LG=new Bv("RecursiveOperationSessionRpcLocal");class FG{options;constructor(e){this.options=e}async sendResponse(e,t){const r=Xj(t.incomingSourceDescriptor);return LG.trace("RecursiveOperationResponse arrived: "+JSON.stringify(e)),this.options.onResponseReceived(r,e.routingPath,e.closestConnectedNodes,e.dataEntries,e.noCloserNodesFound),{}}}const UG=1e4;class jG extends Sl{id=xF();rpcCommunicator;results;foundData=new Map;allKnownHops=new Set;reportedHops=new Set;timeoutTask;completionEventEmitted=!1;noCloserNodesReceivedCounter=0;noCloserNodesReceivedFrom=new Set;options;constructor(e){super(),this.options=e,this.results=new rq({referenceId:e.targetId,maxSize:10,allowToContainReferenceId:!0}),this.rpcCommunicator=new lK(this.id,e.transport,{rpcRequestTimeout:UG}),this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new FG({onResponseReceived:(e,t,r,n,i)=>{this.onResponseReceived(e,t,r,n,i)}});this.rpcCommunicator.registerRpcNotification(Oq,"sendResponse",((t,r)=>e.sendResponse(t,r)))}start(e){const t=this.wrapRequest(e);this.options.doRouteRequest(t)}wrapRequest(e){const t={sessionId:this.getId(),operation:this.options.operation};return{message:{messageId:xF(),serviceId:e,body:{oneofKind:"recursiveOperationRequest",recursiveOperationRequest:t}},requestId:xF(),target:Yj(this.options.targetId),sourcePeer:this.options.localPeerDescriptor,reachableThrough:[],routingPath:[],parallelRootNodeIds:[]}}isCompleted(){const e=new Set(this.allKnownHops);return this.reportedHops.forEach((t=>{e.delete(t)})),this.noCloserNodesReceivedCounter>=1&&0===e.size&&(!(this.options.operation!==yq.FETCH_DATA||!(this.hasNonStaleData()||this.noCloserNodesReceivedCounter>=this.options.waitedRoutingPathCompletions))||this.options.operation!==yq.FETCH_DATA)}hasNonStaleData(){return Array.from(this.foundData.values()).some((e=>!1===e.stale))}onResponseReceived(e,t,r,n,i){this.addKnownHops(t),t.length>=1&&this.setHopAsReported(t[t.length-1]),r.forEach((e=>{this.results.addContact(new YK(e))})),this.processFoundData(n),(i||this.noCloserNodesReceivedFrom.has(e))&&this.onNoCloserPeersFound(e)}addKnownHops(e){const t=Xj(this.options.localPeerDescriptor);e.forEach((e=>{const r=Xj(e);t!==r&&this.allKnownHops.add(r)}))}setHopAsReported(e){const t=Xj(this.options.localPeerDescriptor),r=Xj(e);t!==r&&this.reportedHops.add(r),this.isCompleted()&&!this.completionEventEmitted&&this.isCompleted()&&(this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.emit("completed"),this.completionEventEmitted=!0)}processFoundData(e){e.forEach((e=>{const t=Zj(e.creator),r=this.foundData.get(t);(!r||r.createdAt<e.createdAt||r.createdAt<=e.createdAt&&e.deleted)&&this.foundData.set(t,e)}))}onNoCloserPeersFound(e){this.noCloserNodesReceivedCounter+=1,this.noCloserNodesReceivedFrom.add(e),this.isCompleted()?(this.emit("completed"),this.completionEventEmitted=!0,this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0)):this.timeoutTask||this.completionEventEmitted||(this.timeoutTask=setTimeout((()=>{this.completionEventEmitted||(this.emit("completed"),this.completionEventEmitted=!0)}),4e3))}getResults(){return{closestNodes:this.results.getClosestContacts().map((e=>e.getPeerDescriptor())),dataEntries:Array.from(this.foundData.values())}}getId(){return this.id}stop(){this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.rpcCommunicator.destroy(),this.emit("completed")}}const qG=new Bv("RouterRpcLocal"),zG=(e,t)=>({requestId:e.requestId,error:t});class KG{options;constructor(e){this.options=e}async routeMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?(qG.trace(`routing message targeted to self ${e.requestId}`),this.options.setForwardingEntries(e),this.options.handleMessage(e.message),zG(e)):this.options.doRouteMessage(e))}async forwardMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Forwarding message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received forward routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?this.forwardToDestination(e):this.options.doRouteMessage(e,xG.FORWARD))}forwardToDestination(e){qG.trace(`Forwarding found message targeted to self ${e.requestId}`);const t=e.message;return eq(this.options.localPeerDescriptor,t.targetDescriptor)?(this.options.handleMessage(t),zG(e)):this.options.doRouteMessage({...e,requestId:xF(),target:t.targetDescriptor.nodeId})}}const GG=new Bv("RecursiveOperationRpcLocal");class VG{options;constructor(e){this.options=e}async routeRequest(e){if(this.options.isMostLikelyDuplicate(e.requestId))return zG(e,vq.DUPLICATE);const t=Xj(CG(e)??e.sourcePeer);return GG.trace(`Received routeRequest call from ${t}`),this.options.addToDuplicateDetector(e.requestId),this.options.doRouteRequest(e)}}const HG=new Bv("RecursiveOperationManager");class $G{ongoingSessions=new Map;stopped=!1;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new VG({doRouteRequest:e=>this.doRouteRequest(e),addContact:e=>this.options.addContact(e),isMostLikelyDuplicate:e=>this.options.router.isMostLikelyDuplicate(e),addToDuplicateDetector:e=>this.options.router.addToDuplicateDetector(e)});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeRequest",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeRequest(t)))}async execute(e,t,r,n=!0){if(this.stopped)return{closestNodes:[]};const i=new jG({transport:this.options.sessionTransport,targetId:e,localPeerDescriptor:this.options.localPeerDescriptor,waitedRoutingPathCompletions:this.options.connectionsView.getConnectionCount()>1?2:1,operation:t,doRouteRequest:e=>this.doRouteRequest(e,r)});if(0===this.options.connectionsView.getConnectionCount()){const t=Array.from(this.options.localDataStore.values(e));return i.onResponseReceived(Xj(this.options.localPeerDescriptor),[this.options.localPeerDescriptor],[this.options.localPeerDescriptor],t,!0),i.getResults()}if(this.ongoingSessions.set(i.getId(),i),!0===n)try{const e=eE(i,"completed",UG);i.start(this.options.serviceId),await e}catch(e){HG.debug("start failed",{err:e})}else i.start(this.options.serviceId),await Qv(50);if(t===yq.FETCH_DATA){const t=Array.from(this.options.localDataStore.values(e));t.length>0&&this.sendResponse([this.options.localPeerDescriptor],this.options.localPeerDescriptor,i.getId(),[],t,!0)}else t===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(e,Xj(this.options.localPeerDescriptor));return this.ongoingSessions.delete(i.getId()),i.stop(),i.getResults()}sendResponse(e,t,r,n,i,s=!1){if(eq(this.options.localPeerDescriptor,t)&&this.ongoingSessions.has(r))this.ongoingSessions.get(r).onResponseReceived(Xj(this.options.localPeerDescriptor),e,n,i,s);else{const o=new lK(r,this.options.sessionTransport,{rpcRequestTimeout:UG});new BG(this.options.localPeerDescriptor,t,o,vz,1e4).sendResponse(e,n,i,s),o.destroy()}}doRouteRequest(e,t){if(this.stopped)return zG(e,vq.STOPPED);const r=Zj(e.target),n=e.message.body.recursiveOperationRequest,i=this.getClosestConnectedNodes(r,5),s=n.operation===yq.FETCH_DATA?Array.from(this.options.localDataStore.values(r)):[];if(n.operation===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(r,Xj(e.sourcePeer)),yw(this.options.localPeerDescriptor.nodeId,e.target))return this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,!0),zG(e);{const o=this.options.router.doRouteMessage(e,xG.RECURSIVE,t);if(void 0===o.error||o.error===vq.NO_TARGETS){const t=o.error===vq.NO_TARGETS||i.length>0&&CG(e)&&!this.isPeerCloserToIdThanSelf(i[0],r);this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,t)}return o}}getClosestConnectedNodes(e,t){const r=this.options.connectionsView.getConnections().map((e=>this.options.createDhtNodeRpcRemote(e))),n=new rq({referenceId:e,maxSize:t,allowToContainReferenceId:!0});return n.addContacts(r),n.getClosestContacts(t).map((e=>e.getPeerDescriptor()))}isPeerCloserToIdThanSelf(e,t){const r=Yj(t);return Qj(e.nodeId,r)<Qj(this.options.localPeerDescriptor.nodeId,r)}stop(){this.stopped=!0,this.ongoingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingSessions.clear()}}const WG=(e,t)=>e+(t??""),JG={max:1e3,maxAge:15e3};class QG{tables=new Mj(JG);get(e,t){return this.tables.get(WG(e,t))}set(e,t,r){this.tables.set(WG(e,r),t)}has(e,t){return this.tables.has(WG(e,t))}onNodeDisconnected(e){this.tables.forEach((t=>t.removeContact(e)))}onNodeConnected(e){this.tables.forEach((t=>t.addContact(e)))}reset(){this.tables.forEach((e=>e.stop())),this.tables.clear()}}const ZG=new Bv("Router");class YG{forwardingTable=new Map;routingTablesCache=new QG;ongoingRoutingSessions=new Map;duplicateRequestDetector=new nq(1e4);stopped=!1;options;messagesRouted=0;messagesSent=0;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new KG({doRouteMessage:(e,t)=>this.doRouteMessage(e,t),setForwardingEntries:e=>this.setForwardingEntries(e),duplicateRequestDetector:this.duplicateRequestDetector,localPeerDescriptor:this.options.localPeerDescriptor,handleMessage:this.options.handleMessage});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeMessage(t))),this.options.rpcCommunicator.registerRpcMethod(jq,qq,"forwardMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.forwardMessage(t)))}send(e,t){e.sourceDescriptor=this.options.localPeerDescriptor;const r=e.targetDescriptor,n=this.forwardingTable.get(Xj(r));if(n&&n.peerDescriptors.length>0){const r={message:e,requestId:xF(),target:n.peerDescriptors[0].nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(r,xG.FORWARD);if(void 0!==i.error){const e="Could not forward message with error "+i.error;throw ZG.debug(e),new Error(e)}}else{const n={message:e,requestId:xF(),target:r.nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(n,xG.ROUTE);if(void 0!==i.error){const e="Could not route message with error "+i.error;throw ZG.debug(e),new Error(e)}}this.messagesSent+=1}doRouteMessage(e,t=xG.ROUTE,r){if(this.stopped)return zG(e,vq.STOPPED);ZG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)}`);const n=this.createRoutingSession(e,t,r),i=n.updateAndGetRoutablePeers();if(i.length>0){this.addRoutingSession(n),ZG.trace("starting to raceForEvent from routingSession: "+n.sessionId);const t=tE(n,["routingSucceeded","partialSuccess","routingFailed","stopped"],1e4);return setImmediate((async()=>{try{await t,ZG.trace("raceForEvent ended from routingSession: "+n.sessionId)}catch{ZG.trace("raceForEvent timed out for routingSession "+n.sessionId)}n.stop(),this.removeRoutingSession(n.sessionId)})),n.sendMoreRequests(i),this.messagesRouted+=1,zG(e)}return ZG.trace("no targets",{sessionId:n.sessionId}),zG(e,vq.NO_TARGETS)}createRoutingSession(e,t,r){const n=new Set(e.routingPath.map((e=>Xj(e))));return r&&n.add(r),e.parallelRootNodeIds.forEach((e=>{n.add(e)})),new OG({rpcCommunicator:this.options.rpcCommunicator,localPeerDescriptor:this.options.localPeerDescriptor,routedMessage:e,parallelism:eq(this.options.localPeerDescriptor,e.sourcePeer)?2:1,mode:t,excludedNodeIds:n,routingTablesCache:this.routingTablesCache,getConnections:this.options.getConnections})}isMostLikelyDuplicate(e){return this.duplicateRequestDetector.isMostLikelyDuplicate(e)}addToDuplicateDetector(e){this.duplicateRequestDetector.add(e)}addRoutingSession(e){this.ongoingRoutingSessions.set(e.sessionId,e)}removeRoutingSession(e){this.ongoingRoutingSessions.delete(e)}onNodeConnected(e){const t=new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator);this.routingTablesCache.onNodeConnected(t)}onNodeDisconnected(e){this.routingTablesCache.onNodeDisconnected(Xj(e))}resetCache(){this.routingTablesCache.reset()}stop(){this.stopped=!0,this.ongoingRoutingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingRoutingSessions.clear(),this.forwardingTable.forEach((e=>{clearTimeout(e.timeout)})),this.forwardingTable.clear(),this.duplicateRequestDetector.clear(),this.routingTablesCache.reset()}getDiagnosticInfo(){return{messagesRouted:this.messagesRouted,messagesSent:this.messagesSent}}setForwardingEntries(e){const t=e.reachableThrough.filter((e=>!eq(e,this.options.localPeerDescriptor)));if(t.length>0){const r=Xj(e.sourcePeer);if(this.forwardingTable.has(r)){const e=this.forwardingTable.get(r);clearTimeout(e.timeout),this.forwardingTable.delete(r)}const n={peerDescriptors:t,timeout:setTimeout((()=>{this.forwardingTable.delete(r)}),1e4)};this.forwardingTable.set(r,n)}}}class XG{maxTtl;constructor(e){this.maxTtl=e}store=new Map;storeEntry(e){const t=Zj(e.key),r=Zj(e.creator);if(this.store.has(t)||this.store.set(t,new yE((e=>Math.min(e.ttl,this.maxTtl)))),this.store.get(t).has(r)){const n=1e3*e.createdAt.seconds+e.createdAt.nanos/1e6,i=this.store.get(t).get(r);if(1e3*i.createdAt.seconds+i.createdAt.nanos/1e6>=n)return!1}return this.store.get(t).set(r,e),!0}markAsDeleted(e,t){const r=this.store.get(e);if(!r?.has(t))return!1;return r.get(t).deleted=!0,!0}*values(e){if(void 0!==e){const t=this.store.get(e);void 0!==t&&(yield*t.values())}else for(const e of this.store.values())yield*e.values()}keys(){return this.store.keys()}setAllEntriesAsStale(e){this.store.get(e)?.forEach((e=>{e.stale=!0}))}deleteEntry(e,t){const r=this.store.get(e)?.get(t);r&&(this.store.get(e)?.delete(t),0===this.store.get(e)?.size()&&this.store.delete(e))}clear(){this.store.forEach((e=>e.clear())),this.store.clear()}}const eV=new Bv("StoreRpcLocal");class tV{options;constructor(e){this.options=e}async storeData(e){eV.trace("storeData()");const t=Zj(e.key),r=this.isLocalNodeStorer(t);return this.options.localDataStore.storeEntry({key:e.key,data:e.data,creator:e.creator,createdAt:e.createdAt,storedAt:mq.now(),ttl:e.ttl,stale:!r,deleted:!1}),r||this.options.localDataStore.setAllEntriesAsStale(t),{}}async replicateData(e,t){eV.trace("server-side replicateData()");const r=e.entry;this.options.localDataStore.storeEntry(r)&&this.replicateDataToNeighbors(t.incomingSourceDescriptor,e.entry);const n=Zj(r.key);return this.isLocalNodeStorer(n)||this.options.localDataStore.setAllEntriesAsStale(n),eV.trace("server-side replicateData() at end"),{}}isLocalNodeStorer(e){return this.options.getStorers(e).some((e=>eq(e,this.options.localPeerDescriptor)))}replicateDataToNeighbors(e,t){const r=Zj(t.key),n=this.options.getStorers(r);(eq(n[0],this.options.localPeerDescriptor)?n:[n[0]]).filter((t=>!eq(t,e)&&!eq(t,this.options.localPeerDescriptor))).forEach((e=>{setImmediate((()=>{pE((()=>this.options.replicateDataToContact(t,e)))}))}))}}const rV=new Bv("StoreManager");class nV{options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new tV({localPeerDescriptor:this.options.localPeerDescriptor,localDataStore:this.options.localDataStore,replicateDataToContact:(e,t)=>this.replicateDataToContact(e,t),getStorers:e=>this.getStorers(e)});this.options.rpcCommunicator.registerRpcMethod(Sq,kq,"storeData",(t=>e.storeData(t))),this.options.rpcCommunicator.registerRpcNotification(Iq,"replicateData",((t,r)=>e.replicateData(t,r)))}onContactAdded(e){for(const t of this.options.localDataStore.keys())this.replicateAndUpdateStaleState(t,e)}replicateAndUpdateStaleState(e,t){const r=this.getStorers(e),n=r.filter((e=>!eq(e,t)));eq(n[0],this.options.localPeerDescriptor)?r.some((e=>eq(e,t)))&&setImmediate((async()=>{const r=Array.from(this.options.localDataStore.values(e));await Promise.all(r.map((async e=>this.replicateDataToContact(e,t))))})):r.some((e=>eq(e,this.options.localPeerDescriptor)))||this.options.localDataStore.setAllEntriesAsStale(e)}async replicateDataToContact(e,t){const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!0)}catch(e){rV.trace("replicateData() threw an exception "+e)}}async storeDataToDht(e,t,r){rV.debug(`Storing data to DHT ${this.options.serviceId}`);const n=(await this.options.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes,i=[],s=this.options.highestTtl,o=mq.now();for(let a=0;a<n.length&&i.length<this.options.redundancyFactor;a++){const c=Yj(e),u=Yj(r);if(eq(this.options.localPeerDescriptor,n[a])){this.options.localDataStore.storeEntry({key:c,data:t,creator:u,createdAt:o,storedAt:mq.now(),ttl:s,stale:!1,deleted:!1}),i.push(n[a]);continue}const l=this.options.createRpcRemote(n[a]);try{await l.storeData({key:c,data:t,creator:u,createdAt:o,ttl:s}),i.push(n[a]),rV.trace("remote.storeData() success")}catch(e){rV.trace("remote.storeData() threw an exception "+e)}}return i}async replicateDataToClosestNodes(){const e=Array.from(this.options.localDataStore.values());await Promise.all(e.map((async e=>{const t=Zj(e.key),r=XK(t,this.options.getNeighbors(),{maxCount:this.options.redundancyFactor});await Promise.all(r.map((async t=>{const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!1)}catch(e){rV.trace("Failed to replicate data in replicateDataToClosestNodes",{err:e})}})))})))}getStorers(e,t){return XK(e,[...this.options.getNeighbors(),this.options.localPeerDescriptor],{maxCount:this.options.redundancyFactor,excludedNodeIds:void 0!==t?new Set([Xj(t)]):void 0})}async destroy(){await this.replicateDataToClosestNodes()}}class iV extends jz{async storeData(e){const t=this.formDhtRpcOptions();try{await this.getClient().storeData(e,t)}catch(e){const t=Xj(this.getPeerDescriptor()),r=Xj(this.getLocalPeerDescriptor());throw new Error(`Could not store data to ${t} from ${r} ${e}`)}}async replicateData(e,t){const r=this.formDhtRpcOptions({timeout:Fz,notification:!0,connect:t});return this.getClient().replicateData(e,r)}}const sV=new Bv("DhtNode");class oV extends Sl{options;rpcCommunicator;transport;localPeerDescriptor;router;storeManager;localDataStore;recursiveOperationManager;peerDiscovery;peerManager;connectionsView;connectionLocker;started=!1;abortController=new AbortController;constructor(e){super(),this.options=aE({serviceId:SG,joinParallelism:3,maxContactCount:200,numberOfNodesPerKBucket:8,joinNoProgressLimit:5,dhtJoinTimeout:6e4,peerDiscoveryQueryBatchSize:5,maxConnections:80,storeHighestTtl:6e4,storeMaxTtl:6e4,networkConnectivityTimeout:1e4,storageRedundancyFactor:5,metricsContext:new $v},e),this.validateOptions(),this.localDataStore=new XG(this.options.storeMaxTtl),this.send=this.send.bind(this)}validateOptions(){if(void 0!==this.options.nodeId){if(!/^[0-9a-fA-F]+$/.test(this.options.nodeId))throw new Error("Invalid nodeId, the nodeId should be a hex string");if(40!==this.options.nodeId.length)throw new Error("Invalid nodeId, the length of the nodeId should be 40")}if(void 0!==this.options.peerDescriptor&&20!==this.options.peerDescriptor.nodeId.length)throw new Error("Invalid peerDescriptor, the length of the nodeId should be 20 bytes");if(void 0!==this.options.transport&&void 0===this.options.connectionsView)throw new Error("connectionsView is required when transport is given")}async start(){if(this.started||this.abortController.signal.aborted)return;if(sV.trace(`Starting new Streamr Network DHT Node with serviceId ${this.options.serviceId}`),this.started=!0,this.options.websocketPortRange=void 0,this.options.peerDescriptor&&(this.options.peerDescriptor.websocket=void 0),this.options.transport)this.transport=this.options.transport,this.connectionsView=this.options.connectionsView,this.connectionLocker=this.options.connectionLocker,this.localPeerDescriptor=this.transport.getLocalPeerDescriptor();else{const e={transport:this,entryPoints:this.options.entryPoints,iceServers:this.options.iceServers,webrtcAllowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,webrtcDatachannelBufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,webrtcDatachannelBufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,webrtcPortRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize,websocketServerEnableTls:this.options.websocketServerEnableTls,tlsCertificate:this.options.tlsCertificate,externalIp:this.options.externalIp,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder,createLocalPeerDescriptor:e=>this.generatePeerDescriptorCallBack(e)};this.options.peerDescriptor?.websocket?(e.websocketHost=this.options.peerDescriptor.websocket.host,e.websocketPortRange={min:this.options.peerDescriptor.websocket.port,max:this.options.peerDescriptor.websocket.port}):this.options.websocketPortRange&&(e.websocketHost=this.options.websocketHost,e.websocketPortRange=this.options.websocketPortRange);const t=new Yz({createConnectorFacade:()=>new WK(e),maxConnections:this.options.maxConnections,metricsContext:this.options.metricsContext,allowIncomingPrivateConnections:this.options.allowIncomingPrivateConnections??!1});await t.start(),this.connectionsView=t,this.connectionLocker=t,this.transport=t}this.rpcCommunicator=new Iz(this.options.serviceId,((e,t)=>this.transport.send(e,t)),{rpcRequestTimeout:this.options.rpcRequestTimeout}),oE(this.transport,"message",(e=>this.handleMessageFromTransport(e)),this.abortController.signal),this.initPeerManager(),this.peerDiscovery=new RG({localPeerDescriptor:this.localPeerDescriptor,joinNoProgressLimit:this.options.joinNoProgressLimit,joinTimeout:this.options.dhtJoinTimeout,serviceId:this.options.serviceId,parallelism:this.options.joinParallelism,connectionLocker:this.connectionLocker,peerManager:this.peerManager,abortSignal:this.abortController.signal,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.router=new YG({rpcCommunicator:this.rpcCommunicator,localPeerDescriptor:this.localPeerDescriptor,handleMessage:e=>this.handleMessageFromRouter(e),getConnections:()=>this.connectionsView.getConnections()}),this.recursiveOperationManager=new $G({rpcCommunicator:this.rpcCommunicator,router:this.router,sessionTransport:this,connectionsView:this.connectionsView,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,localDataStore:this.localDataStore,addContact:e=>this.peerManager.addContact(e),createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.storeManager=new nV({rpcCommunicator:this.rpcCommunicator,recursiveOperationManager:this.recursiveOperationManager,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,highestTtl:this.options.storeHighestTtl,redundancyFactor:this.options.storageRedundancyFactor,localDataStore:this.localDataStore,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),createRpcRemote:e=>new iV(this.localPeerDescriptor,e,this.rpcCommunicator,wz,this.options.rpcRequestTimeout)}),this.on("nearbyContactAdded",(e=>{this.storeManager.onContactAdded(e)})),this.bindRpcLocalMethods();const e=[];!0===this.options.periodicallyPingNeighbors&&e.push((()=>this.peerManager.getNeighbors().map((e=>this.createDhtNodeRpcRemote(e.getPeerDescriptor()))))),!0===this.options.periodicallyPingRingContacts&&e.push((()=>this.peerManager.getRingContacts().getAllContacts()));for(const t of e)await Jv((async()=>{const e=t();await this.peerManager.pruneOfflineNodes(e)}),6e4,!1,this.abortController.signal)}initPeerManager(){this.peerManager=new bG({numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,maxContactCount:this.options.maxContactCount,localNodeId:this.getNodeId(),localPeerDescriptor:this.localPeerDescriptor,connectionLocker:this.connectionLocker,lockId:this.options.serviceId,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e),hasConnection:e=>this.connectionsView.hasConnection(e),neighborPingLimit:this.options.neighborPingLimit}),this.peerManager.on("nearbyContactRemoved",(e=>{this.emit("nearbyContactRemoved",e)})),this.peerManager.on("nearbyContactAdded",(e=>this.emit("nearbyContactAdded",e))),this.peerManager.on("randomContactRemoved",(e=>this.emit("randomContactRemoved",e))),this.peerManager.on("randomContactAdded",(e=>this.emit("randomContactAdded",e))),this.peerManager.on("ringContactRemoved",(e=>{this.emit("ringContactRemoved",e)})),this.peerManager.on("ringContactAdded",(e=>{this.emit("ringContactAdded",e)})),this.peerManager.on("kBucketEmpty",(()=>{this.peerDiscovery.isJoinOngoing()||(this.options.entryPoints&&this.options.entryPoints.length>0?setImmediate((async()=>{const e=new Set,t=new Set;await Promise.all(this.options.entryPoints.map((r=>this.peerDiscovery.rejoinDht(r,e,t))))})):this.emit("manualRejoinRequired"))})),oE(this.transport,"connected",(e=>{this.router.onNodeConnected(e),this.emit("connected",e)}),this.abortController.signal),oE(this.transport,"disconnected",((e,t)=>{if(void 0!==this.connectionLocker){const r=Xj(e);t?this.peerManager.removeContact(r):this.peerManager.removeNeighbor(r)}this.router.onNodeDisconnected(e),this.emit("disconnected",e,t)}),this.abortController.signal)}bindRpcLocalMethods(){if(!this.started||this.abortController.signal.aborted)return;const e=new tG({peerDiscoveryQueryBatchSize:this.options.peerDiscoveryQueryBatchSize,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),getClosestRingContactsTo:(e,t)=>this.getClosestRingContactsTo(e,t),addContact:e=>this.peerManager.addContact(e),removeContact:e=>this.removeContact(e)});this.rpcCommunicator.registerRpcMethod(Tq,_q,"getClosestPeers",((t,r)=>e.getClosestPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Nq,Mq,"getClosestRingPeers",((t,r)=>e.getClosestRingPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Dq,Bq,"ping",((t,r)=>e.ping(t,r))),this.rpcCommunicator.registerRpcNotification(Lq,"leaveNotice",((t,r)=>e.leaveNotice(r)));const t=new iG({executeRecursiveOperation:(e,t,r)=>this.recursiveOperationManager.execute(e,t,r),storeDataToDht:(e,t,r)=>this.storeDataToDht(e,t,r)});this.rpcCommunicator.registerRpcMethod(nz,iz,"externalFetchData",((e,r)=>t.externalFetchData(e,r)),{timeout:1e4}),this.rpcCommunicator.registerRpcMethod(Rq,Cq,"externalStoreData",((e,r)=>t.externalStoreData(e,r)),{timeout:1e4})}handleMessageFromTransport(e){e.serviceId===this.options.serviceId&&this.rpcCommunicator?.handleMessageFromPeer(e)}handleMessageFromRouter(e){e.serviceId===this.options.serviceId?this.rpcCommunicator?.handleMessageFromPeer(e):this.emit("message",e)}async generatePeerDescriptorCallBack(e){if(void 0!==this.options.peerDescriptor)this.localPeerDescriptor=this.options.peerDescriptor;else{let t;void 0!==this.options.region?(t=this.options.region,sV.debug(`Using region ${t} from options when generating local PeerDescriptor`)):void 0!==e.latitude&&void 0!==e.longitude?(t=((e,t)=>{const r=[];return Object.keys(Lj).forEach((n=>{const i=Lj[n],s=Bj({latitude:e,longitude:t},{latitude:i[1],longitude:i[2]});r.push([i[0],s])})),r.sort(((e,t)=>e[1]-t[1])),r[0][0]})(e.latitude,e.longitude),sV.debug(`Using region ${t} from GeoIP when generating local PeerDescriptor`)):(t=await(async(e=36e5)=>{if(void 0===zj||void 0===Kj||Date.now()-Kj>e){const e=await Gj();return zj=e,Kj=Date.now(),e}return zj})(),sV.debug(`Using region ${t} from CDN when generating local PeerDescriptor`)),this.localPeerDescriptor=await ZK(e,t,this.options.nodeId)}return this.localPeerDescriptor}getClosestContacts(e){return this.peerManager.getNearbyContacts().getClosestContacts(e).map((e=>e.getPeerDescriptor()))}getRandomContacts(e){return this.peerManager.getRandomContacts().getContacts(e).map((e=>e.getPeerDescriptor()))}getRingContacts(){const e=this.peerManager.getRingContacts().getClosestContacts();return{left:e.left.map((e=>e.getPeerDescriptor())),right:e.right.map((e=>e.getPeerDescriptor()))}}getClosestRingContactsTo(e,t){const r=this.peerManager.getClosestRingContactsTo(e,t);return{left:r.left.map((e=>e.getPeerDescriptor())),right:r.right.map((e=>e.getPeerDescriptor()))}}getNodeId(){return Xj(this.localPeerDescriptor)}getNeighborCount(){return this.peerManager.getNeighborCount()}removeContact(e){this.started&&this.peerManager.removeContact(e)}async send(e){if(!this.started||this.abortController.signal.aborted)return;const t=this.peerDiscovery.isJoinOngoing()?this.getConnectedEntryPoints():[];this.router.send(e,t)}getConnectedEntryPoints(){return void 0!==this.options.entryPoints?this.options.entryPoints.filter((e=>this.connectionsView.hasConnection(Xj(e)))):[]}async joinDht(e,t,r){if(!this.started)throw new Error("Cannot join DHT before calling start() on DhtNode");await this.peerDiscovery.joinDht(e,t,r)}async joinRing(){if(!this.started)throw new Error("Cannot join ring before calling start() on DhtNode");await this.peerDiscovery.joinRing()}async storeDataToDht(e,t,r){return this.executeRecursiveOperation((()=>this.storeManager.storeDataToDht(e,t,r??this.getNodeId())),(r=>this.storeDataToDhtViaPeer(e,t,r)))}async storeDataToDhtViaPeer(e,t,r){const n=new oG(this.localPeerDescriptor,r,this.rpcCommunicator,kz);return await n.storeData(e,t)}async fetchDataFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FETCH_DATA)).dataEntries??[]),(t=>this.fetchDataFromDhtViaPeer(e,t)))}async fetchDataFromDhtViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFetchData(e)}async executeRecursiveOperation(e,t){const r=this.getConnectedEntryPoints();return this.peerDiscovery.isJoinOngoing()&&r.length>0?t(oA(r)):e()}async deleteDataFromDht(e,t){this.abortController.signal.aborted||await this.recursiveOperationManager.execute(e,yq.DELETE_DATA,void 0,t)}async findClosestNodesFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes),(t=>this.findClosestNodesViaPeer(e,t)))}async findClosestNodesViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFindClosestNode(e)}getTransport(){return this.transport}getLocalPeerDescriptor(){return this.localPeerDescriptor}getNeighbors(){return this.started?this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())):[]}getConnectionsView(){return this.connectionsView}getLocalLockedConnectionCount(){return this.connectionLocker.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.connectionLocker.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.connectionLocker.getWeakLockedConnectionCount()}async waitForNetworkConnectivity(){await iE((()=>this.connectionsView.getConnectionCount()>0),this.options.networkConnectivityTimeout,100,this.abortController.signal)}hasJoined(){return this.peerDiscovery.isJoinCalled()}getDiagnosticInfo(){return{localPeerDescriptor:this.localPeerDescriptor,transport:this.transport.getDiagnosticInfo(),router:this.router.getDiagnosticInfo(),neighborCount:this.getNeighborCount(),nearbyContactCount:Array.from(this.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder()).length,randomContactCount:this.peerManager.getRandomContacts().getSize()}}async stop(){!this.abortController.signal.aborted&&this.started&&(sV.trace("stop()"),this.abortController.abort(),await this.storeManager.destroy(),this.localDataStore.clear(),this.peerManager?.stop(),this.rpcCommunicator.stop(),this.router.stop(),this.recursiveOperationManager.stop(),void 0===this.options.transport&&await this.transport.stop(),this.transport=void 0,this.connectionLocker=void 0,this.removeAllListeners())}createDhtNodeRpcRemote(e){return new nG(this.localPeerDescriptor,e,this.options.serviceId,this.rpcCommunicator,this.options.rpcRequestTimeout)}}var aV,cV,uV,lV,hV,dV,fV,pV,gV,mV;function yV(){if(lV)return uV;return lV=1,uV=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e},uV}!function(e){e[e.eu_central_1=0]="eu_central_1",e[e.eu_west_1=1]="eu_west_1",e[e.eu_west_2=2]="eu_west_2",e[e.eu_west_3=3]="eu_west_3",e[e.eu_north_1=4]="eu_north_1",e[e.us_east_1=5]="us_east_1",e[e.us_east_2=6]="us_east_2",e[e.us_west_1=7]="us_west_1",e[e.us_west_2=8]="us_west_2",e[e.ca_central_1=9]="ca_central_1",e[e.ap_south_1=10]="ap_south_1",e[e.ap_northeast_2=11]="ap_northeast_2",e[e.ap_southeast_1=12]="ap_southeast_1",e[e.ap_southeast_2=13]="ap_southeast_2",e[e.ap_northeast_1=14]="ap_northeast_1",e[e.sa_east_1=15]="sa_east_1"}(aV||(aV={})),new Bv("Simulator"),function(e){e.NONE="NONE",e.RANDOM="RANDOM",e.REAL="REAL",e.FIXED="FIXED"}(cV||(cV={}));var bV=function(){if(mV)return gV;mV=1;var e=function(){if(dV)return hV;dV=1;var e=yV(),t=Th(),r=$U();return hV=function(n,i){return r(t(n),e(i,0,n.length))},hV}(),t=function(){if(pV)return fV;pV=1;var e=yV(),t=$U(),r=nA();return fV=function(n,i){var s=r(n);return t(s,e(i,0,s.length))},fV}(),r=qu(),n=_d(),i=Ue();return gV=function(s,o,a){return o=(a?n(s,o,a):void 0===o)?1:i(o),(r(s)?e:t)(s,o)},gV}(),wV=n(bV);class vV{tail;head;length=0;static create(e=[]){return new vV(e)}constructor(e=[]){for(const t of e)this.push(t)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");const t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,t}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);const t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);const t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let t=0,r=e.length;t<r;t++)AV(this,e[t]);return this.length}unshift(...e){for(var t=0,r=e.length;t<r;t++)SV(this,e[t]);return this.length}pop(){if(!this.tail)return;const e=this.tail.value,t=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,t.list=void 0,this.length--,e}shift(){if(!this.head)return;const e=this.head.value,t=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,t.list=void 0,this.length--,e}forEach(e,t){t=t||this;for(let r=this.head,n=0;r;n++)e.call(t,r.value,n,this),r=r.next}forEachReverse(e,t){t=t||this;for(let r=this.tail,n=this.length-1;r;n--)e.call(t,r.value,n,this),r=r.prev}get(e){let t=0,r=this.head;for(;r&&t<e;t++)r=r.next;if(t===e&&r)return r.value}getReverse(e){let t=0,r=this.tail;for(;r&&t<e;t++)r=r.prev;if(t===e&&r)return r.value}map(e,t){t=t||this;const r=new vV;for(let n=this.head;n;)r.push(e.call(t,n.value,this)),n=n.next;return r}mapReverse(e,t){t=t||this;var r=new vV;for(let n=this.tail;n;)r.push(e.call(t,n.value,this)),n=n.prev;return r}reduce(e,t){let r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;n;i++)r=e(r,n.value,i),n=n.next;return r}reduceReverse(e,t){let r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(let t=this.length-1;n;t--)r=e(r,n.value,t),n=n.prev;return r}toArray(){const e=new Array(this.length);for(let t=0,r=this.head;r;t++)e[t]=r.value,r=r.next;return e}toArrayReverse(){const e=new Array(this.length);for(let t=0,r=this.tail;r;t++)e[t]=r.value,r=r.prev;return e}slice(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.head,i=0;for(i=0;n&&i<e;i++)n=n.next;for(;n&&i<t;i++,n=n.next)r.push(n.value);return r}sliceReverse(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.length,i=this.tail;for(;i&&n>t;n--)i=i.prev;for(;i&&n>e;n--,i=i.prev)r.push(i.value);return r}splice(e,t=0,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let n=this.head;for(let t=0;n&&t<e;t++)n=n.next;const i=[];for(let e=0;n&&e<t;e++)i.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(const e of r)n=EV(this,n,e);return i}reverse(){const e=this.head,t=this.tail;for(let t=e;t;t=t.prev){const e=t.prev;t.prev=t.next,t.next=e}return this.head=t,this.tail=e,this}}function EV(e,t,r){const n=t,i=t?t.next:e.head,s=new kV(r,n,i,e);return void 0===s.next&&(e.tail=s),void 0===s.prev&&(e.head=s),e.length++,s}function AV(e,t){e.tail=new kV(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function SV(e,t){e.head=new kV(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}class kV{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}}class RV{rpcCommunicator;constructor(e){this.rpcCommunicator=new lK("external-network-service",e)}registerRpcMethod(e,t,r,n){this.rpcCommunicator.registerRpcMethod(e,t,r,n)}createRpcClient(e){return iU(new e(this.rpcCommunicator.getRpcClientTransport()))}destroy(){this.rpcCommunicator.destroy()}}const CV=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},IV=new Bv("PeerDescriptorStoreManager");class PV{abortController;options;isLocalNodeStored_=!1;constructor(e){this.options=e,this.abortController=new AbortController}async fetchNodes(){IV.trace("Fetch data",{key:this.options.key});try{const e=await this.options.fetchDataFromDht(this.options.key);return e.filter((e=>!e.deleted)).map((e=>CV.unpack(e.data,Fq)))}catch{return[]}}async storeAndKeepLocalNode(){this.abortController.signal.aborted||(this.isLocalNodeStored_=!0,await this.storeLocalNode(),await this.keepLocalNode())}async storeLocalNode(){const e=this.options.localPeerDescriptor,t=CV.pack(e,Fq);try{await this.options.storeDataToDht(this.options.key,t)}catch{IV.warn("Failed to store local node",{key:this.options.key})}}async keepLocalNode(){await Jv((async()=>{IV.trace("Attempting to keep local node",{key:this.options.key});try{const e=await this.fetchNodes();(e.length<8||e.some((e=>eq(e,this.options.localPeerDescriptor))))&&await this.storeLocalNode()}catch{IV.debug("Failed to keep local node",{key:this.options.key})}}),this.options.storeInterval??6e4,!1,this.abortController.signal)}isLocalNodeStored(){return this.isLocalNodeStored_}async destroy(){this.abortController.abort(),await this.options.deleteDataFromDht(this.options.key,!1)}}const TV=new Bv("StreamPartNetworkSplitAvoidance");class _V{abortController;options;excludedNodes=new Set;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async avoidNetworkSplit(){this.running=!0,await(async(e,t,r,n=500,i=6)=>{for(let s=1;s<=i;s++){if(r.aborted)return;const i=n*2**s;try{await e()}catch{TV.trace(`${t} failed, retrying in ${i} ms`)}try{await Qv(i,r)}catch(e){TV.trace(`${e}`)}}})((async()=>{const e=(await this.options.discoverEntryPoints()).filter((e=>!this.excludedNodes.has(Xj(e))));if(await this.options.discoveryLayerNode.joinDht(e,!1,!1),this.options.discoveryLayerNode.getNeighborCount()<4){throw e.filter((e=>!this.options.discoveryLayerNode.getNeighbors().some((t=>eq(t,e))))).map((e=>Xj(e))).forEach((e=>this.excludedNodes.add(e))),new Error("Network split is still possible")}}),"avoid network split",this.abortController.signal,this.options.exponentialRunOfBaseDelay),this.running=!1,this.excludedNodes.clear(),TV.trace("Network split avoided")}isRunning(){return this.running}destroy(){this.abortController.abort()}}class NV{abortController;discoveryLayerNode;peerDescriptorStoreManager;constructor(e,t){this.discoveryLayerNode=e,this.peerDescriptorStoreManager=t}async reconnect(e=3e4){this.abortController=new AbortController,await Jv((async()=>{const e=await this.peerDescriptorStoreManager.fetchNodes();await this.discoveryLayerNode.joinDht(e),!this.peerDescriptorStoreManager.isLocalNodeStored()&&e.length<8&&await this.peerDescriptorStoreManager.storeAndKeepLocalNode(),this.discoveryLayerNode.getNeighborCount()>0&&this.abortController.abort()}),e,!0,this.abortController.signal)}isRunning(){return!!this.abortController&&!this.abortController.signal.aborted}destroy(){this.abortController?.abort()}}const MV=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var xV;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(xV||(xV={}));const OV=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>CV},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",xV]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>MV}])}};const DV=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var BV,LV,FV,UV,jV,qV;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(BV||(BV={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(LV||(LV={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(FV||(FV={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(UV||(UV={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(jV||(jV={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(qV||(qV={}));const zV=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"ttl",kind:"scalar",T:13}])}};const KV=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const GV=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV}])}};const VV=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>nH}])}};const HV=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>$V}])}};const $V=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"storedAt",kind:"message",T:()=>DV},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const WV=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const JV=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"requestId",kind:"scalar",T:9}])}};const QV=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const ZV=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>nH},{no:3,name:"requestId",kind:"scalar",T:9}])}};const YV=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",BV]}])}};const XV=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>nH},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>$V},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>nH}])}};const eH=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const tH=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const rH=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const nH=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",LV]},{no:3,name:"udp",kind:"message",T:()=>iH},{no:4,name:"tcp",kind:"message",T:()=>iH},{no:5,name:"websocket",kind:"message",T:()=>iH},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const iH=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const sH=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>nH},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>hH},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>nH},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>nH},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const oH=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",UV]}])}};const aH=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const cH=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>iH},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const uH=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>nH},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const lH=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",jV]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const hH=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>nH},{no:3,name:"targetDescriptor",kind:"message",T:()=>nH},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>OV},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>aH},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>cH},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>uH},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>lH},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>YV}])}};const dH=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const fH=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const pH=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const gH=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const mH=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const yH=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const bH=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const wH=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const vH=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",qV]}])}};const EH=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const AH=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const SH=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>$V}])}};const kH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const RH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>nH}])}};var CH,IH,PH,TH,_H;new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:WV,O:JV},{name:"getClosestRingPeers",options:{},I:QV,O:ZV},{name:"ping",options:{},I:eH,O:tH},{name:"leaveNotice",options:{},I:rH,O:MV}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:sH,O:oH},{name:"forwardMessage",options:{},I:sH,O:oH}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:sH,O:oH}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:zV,O:KV},{name:"replicateData",options:{},I:HV,O:MV}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:XV,O:MV}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:dH,O:MV}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:fH,O:MV},{name:"rtcOffer",options:{},I:pH,O:MV},{name:"rtcAnswer",options:{},I:gH,O:MV},{name:"iceCandidate",options:{},I:mH,O:MV}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:yH,O:wH},{name:"unlockRequest",options:{},I:bH,O:MV},{name:"gracefulDisconnect",options:{},I:vH,O:MV},{name:"setPrivate",options:{},I:EH,O:MV}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:AH,O:SH},{name:"externalStoreData",options:{},I:GV,O:VV},{name:"externalFindClosestNodes",options:{},I:kH,O:RH}]),e.ContentType=void 0,(CH=e.ContentType||(e.ContentType={}))[CH.JSON=0]="JSON",CH[CH.BINARY=1]="BINARY",e.EncryptionType=void 0,(IH=e.EncryptionType||(e.EncryptionType={}))[IH.NONE=0]="NONE",IH[IH.AES=1]="AES",function(e){e[e.RSA=0]="RSA",e[e.ML_KEM=1]="ML_KEM"}(PH||(PH={})),e.SignatureType=void 0,(TH=e.SignatureType||(e.SignatureType={}))[TH.ECDSA_SECP256K1_LEGACY=0]="ECDSA_SECP256K1_LEGACY",TH[TH.ECDSA_SECP256K1_EVM=1]="ECDSA_SECP256K1_EVM",TH[TH.ERC_1271=2]="ERC_1271",TH[TH.ML_DSA_87=3]="ML_DSA_87",TH[TH.ECDSA_SECP256R1=4]="ECDSA_SECP256R1",e.ProxyDirection=void 0,(_H=e.ProxyDirection||(e.ProxyDirection={}))[_H.PUBLISH=0]="PUBLISH",_H[_H.SUBSCRIBE=1]="SUBSCRIBE";const NH=new class extends wF{constructor(){super("MessageID",[{no:1,name:"streamId",kind:"scalar",T:9},{no:2,name:"streamPartition",kind:"scalar",T:5},{no:3,name:"timestamp",kind:"scalar",T:3,L:2},{no:4,name:"sequenceNumber",kind:"scalar",T:5},{no:5,name:"publisherId",kind:"scalar",T:12},{no:6,name:"messageChainId",kind:"scalar",T:9}])}};const MH=new class extends wF{constructor(){super("MessageRef",[{no:1,name:"timestamp",kind:"scalar",T:3,L:2},{no:2,name:"sequenceNumber",kind:"scalar",T:5}])}};const xH=new class extends wF{constructor(){super("StreamMessage",[{no:1,name:"messageId",kind:"message",T:()=>NH},{no:2,name:"previousMessageRef",kind:"message",T:()=>MH},{no:3,name:"signature",kind:"scalar",T:12},{no:4,name:"signatureType",kind:"enum",T:()=>["SignatureType",e.SignatureType]},{no:5,name:"contentMessage",kind:"message",oneof:"body",T:()=>OH},{no:6,name:"groupKeyRequest",kind:"message",oneof:"body",T:()=>DH},{no:7,name:"groupKeyResponse",kind:"message",oneof:"body",T:()=>BH}])}};const OH=new class extends wF{constructor(){super("ContentMessage",[{no:1,name:"content",kind:"scalar",T:12},{no:2,name:"contentType",kind:"enum",T:()=>["ContentType",e.ContentType]},{no:3,name:"encryptionType",kind:"enum",T:()=>["EncryptionType",e.EncryptionType]},{no:4,name:"groupKeyId",kind:"scalar",opt:!0,T:9},{no:5,name:"newGroupKey",kind:"message",T:()=>LH}])}};const DH=new class extends wF{constructor(){super("GroupKeyRequest",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"publicKey",kind:"scalar",T:12},{no:4,name:"groupKeyIds",kind:"scalar",repeat:2,T:9},{no:5,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const BH=new class extends wF{constructor(){super("GroupKeyResponse",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"groupKeys",kind:"message",repeat:2,T:()=>LH},{no:4,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const LH=new class extends wF{constructor(){super("EncryptedGroupKey",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12}])}};const FH=new class extends wF{constructor(){super("StreamPartHandshakeRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"concurrentHandshakeNodeId",kind:"scalar",opt:!0,T:12},{no:4,name:"neighborNodeIds",kind:"scalar",repeat:2,T:12},{no:5,name:"interleaveNodeId",kind:"scalar",opt:!0,T:12}])}};const UH=new class extends wF{constructor(){super("StreamPartHandshakeResponse",[{no:1,name:"accepted",kind:"scalar",T:8},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const jH=new class extends wF{constructor(){super("InterleaveRequest",[{no:1,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const qH=new class extends wF{constructor(){super("InterleaveResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const zH=new class extends wF{constructor(){super("LeaveStreamPartNotice",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"isEntryPoint",kind:"scalar",T:8}])}};const KH=new class extends wF{constructor(){super("NeighborUpdate",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"removeMe",kind:"scalar",T:8},{no:3,name:"neighborDescriptors",kind:"message",repeat:2,T:()=>nH}])}};const GH=new class extends wF{constructor(){super("ProxyConnectionRequest",[{no:1,name:"direction",kind:"enum",opt:!0,T:()=>["ProxyDirection",e.ProxyDirection]},{no:2,name:"userId",kind:"scalar",T:12}])}};const VH=new class extends wF{constructor(){super("ProxyConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const HH=new class extends wF{constructor(){super("TemporaryConnectionRequest",[])}};const $H=new class extends wF{constructor(){super("TemporaryConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const WH=new class extends wF{constructor(){super("CloseTemporaryConnection",[])}};const JH=new class extends wF{constructor(){super("StreamPartitionInfo",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"controlLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:3,name:"deprecatedContentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:4,name:"contentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>QH}])}};const QH=new class extends wF{constructor(){super("ContentDeliveryLayerNeighborInfo",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"rtt",kind:"scalar",opt:!0,T:5}])}};const ZH=new class extends wF{constructor(){super("ControlLayerInfo",[{no:1,name:"neighbors",kind:"message",repeat:2,T:()=>nH},{no:2,name:"connections",kind:"message",repeat:2,T:()=>nH}])}};const YH=new class extends wF{constructor(){super("NodeInfoRequest",[])}};const XH=new class extends wF{constructor(){super("NodeInfoResponse",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"streamPartitions",kind:"message",repeat:2,T:()=>JH},{no:3,name:"controlLayer",kind:"message",T:()=>ZH},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const e$=new class extends wF{constructor(){super("PauseNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9}])}};const t$=new class extends wF{constructor(){super("PauseNeighborResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const r$=new class extends wF{constructor(){super("ResumeNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9},{no:2,name:"fromTimestamp",kind:"scalar",T:3,L:2}])}},n$=new vF("ContentDeliveryRpc",[{name:"sendStreamMessage",options:{},I:xH,O:MV},{name:"leaveStreamPartNotice",options:{},I:zH,O:MV}]),i$=new vF("ProxyConnectionRpc",[{name:"requestConnection",options:{},I:GH,O:VH}]),s$=new vF("HandshakeRpc",[{name:"handshake",options:{},I:FH,O:UH},{name:"interleaveRequest",options:{},I:jH,O:qH}]),o$=new vF("NeighborUpdateRpc",[{name:"neighborUpdate",options:{},I:KH,O:KH}]),a$=new vF("TemporaryConnectionRpc",[{name:"openConnection",options:{},I:HH,O:$H},{name:"closeConnection",options:{},I:WH,O:MV}]),c$=new vF("NodeInfoRpc",[{name:"getInfo",options:{},I:YH,O:XH}]),u$=new vF("PlumtreeRpc",[{name:"pauseNeighbor",options:{},I:e$,O:t$},{name:"resumeNeighbor",options:{},I:r$,O:MV},{name:"sendMetadata",options:{},I:NH,O:MV}]);class l${_transport;typeName=n$.typeName;methods=n$.methods;options=n$.options;constructor(e){this._transport=e}sendStreamMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveStreamPartNotice(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class h${_transport;typeName=i$.typeName;methods=i$.methods;options=i$.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class d${_transport;typeName=s$.typeName;methods=s$.methods;options=s$.options;constructor(e){this._transport=e}handshake(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}interleaveRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class f${_transport;typeName=o$.typeName;methods=o$.methods;options=o$.options;constructor(e){this._transport=e}neighborUpdate(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class p${_transport;typeName=a$.typeName;methods=a$.methods;options=a$.options;constructor(e){this._transport=e}openConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}closeConnection(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class g${_transport;typeName=c$.typeName;methods=c$.methods;options=c$.options;constructor(e){this._transport=e}getInfo(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class m${_transport;typeName=u$.typeName;methods=u$.methods;options=u$.options;constructor(e){this._transport=e}pauseNeighbor(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}resumeNeighbor(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}sendMetadata(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const y$=new Bv("ContentDeliveryRpcRemote");class b$ extends jz{rtt;async sendStreamMessage(e,t){const r=this.formDhtRpcOptions({notification:!0,bufferWhileConnecting:t});this.getClient().sendStreamMessage(e,r).catch((()=>{y$.trace("Failed to sendStreamMessage")}))}leaveStreamPartNotice(e,t){const r={streamPartId:e,isEntryPoint:t},n=this.formDhtRpcOptions({notification:!0});this.getClient().leaveStreamPartNotice(r,n).catch((()=>{y$.debug("Failed to send leaveStreamPartNotice")}))}setRtt(e){this.rtt=e}getRtt(){return this.rtt}}const w$=new Bv("HandshakeRpcLocal");class v${options;constructor(e){this.options=e}async handshake(e,t){return this.handleRequest(e,t)}handleRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.ongoingInterleaves.has(n)?this.rejectHandshake(e):this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)||this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?this.acceptHandshake(e,r):this.options.neighbors.size(void 0!==e.interleaveNodeId?[Zj(e.interleaveNodeId)]:[])-this.options.ongoingInterleaves.size>=2&&this.options.neighbors.size()<=this.options.maxNeighborCount?this.acceptHandshakeWithInterleaving(e,r):this.rejectHandshake(e)}acceptHandshake(e,t){const r={requestId:e.requestId,accepted:!0};return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),r}rejectHandshake(e){return{requestId:e.requestId,accepted:!1}}acceptHandshakeWithInterleaving(e,t){const r=[];e.neighborNodeIds.forEach((e=>r.push(Zj(e)))),this.options.ongoingInterleaves.forEach((e=>r.push(e))),r.push(Xj(t)),void 0!==e.interleaveNodeId&&r.push(Zj(e.interleaveNodeId));const n=this.options.neighbors.getLast(r),i=n?n.getPeerDescriptor():void 0;if(n){const e=Xj(n.getPeerDescriptor()),r=this.options.createRpcRemote(n.getPeerDescriptor());this.options.ongoingInterleaves.add(e),r.interleaveRequest(t).then((e=>{e.accepted&&this.options.neighbors.remove(Xj(i))})).catch((()=>{})).finally((()=>{this.options.ongoingInterleaves.delete(e)}))}return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),{requestId:e.requestId,accepted:!0,interleaveTargetDescriptor:i}}async interleaveRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);try{return await this.options.handshakeWithInterleaving(e.interleaveTargetDescriptor,n),this.options.neighbors.remove(n),{accepted:!0}}catch(t){return w$.debug(`interleaveRequest to ${Xj(e.interleaveTargetDescriptor)} failed`,{err:t}),{accepted:!1}}}}const E$=new Bv("HandshakeRpcRemote");class A$ extends jz{async handshake(e,t,r,n){const i={streamPartId:e,requestId:xF(),neighborNodeIds:t.map((e=>Yj(e))),concurrentHandshakeNodeId:void 0!==r?Yj(r):void 0,interleaveNodeId:void 0!==n?Yj(n):void 0};try{const e=await this.getClient().handshake(i,this.formDhtRpcOptions());return{accepted:e.accepted,interleaveTargetDescriptor:e.interleaveTargetDescriptor}}catch(e){return E$.debug(`handshake to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}async interleaveRequest(e){const t={interleaveTargetDescriptor:e},r=this.formDhtRpcOptions({connect:!1,timeout:1e4});try{return{accepted:(await this.getClient().interleaveRequest(t,r)).accepted}}catch(e){return E$.debug(`interleaveRequest to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}}const S$=new Bv("Handshaker");class k${options;rpcLocal;constructor(e){this.options=e,this.rpcLocal=new v$({streamPartId:this.options.streamPartId,neighbors:this.options.neighbors,ongoingHandshakes:this.options.ongoingHandshakes,ongoingInterleaves:new Set,maxNeighborCount:this.options.maxNeighborCount,handshakeWithInterleaving:(e,t)=>this.handshakeWithInterleaving(e,t),createRpcRemote:e=>this.createRpcRemote(e),createContentDeliveryRpcRemote:e=>this.createContentDeliveryRpcRemote(e)}),this.options.rpcCommunicator.registerRpcMethod(jH,qH,"interleaveRequest",((e,t)=>this.rpcLocal.interleaveRequest(e,t)),{timeout:1e4}),this.options.rpcCommunicator.registerRpcMethod(FH,UH,"handshake",((e,t)=>this.rpcLocal.handshake(e,t)))}async attemptHandshakesOnContacts(e){return this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount-2?(S$.trace("Attempting parallel handshakes with 2 targets"),this.selectParallelTargetsAndHandshake(e)):this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?(S$.trace("Attempting handshake with new target"),this.selectNewTargetAndHandshake(e)):e}async selectParallelTargetsAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.selectParallelTargets(t);return r.forEach((e=>this.options.ongoingHandshakes.add(Xj(e.getPeerDescriptor())))),this.doParallelHandshakes(r,t)}selectParallelTargets(e){const t=new Map,r=()=>[...e,...Array.from(t.keys())];if(0===this.options.neighbors.size()){const e=this.options.nearbyNodeView.getFirst(r(),!0);if(e){const r=Xj(e.getPeerDescriptor());t.set(r,e)}}const n=this.options.leftNodeView.getFirst(r()),i=this.options.rightNodeView.getFirst(r());if(n&&t.set(Xj(n.getPeerDescriptor()),n),i&&t.set(Xj(i.getPeerDescriptor()),i),t.size<2){const e=this.options.nearbyNodeView.getFirst(r());e&&t.set(Xj(e.getPeerDescriptor()),e)}for(;t.size<2;){const e=this.options.randomNodeView.getRandom(r());if(!e)break;t.set(Xj(e.getPeerDescriptor()),e)}return Array.from(t.values()).map((e=>this.createRpcRemote(e.getPeerDescriptor())))}async doParallelHandshakes(e,t){return(await Promise.allSettled(Array.from(e.values()).map((async(t,r)=>{const n=0===r?e[1]:e[0],i=n?Xj(n.getPeerDescriptor()):void 0;return this.handshakeWithTarget(t,i)})))).forEach(((r,n)=>{"fulfilled"===r.status&&r.value||t.push(Xj(e[n].getPeerDescriptor()))})),t}async selectNewTargetAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.options.leftNodeView.getFirst(t)??this.options.rightNodeView.getFirst(t)??this.options.nearbyNodeView.getFirst(t)??this.options.randomNodeView.getRandom(t);if(r){await this.handshakeWithTarget(this.createRpcRemote(r.getPeerDescriptor()))||e.push(Xj(r.getPeerDescriptor()))}return e}async handshakeWithTarget(e,t){const r=Xj(e.getPeerDescriptor());this.options.ongoingHandshakes.add(r);const n=await e.handshake(this.options.streamPartId,this.options.neighbors.getIds(),t);return n.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(e.getPeerDescriptor())),n.interleaveTargetDescriptor&&await this.handshakeWithInterleaving(n.interleaveTargetDescriptor,r),this.options.ongoingHandshakes.delete(r),n.accepted}async handshakeWithInterleaving(e,t){const r=this.createRpcRemote(e),n=Xj(r.getPeerDescriptor());this.options.ongoingHandshakes.add(n);const i=await r.handshake(this.options.streamPartId,this.options.neighbors.getIds(),void 0,t);return i.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(r.getPeerDescriptor())),this.options.ongoingHandshakes.delete(n),i.accepted}createRpcRemote(e){return new A$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,d$,this.options.rpcRequestTimeout)}createContentDeliveryRpcRemote(e){return new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)}getOngoingHandshakes(){return this.options.ongoingHandshakes}}const R$=new Bv("NeighborFinder");class C${abortController;options;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async findNeighbors(e){if(!this.running)return;const t=await this.options.doFindNeighbors(e),r=new Set([...this.options.nearbyNodeView.getIds(),...this.options.leftNodeView.getIds(),...this.options.rightNodeView.getIds(),...this.options.randomNodeView.getIds()]).size;this.options.neighbors.size()<this.options.minCount&&t.length<r?Yy((()=>this.findNeighbors(t)),250,this.abortController.signal):0===this.options.neighbors.size()&&r>0?(R$.debug("No neighbors found yet contacts are available, restarting handshaking process"),Yy((()=>this.findNeighbors([])),250,this.abortController.signal)):this.running=!1}isRunning(){return this.running}start(e=[]){this.running||(this.running=!0,Yy((async()=>{await Promise.all([this.findNeighbors(e),this.findNeighbors(e)])}),100,this.abortController.signal))}stop(){this.running&&(this.running=!1,this.abortController.abort())}}class I${options;constructor(e){this.options=e}updateContacts(e){const t=Xj(this.options.localPeerDescriptor);e.filter((e=>{const r=Xj(e);return r!==t&&!this.options.neighbors.getIds().includes(r)})).forEach((e=>this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$))))}createResponse(e){return{streamPartId:this.options.streamPartId,neighborDescriptors:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),removeMe:e}}async neighborUpdate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);if(this.updateContacts(e.neighborDescriptors),this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)){const t=this.options.neighbors.size()>this.options.neighborTargetCount&&e.neighborDescriptors.length>this.options.neighborTargetCount;return t?this.options.neighbors.remove(n):this.options.neighborFinder.start(),this.createResponse(t)}return this.createResponse(!0)}}const P$=new Bv("NeighborUpdateRpcRemote");class T$ extends jz{async updateNeighbors(e,t){const r={streamPartId:e,neighborDescriptors:t,removeMe:!1};try{const e=await this.getClient().neighborUpdate(r,this.formDhtRpcOptions());return{peerDescriptors:e.neighborDescriptors,removeMe:e.removeMe}}catch(e){return P$.debug(`updateNeighbors to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{peerDescriptors:[],removeMe:!0}}}}const _$=new Bv("NeighborUpdateManager");class N${abortController;options;rpcLocal;constructor(e){this.abortController=new AbortController,this.rpcLocal=new I$(e),this.options=e,this.options.rpcCommunicator.registerRpcMethod(KH,KH,"neighborUpdate",((e,t)=>this.rpcLocal.neighborUpdate(e,t)))}async start(){await Jv((()=>this.updateNeighborInfo()),this.options.neighborUpdateInterval,!1,this.abortController.signal)}stop(){this.abortController.abort()}async updateNeighborInfo(){_$.trace("Updating neighbor info to nodes");const e=this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),t=Date.now();await Promise.allSettled(this.options.neighbors.getAll().map((async r=>{const n=await this.createRemote(r.getPeerDescriptor()).updateNeighbors(this.options.streamPartId,e),i=Xj(r.getPeerDescriptor());this.options.neighbors.get(i).setRtt(Date.now()-t),n.removeMe&&(this.options.neighbors.remove(i),this.options.neighborFinder.start([i]))})))}createRemote(e){return new T$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,f$)}}class M${options;constructor(e){this.options=e}async sendStreamMessage(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.markForInspection(n,e.messageId),void 0===this.options.plumtreeManager?this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)&&this.options.broadcast(e,n):this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)?this.options.plumtreeManager.broadcast(e,n):await this.options.plumtreeManager.pauseNeighbor(r,e.messageId.messageChainId),MV}async leaveStreamPartNotice(e,t){if(e.streamPartId===this.options.streamPartId){const r=t.incomingSourceDescriptor,n=Xj(r);this.options.onLeaveNotice(n,e.isEntryPoint)}return MV}}class x${a;b;constructor(e,t){this.a=e,this.b=t}greaterThanOrEqual(e){return this.greaterThan(e)||this.equalTo(e)}greaterThan(e){return 1===this.compareTo(e)}equalTo(e){return 0===this.compareTo(e)}compareTo(e){return this.a>e.a?1:this.a<e.a?-1:this.b>e.b?1:this.b<e.b?-1:0}toString(){return`${this.a}|${this.b}`}}class O$ extends Error{constructor(){super("pre-condition: previousNumber < number")}}class D$ extends Error{constructor(e,t,r){super(`pre-condition: gap overlap in given numbers: previousNumber=${t.toString()}, number=${r.toString()}, state=${e}`)}}class B${maxGapCount;gaps;constructor(e=1e4){this.maxGapCount=e,this.gaps=[]}markAndCheck(e,t){if(e?.greaterThanOrEqual(t))throw new O$;if(0===this.gaps.length)return this.gaps.push([t,new x$(1/0,1/0)]),!0;if(null===e)return!!t.greaterThan(this.gaps[this.gaps.length-1][0])&&(this.gaps[this.gaps.length-1][0]=t,!0);for(let r=this.gaps.length-1;r>=0;--r){const[n,i]=this.gaps[r];if(e.greaterThanOrEqual(i))return!1;if(e.greaterThanOrEqual(n)){if(t.greaterThan(i))throw new D$(this.toString(),e,t);return e.equalTo(n)?t.equalTo(i)?this.gaps.splice(r,1):this.gaps[r]=[t,i]:t.equalTo(i)?this.gaps[r]=[n,e]:this.gaps.splice(r,1,[n,e],[t,i]),this.dropLowestGapIfOverMaxGapCount(),!0}if(t.greaterThan(n))throw new D$(this.toString(),e,t)}return!1}dropLowestGapIfOverMaxGapCount(){this.gaps.length>this.maxGapCount&&this.gaps.shift()}toString(){return this.gaps.map((([e,t])=>`(${e.toString()}, ${t.toString()}]`)).join(", ")}}const L$=(e,t,r)=>{const n=`${kE(t.publisherId)}-${t.messageChainId}`,i=r?new x$(Number(r.timestamp),r.sequenceNumber):null,s=new x$(Number(t.timestamp),t.sequenceNumber);return e.has(n)||e.set(n,new B$),e.get(n).markAndCheck(i,s)},F$=new Bv("ContentDeliveryLayerNode");class U$ extends Sl{started=!1;duplicateDetectors;options;contentDeliveryRpcLocal;abortController=new AbortController;messagesPropagated=0;constructor(e){super(),this.options=e,this.duplicateDetectors=new Map,this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,rpcCommunicator:this.options.rpcCommunicator,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:(e,t)=>{if(this.abortController.signal.aborted)return;(this.options.nearbyNodeView.get(e)??this.options.randomNodeView.get(e)??this.options.neighbors.get(e)??this.options.proxyConnectionRpcLocal?.getConnection(e)?.remote)&&(this.options.discoveryLayerNode.removeContact(e),this.options.neighbors.remove(e),this.options.nearbyNodeView.remove(e),this.options.randomNodeView.remove(e),this.options.leftNodeView.remove(e),this.options.rightNodeView.remove(e),this.options.neighborFinder.start([e]),this.options.proxyConnectionRpcLocal?.removeConnection(e)),t&&this.emit("entryPointLeaveDetected")},markForInspection:(e,t)=>this.options.inspector.markMessage(e,t),plumtreeManager:this.options.plumtreeManager})}async start(){this.started=!0,this.registerDefaultServerMethods(),oE(this.options.discoveryLayerNode,"nearbyContactAdded",(()=>this.onNearbyContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"nearbyContactRemoved",(()=>this.onNearbyContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactAdded",(()=>this.onRandomContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactRemoved",(()=>this.onRandomContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactAdded",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactRemoved",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal),oE(this.options.neighbors,"nodeAdded",((e,t)=>{this.options.propagation.onNeighborJoined(e),this.options.connectionLocker.weakLockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId),this.emit("neighborConnected",e)}),this.abortController.signal),oE(this.options.neighbors,"nodeRemoved",((e,t)=>{this.options.connectionLocker.weakUnlockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId)}),this.abortController.signal),void 0!==this.options.proxyConnectionRpcLocal&&oE(this.options.proxyConnectionRpcLocal,"newConnection",(e=>this.options.propagation.onNeighborJoined(e)),this.abortController.signal),this.options.plumtreeManager&&oE(this.options.plumtreeManager,"message",(e=>this.emit("message",e)),this.abortController.signal),this.options.neighborFinder.start(),await this.options.neighborUpdateManager.start()}registerDefaultServerMethods(){this.options.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.options.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t))),this.options.rpcCommunicator.registerRpcMethod(HH,$H,"openConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.openConnection(e,t))),this.options.rpcCommunicator.registerRpcNotification(WH,"closeConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.closeConnection(e,t)))}onRingContactsUpdated(){if(F$.trace("onRingContactsUpdated"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRingContacts();this.options.leftNodeView.replaceAll(e.left.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.rightNodeView.replaceAll(e.right.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNearbyContactAdded(){if(F$.trace("New nearby contact found"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onNearbyContactRemoved(){if(F$.trace("Nearby contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e)}updateNearbyNodeView(e){this.options.nearbyNodeView.replaceAll(Array.from(e).map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))));for(const e of this.options.discoveryLayerNode.getNeighbors()){if(this.options.nearbyNodeView.size()>=this.options.nodeViewSize)break;this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))}}onRandomContactAdded(){if(this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onRandomContactRemoved(){if(F$.trace("New random contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNodeDisconnected(e){const t=Xj(e);this.options.neighbors.has(t)&&(this.options.neighbors.remove(t),this.options.neighborFinder.start([t]),this.options.temporaryConnectionRpcLocal.removeNode(t))}hasProxyConnection(e){return!!this.options.proxyConnectionRpcLocal&&this.options.proxyConnectionRpcLocal.hasConnection(e)}stop(){this.started&&(this.abortController.abort(),this.options.proxyConnectionRpcLocal?.stop(),this.options.neighbors.getAll().map((e=>{e.leaveStreamPartNotice(this.options.streamPartId,this.options.isLocalNodeEntryPoint()),this.options.connectionLocker.weakUnlockConnection(Xj(e.getPeerDescriptor()),this.options.streamPartId)})),this.options.rpcCommunicator.destroy(),this.removeAllListeners(),this.options.plumtreeManager?.stop(),this.options.nearbyNodeView.stop(),this.options.neighbors.stop(),this.options.randomNodeView.stop(),this.options.neighborFinder.stop(),this.options.neighborUpdateManager.stop(),this.options.inspector.stop())}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e);const r=void 0!==t&&!this.options.temporaryConnectionRpcLocal.hasNode(t);this.options.propagation.feedUnseenMessage(e,this.getPropagationTargets(e),r?t:null),this.messagesPropagated+=1}inspect(e){return this.options.inspector.inspect(e)}getPropagationTargets(e){let t=this.options.neighbors.getIds();return this.options.proxyConnectionRpcLocal&&(t=t.concat(this.options.proxyConnectionRpcLocal.getPropagationTargets(e))),t=t.concat(this.options.temporaryConnectionRpcLocal.getNodes().getIds()),t}getOwnNodeId(){return Xj(this.options.localPeerDescriptor)}getOutgoingHandshakeCount(){return this.options.handshaker.getOngoingHandshakes().size}getNeighbors(){return!this.started&&this.isStopped()?[]:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor()))}getInfos(){return this.options.neighbors.getAll().map((e=>({peerDescriptor:e.getPeerDescriptor(),rtt:e.getRtt()})))}getNearbyNodeView(){return this.options.nearbyNodeView}getDiagnosticInfo(){return{neighborCount:this.options.neighbors.size(),nearbyNodeViewCount:this.options.nearbyNodeView.size(),randomNodeViewCount:this.options.randomNodeView.size(),leftNodeViewCount:this.options.leftNodeView.size(),rightNodeViewCount:this.options.rightNodeView.size(),messagesPropagated:this.messagesPropagated}}isStopped(){return this.abortController.signal.aborted}}const j$=(e,t,r=!1)=>{const n=r?Array.from(e.entries()).filter((([e,t])=>void 0!==t.getPeerDescriptor().websocket)):Array.from(e.entries());return n.filter((([e])=>!t.includes(e))).map((([e,t])=>t))};class q$ extends Sl{nodes;limit;ownId;constructor(e,t){super(),this.nodes=new Map,this.limit=t,this.ownId=e}add(e){const t=Xj(e.getPeerDescriptor());if(this.ownId!==t&&this.nodes.size<this.limit){const r=this.nodes.has(t);this.nodes.set(t,e),r||this.emit("nodeAdded",t,e)}}remove(e){if(this.nodes.has(e)){const t=this.nodes.get(e);this.nodes.delete(e),this.emit("nodeRemoved",e,t)}}has(e){return this.nodes.has(e)}replaceAll(e){this.nodes.clear();e.splice(0,this.limit).forEach((e=>{this.add(e)}))}getIds(){return Array.from(this.nodes.keys())}get(e){return this.nodes.get(e)}size(e=[]){return Array.from(this.nodes.keys()).filter((t=>!e.includes(t))).length}getRandom(e){return oA(j$(this.nodes,e))}getFirst(e,t=!1){return j$(this.nodes,e,t)[0]}getFirstAndLast(e){const t=j$(this.nodes,e);return 0===t.length?[]:t.length>1?[this.getFirst(e),this.getLast(e)]:[this.getFirst(e)]}getLast(e){const t=j$(this.nodes,e);return t[t.length-1]}getAll(){return Array.from(this.nodes.values())}stop(){this.nodes.forEach((e=>this.remove(Xj(e.getPeerDescriptor())))),this.removeAllListeners()}}class z${items=new Map;dropQueue=vV.create();ttlInMs;maxSize;onItemDropped;timeProvider;constructor({ttlInMs:e,maxSize:t,onItemDropped:r=()=>{},timeProvider:n=Date.now}){if(e<0)throw new Error(`ttlInMs (${e}) cannot be < 0`);if(t<0)throw new Error(`maxSize (${t}) cannot be < 0`);this.ttlInMs=e,this.maxSize=t,this.onItemDropped=r,this.timeProvider=n}set(e,t){if(0===this.maxSize)return;if(this.items.size>this.maxSize)throw new Error("assertion error: maximum size exceeded");if(this.delete(e),this.items.size===this.maxSize){const e=this.dropQueue.shift();if(void 0===e)throw new Error("assertion error: queue empty but still have items");this.items.delete(e),this.onItemDropped(e)}const r=new kV(e);this.dropQueue.pushNode(r),this.items.set(e,{value:t,dropQueueNode:r,expiresAt:this.timeProvider()+this.ttlInMs})}delete(e){const t=this.items.get(e);void 0!==t&&(this.items.delete(e),this.dropQueue.removeNode(t.dropQueueNode),this.onItemDropped(e))}get(e){const t=this.items.get(e);if(void 0!==t){if(!(t.expiresAt<=this.timeProvider()))return t.value;this.delete(e)}}values(){const e=[...this.items.keys()],t=[];for(const r of e){const e=this.get(r);void 0!==e&&t.push(e)}return t}}class K${tasks;constructor(e,t){this.tasks=new z$({ttlInMs:e,maxSize:t})}get(){return this.tasks.values()}add(e){const t=e.message.messageId;this.tasks.set(t,e)}delete(e){this.tasks.delete(e)}}class G${sendToNeighbor;minPropagationTargets;activeTaskStore;constructor({sendToNeighbor:e,minPropagationTargets:t,maxMessages:r,ttl:n}){this.sendToNeighbor=e,this.minPropagationTargets=t,this.activeTaskStore=new K$(n,r)}feedUnseenMessage(e,t,r){const n={message:e,source:r,handledNeighbors:new Set};this.activeTaskStore.add(n);for(const e of t)this.sendAndAwaitThenMark(n,e)}onNeighborJoined(e){const t=this.activeTaskStore.get();for(const r of t)this.sendAndAwaitThenMark(r,e)}sendAndAwaitThenMark({message:e,source:t,handledNeighbors:r},n){r.has(n)||n===t||(async()=>{try{await this.sendToNeighbor(n,e)}catch{return}r.add(n),r.size>=this.minPropagationTargets&&this.activeTaskStore.delete(e.messageId)})()}}const V$=new Bv("ProxyConnectionRpcLocal");class H$ extends Sl{options;connections=new Map;constructor(e){super(),this.options=e,this.options.rpcCommunicator.registerRpcMethod(GH,VH,"requestConnection",((e,t)=>this.requestConnection(e,t)))}getConnection(e){return this.connections.get(e)}hasConnection(e){return this.connections.has(e)}removeConnection(e){this.connections.delete(e)}stop(){this.connections.forEach((e=>e.remote.leaveStreamPartNotice(this.options.streamPartId,!1))),this.connections.clear(),this.removeAllListeners()}getPropagationTargets(e){if("groupKeyRequest"!==e.body.oneofKind)return this.getSubscribers();try{const t=e.body.groupKeyRequest.recipientId;return this.getNodeIdsForUserId(kE(t))}catch(e){return V$.trace("Could not parse GroupKeyRequest",{err:e}),[]}}getNodeIdsForUserId(e){return Array.from(this.connections.keys()).filter((t=>this.connections.get(t).userId===e))}getSubscribers(){return Array.from(this.connections.keys()).filter((t=>{const r=this.connections.get(t).direction;return void 0===r||r===e.ProxyDirection.SUBSCRIBE}))}async requestConnection(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);this.connections.set(n,{direction:e.direction,userId:kE(e.userId),remote:new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$)});return V$.trace(`Accepted connection request from ${n} to ${this.options.streamPartId}`),this.emit("newConnection",n),{accepted:!0}}}const $$=new Bv("TemporaryConnectionRpcRemote");class W$ extends jz{async openConnection(){try{return(await this.getClient().openConnection({},this.formDhtRpcOptions())).accepted}catch(e){return $$.debug(`temporaryConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),!1}}async closeConnection(){try{await this.getClient().closeConnection({},this.formDhtRpcOptions({connect:!1,notification:!0}))}catch(e){$$.trace(`closeConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e})}}}class J$ extends Sl{inspectionMessages=new Map;inspectedNode;constructor(e){super(),this.inspectedNode=e.inspectedNode}markMessage(e,t){const r=(e=>`${kE(e.publisherId)}:${e.messageChainId}:${e.timestamp}:${e.sequenceNumber}`)(t);this.inspectionMessages.has(r)?(this.inspectionMessages.has(r)&&!1===this.inspectionMessages.get(r)&&e===this.inspectedNode||this.inspectionMessages.has(r)&&!0===this.inspectionMessages.get(r))&&this.emit("done"):this.inspectionMessages.set(r,e===this.inspectedNode)}getInspectedMessageCount(){return this.inspectionMessages.size}onlyMarkedByInspectedNode(){return Array.from(this.inspectionMessages.values()).every((e=>!0===e))}stop(){this.emit("done")}}const Q$=new Bv("Inspector");class Z${sessions=new Map;streamPartId;localPeerDescriptor;rpcCommunicator;connectionLocker;inspectionTimeout;openInspectConnection;closeInspectConnection;constructor(e){this.streamPartId=e.streamPartId,this.localPeerDescriptor=e.localPeerDescriptor,this.rpcCommunicator=e.rpcCommunicator,this.connectionLocker=e.connectionLocker,this.inspectionTimeout=e.inspectionTimeout??6e4,this.openInspectConnection=e.openInspectConnection??this.defaultOpenInspectConnection,this.closeInspectConnection=e.closeInspectConnection??this.defaultCloseInspectConnection}async defaultOpenInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.openConnection(),this.connectionLocker.weakLockConnection(Xj(e),t)}async defaultCloseInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.closeConnection(),this.connectionLocker.weakUnlockConnection(Xj(e),t)}async inspect(e){const t=Xj(e),r=new J$({inspectedNode:t}),n=`inspector-${this.streamPartId}`;this.sessions.set(t,r),await this.openInspectConnection(e,n);let i=!1;try{await eE(r,"done",this.inspectionTimeout),i=!0}catch{Q$.trace("Inspect session timed out, removing")}finally{await this.closeInspectConnection(e,n),this.sessions.delete(t)}return i||r.getInspectedMessageCount()<1||r.onlyMarkedByInspectedNode()}markMessage(e,t){this.sessions.forEach((r=>r.markMessage(e,t)))}isInspected(e){return this.sessions.has(e)}stop(){this.sessions.forEach((e=>{e.stop()})),this.sessions.clear()}}class Y${options;temporaryNodes;lockId;constructor(e){this.options=e,this.temporaryNodes=new q$(Xj(e.localPeerDescriptor),10),this.lockId="system/content-delivery/temporary-connection/"+e.streamPartId}getNodes(){return this.temporaryNodes}hasNode(e){return this.temporaryNodes.has(e)}removeNode(e){this.temporaryNodes.remove(e),this.options.connectionLocker.weakUnlockConnection(e,this.lockId)}async openConnection(e,t){const r=t.incomingSourceDescriptor,n=new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$);return this.temporaryNodes.add(n),this.options.connectionLocker.weakLockConnection(Xj(r),this.lockId),{accepted:!0}}async closeConnection(e,t){const r=Xj(t.incomingSourceDescriptor);return this.removeNode(r),{}}}const X$=e=>`stream-part-delivery-${e}`;class eW{neighbors;pausedNodes;onMetadataCb;sendBuffer;constructor(e,t,r,n){this.neighbors=e,this.pausedNodes=t,this.onMetadataCb=r,this.sendBuffer=n}async sendMetadata(e,t){const r=t.incomingSourceDescriptor;return await this.onMetadataCb(e,r),MV}async pauseNeighbor(e,t){const r=Xj(t.incomingSourceDescriptor);if(this.neighbors.has(r)){return{accepted:this.pausedNodes.add(r,e.messageChainId)}}return{accepted:!1}}async resumeNeighbor(e,t){const r=t.incomingSourceDescriptor;return this.neighbors.has(Xj(r))&&(this.pausedNodes.delete(Xj(r),e.messageChainId),await this.sendBuffer(e.fromTimestamp,e.messageChainId,r)),MV}}class tW extends jz{async sendMetadata(e){const t=this.formDhtRpcOptions({notification:!0});await this.getClient().sendMetadata(e,t)}async pauseNeighbor(e){const t=this.formDhtRpcOptions();return(await this.getClient().pauseNeighbor({messageChainId:e},t)).accepted}async resumeNeighbor(e,t){const r=this.formDhtRpcOptions({notification:!0});await this.getClient().resumeNeighbor({fromTimestamp:e,messageChainId:t},r)}}class rW{pausedNeighbors;limit;constructor(e){this.pausedNeighbors=new Map,this.limit=e}add(e,t){return this.pausedNeighbors.has(t)||this.pausedNeighbors.set(t,new Set),!(this.pausedNeighbors.get(t).size>=this.limit)&&(this.pausedNeighbors.get(t).add(e),!0)}delete(e,t){this.pausedNeighbors.get(t)?.delete(e),0===this.pausedNeighbors.get(t)?.size&&this.pausedNeighbors.delete(t)}deleteAll(e){this.pausedNeighbors.forEach(((t,r)=>{t.delete(e),0===t.size&&this.pausedNeighbors.delete(r)}))}isPaused(e,t){return!!this.pausedNeighbors.has(t)&&this.pausedNeighbors.get(t).has(e)}forEach(e){this.pausedNeighbors.forEach(((t,r)=>{e(t,r)}))}size(e){return this.pausedNeighbors.get(e)?.size??0}}const nW=new Bv("PlumtreeManager");class iW extends Sl{neighbors;localPeerDescriptor;localPausedNeighbors;remotePausedNeighbors;rpcLocal;latestMessages=new Map;rpcCommunicator;maxPausedNeighbors;recoveryState=new Map;recoveryCooldownUntil=new Map;recoveryTimeout;recoveryCooldown;abortController=new AbortController;constructor(e){super(),this.neighbors=e.neighbors,this.maxPausedNeighbors=e.maxPausedNeighbors??3,this.localPeerDescriptor=e.localPeerDescriptor,this.localPausedNeighbors=new rW(e.maxPausedNeighbors??3),this.remotePausedNeighbors=new rW(e.maxPausedNeighbors??3),this.recoveryTimeout=e.recoveryTimeout??500,this.recoveryCooldown=e.recoveryCooldown??2500,this.rpcLocal=new eW(this.neighbors,this.localPausedNeighbors,((e,t)=>this.onMetadata(e,t)),((e,t,r)=>this.sendBuffer(e,t,r))),this.neighbors.on("nodeRemoved",this.onNeighborRemoved),this.rpcCommunicator=e.rpcCommunicator,this.rpcCommunicator.registerRpcNotification(NH,"sendMetadata",((e,t)=>this.rpcLocal.sendMetadata(e,t))),this.rpcCommunicator.registerRpcMethod(e$,t$,"pauseNeighbor",((e,t)=>this.rpcLocal.pauseNeighbor(e,t))),this.rpcCommunicator.registerRpcNotification(r$,"resumeNeighbor",((e,t)=>this.rpcLocal.resumeNeighbor(e,t))),((e,t,r)=>{if(r.aborted)return;r.addEventListener("abort",(()=>{clearInterval(n)}),{once:!0});const n=setInterval((()=>{e()}),t)})((()=>{const e=performance.now();for(const[t,r]of this.recoveryState)e-r.metadataAheadSince>=this.recoveryTimeout&&!r.resumeInProgress&&this.attemptRecovery(t,r,this.getLatestMessageTimestamp(t))}),e.recoveryCheckInterval??200,this.abortController.signal)}async pauseNeighbor(e,t){if(this.neighbors.has(Xj(e))&&!this.remotePausedNeighbors.isPaused(Xj(e),t)&&this.remotePausedNeighbors.size(t)<this.maxPausedNeighbors){nW.debug(`Pausing neighbor ${Xj(e)}`),this.remotePausedNeighbors.add(Xj(e),t);try{const r=this.createRemote(e);await r.pauseNeighbor(t)||this.remotePausedNeighbors.delete(Xj(e),t)}catch(r){this.remotePausedNeighbors.delete(Xj(e),t)}}}async resumeNeighbor(e,t,r){if(this.remotePausedNeighbors.isPaused(Xj(e),t)){nW.debug(`Resuming neighbor ${Xj(e)}`),this.remotePausedNeighbors.delete(Xj(e),t);const n=this.createRemote(e);await n.resumeNeighbor(r,t)}}onNeighborRemoved=e=>{this.localPausedNeighbors.deleteAll(e),this.remotePausedNeighbors.deleteAll(e);for(const[t,r]of this.recoveryState)r.candidates=r.candidates.filter((t=>Xj(t)!==e)),null!==r.lastAttemptedNode&&Xj(r.lastAttemptedNode)===e&&(r.lastAttemptedNode=null);this.neighbors.size()>0&&this.remotePausedNeighbors.forEach(((e,t)=>{if(e.size>=this.neighbors.size()){nW.debug("All neighbors are paused, resuming first neighbor");const e=this.neighbors.getFirst([]).getPeerDescriptor();setImmediate((()=>this.resumeNeighbor(e,t,this.getLatestMessageTimestamp(t))))}}))};getLatestMessageTimestamp(e){return this.latestMessages.has(e)&&0!==this.latestMessages.get(e).length?this.latestMessages.get(e)[this.latestMessages.get(e).length-1].messageId.timestamp:0}async sendBuffer(e,t,r){const n=new b$(this.localPeerDescriptor,r,this.rpcCommunicator,l$),i=this.latestMessages.get(t)?.filter((t=>t.messageId.timestamp>e))??[];for(const e of i)await n.sendStreamMessage(e)}async onMetadata(e,t){const r=this.getLatestMessageTimestamp(e.messageChainId);if(r>=e.timestamp)return;const n=e.messageChainId,i=this.recoveryCooldownUntil.get(n);if(void 0!==i&&performance.now()<i)return;let s=this.recoveryState.get(n);s||(s={timestampsAhead:new Set,metadataAheadSince:performance.now(),candidates:[],lastAttemptedNode:null,resumeInProgress:!1},this.recoveryState.set(n,s)),s.timestampsAhead.add(e.timestamp);const o=Xj(t);null!==s.lastAttemptedNode&&Xj(s.lastAttemptedNode)===o||s.candidates.some((e=>Xj(e)===o))||s.candidates.push(t),s.timestampsAhead.size>1&&!s.resumeInProgress&&await this.attemptRecovery(n,s,r)}async attemptRecovery(e,t,r){const n=t.candidates.shift();if(n){t.resumeInProgress=!0,t.lastAttemptedNode=n,t.candidates=[],t.timestampsAhead.clear(),t.metadataAheadSince=performance.now();try{const t=this.createRemote(n);await t.resumeNeighbor(r,e)}catch(e){nW.debug("Recovery resume failed, will retry with next candidate")}finally{t.resumeInProgress=!1}}else t.metadataAheadSince=performance.now()}createRemote(e){return new tW(this.localPeerDescriptor,e,this.rpcCommunicator,m$)}broadcast(e,t){const r=e.messageId.messageChainId;this.latestMessages.has(r)||this.latestMessages.set(r,[]),this.latestMessages.get(r).length<20||this.latestMessages.get(r).shift(),this.latestMessages.get(r).push(e);const n=this.recoveryState.get(r);n&&(n.lastAttemptedNode&&this.remotePausedNeighbors.delete(Xj(n.lastAttemptedNode),r),this.recoveryState.delete(r),this.recoveryCooldownUntil.set(r,performance.now()+this.recoveryCooldown)),this.emit("message",e);const i=this.neighbors.getAll().filter((e=>Xj(e.getPeerDescriptor())!==t));for(const t of i)if(this.localPausedNeighbors.isPaused(Xj(t.getPeerDescriptor()),e.messageId.messageChainId)){const r=this.createRemote(t.getPeerDescriptor());setImmediate((()=>r.sendMetadata(e.messageId)))}else setImmediate((()=>t.sendStreamMessage(e)))}isNeighborPaused(e,t){return this.localPausedNeighbors.isPaused(Xj(e),t)||this.remotePausedNeighbors.isPaused(Xj(e),t)}getLocalPausedNeighbors(){return this.localPausedNeighbors}getRemotePausedNeighbors(){return this.remotePausedNeighbors}stop(){this.abortController.abort(),this.neighbors.off("nodeRemoved",this.onNeighborRemoved)}}const sW=e=>new U$((e=>{const t=Xj(e.localPeerDescriptor),r=e.rpcCommunicator??new lK(X$(e.streamPartId),e.transport),n=e.neighborTargetCount??4,i=e.maxContactCount??20,s=e.acceptProxyConnections??!1,o=e.neighborUpdateInterval??1e4,a=e.minPropagationTargets??2,c=e.maxPropagationBufferSize??150,u=e.neighbors??new q$(t,i),l=e.leftNodeView??new q$(t,i),h=e.rightNodeView??new q$(t,i),d=e.nearbyNodeView??new q$(t,i),f=e.randomNodeView??new q$(t,i),p=new Set,g=new Y$({rpcCommunicator:r,localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker}),m=s?new H$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r}):void 0,y=e.plumtreeOptimization?new iW({neighbors:u,localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,maxPausedNeighbors:e.plumtreeMaxPausedNeighbors}):void 0,b=e.propagation??new G$({minPropagationTargets:a,maxMessages:c,ttl:1e4,sendToNeighbor:async(t,r)=>{const n=u.get(t)??g.getNodes().get(t),i=m?.getConnection(t);if(n)await n.sendStreamMessage(r,e.bufferWhileConnecting);else{if(!i)throw new Error("Propagation target not found");await i.remote.sendStreamMessage(r)}}}),w=e.handshaker??new k$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,maxNeighborCount:n,rpcRequestTimeout:e.rpcRequestTimeout,ongoingHandshakes:p}),v=e.neighborFinder??new C$({neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,doFindNeighbors:e=>w.attemptHandshakesOnContacts(e),minCount:n}),E=e.neighborUpdateManager??new N$({neighbors:u,nearbyNodeView:d,localPeerDescriptor:e.localPeerDescriptor,neighborFinder:v,streamPartId:e.streamPartId,rpcCommunicator:r,neighborUpdateInterval:o,neighborTargetCount:n,ongoingHandshakes:p}),A=e.inspector??new Z$({localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker});return{...e,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,rpcCommunicator:r,handshaker:w,neighborFinder:v,neighborUpdateManager:E,propagation:b,neighborTargetCount:n,nodeViewSize:i,proxyConnectionRpcLocal:m,inspector:A,temporaryConnectionRpcLocal:g,plumtreeManager:y}})(e)),oW=new Bv("ProxyConnectionRpcRemote");class aW extends jz{async requestConnection(e,t){const r={direction:t,userId:RE(e)},n=this.formDhtRpcOptions({timeout:Fz});try{return(await this.getClient().requestConnection(r,n)).accepted}catch(e){return oW.debug("ProxyConnectionRequest failed with error",{err:e}),!1}}}const cW=new Bv("ProxyClient"),uW="system/proxy-client";class lW extends Sl{rpcCommunicator;contentDeliveryRpcLocal;options;duplicateDetectors=new Map;definition;connections=new Map;propagation;neighbors;abortController;constructor(e){super(),this.options=e,this.rpcCommunicator=new lK(X$(e.streamPartId),e.transport),this.neighbors=new q$(Xj(this.options.localPeerDescriptor),1e3),this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:e=>{const t=this.neighbors.get(e);t&&setImmediate((()=>this.onNodeDisconnected(t.getPeerDescriptor())))},rpcCommunicator:this.rpcCommunicator,markForInspection:()=>{}}),this.propagation=new G$({minPropagationTargets:e.minPropagationTargets,maxMessages:e.maxPropagationBufferSize,ttl:e.propagationBufferTtl,sendToNeighbor:async(e,t)=>{const r=this.neighbors.get(e);if(!r)throw new Error("Propagation target not found");await r.sendStreamMessage(t)}}),this.abortController=new AbortController}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t)))}async setProxies(e,t,r,n){if(cW.trace("Setting proxies",{streamPartId:this.options.streamPartId,peerDescriptors:e,direction:r,userId:t,connectionCount:n}),void 0!==n&&n>e.length)throw new Error("Cannot set connectionCount above the size of the configured array of nodes");const i=new Map;e.forEach((e=>{i.set(Xj(e),e)})),this.definition={nodes:i,userId:t,direction:r,connectionCount:n??e.length},await this.updateConnections()}async updateConnections(){await Promise.all(this.getInvalidConnections().map((async e=>{await this.closeConnection(e)})));const e=this.definition.connectionCount-this.connections.size;e>0?await this.openRandomConnections(e):e<0&&await this.closeRandomConnections(-e)}getInvalidConnections(){return Array.from(this.connections.keys()).filter((e=>!this.definition.nodes.has(e)||this.definition.direction!==this.connections.get(e).direction))}async openRandomConnections(e){const t=wV(Array.from(this.definition.nodes.keys()).filter((e=>!this.connections.has(e))),e);await Promise.all(t.map((e=>this.attemptConnection(e,this.definition.userId,this.definition.direction))))}async attemptConnection(e,t,r){const n=this.definition.nodes.get(e),i=new aW(this.options.localPeerDescriptor,n,this.rpcCommunicator,h$);if(await i.requestConnection(t,r)){this.options.connectionLocker.lockConnection(n,uW),this.connections.set(e,{peerDescriptor:n,direction:r});const t=new b$(this.options.localPeerDescriptor,n,this.rpcCommunicator,l$);this.neighbors.add(t),this.propagation.onNeighborJoined(e),cW.info("Open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}else cW.warn("Unable to open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}async closeRandomConnections(e){const t=wV(Array.from(this.connections.keys()),e);await Promise.allSettled(t.map((e=>this.closeConnection(e))))}async closeConnection(e){if(this.connections.has(e)){cW.info("Close proxy connection",{nodeId:e});const t=this.neighbors.get(e);t?.leaveStreamPartNotice(this.options.streamPartId,!1),this.removeConnection(this.connections.get(e).peerDescriptor)}}removeConnection(e){const t=Xj(e);this.connections.delete(t),this.neighbors.remove(t),this.options.connectionLocker.unlockConnection(e,uW)}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e),this.propagation.feedUnseenMessage(e,this.neighbors.getIds(),t??null)}hasConnection(e,t){return this.connections.has(e)&&this.connections.get(e).direction===t}getDirection(){return this.definition.direction}async onNodeDisconnected(e){const t=Xj(e);this.connections.has(t)&&(this.options.connectionLocker.unlockConnection(e,uW),this.removeConnection(e),await(async(e,t,r,n=1e4)=>{for(;;){try{return await e()}catch{cW.warn(`Failed ${t} (retrying after delay)`,{delayInMs:n})}await Qv(n,r)}})((()=>this.updateConnections()),"updating proxy connections",this.abortController.signal))}async start(){this.registerDefaultServerMethods(),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal)}getDiagnosticInfo(){return{neighbors:this.neighbors.getAll().map((e=>e.getPeerDescriptor()))}}stop(){this.neighbors.getAll().forEach((e=>{this.options.connectionLocker.unlockConnection(e.getPeerDescriptor(),uW),e.leaveStreamPartNotice(this.options.streamPartId,!1)})),this.neighbors.stop(),this.rpcCommunicator.destroy(),this.connections.clear(),this.abortController.abort()}}const hW=new Bv("ContentDeliveryManager"),dW=e=>{return Zj((t=e,Buffer.from(Zr(pw(t)))));var t};class fW extends Sl{transport;connectionLocker;controlLayerNode;metricsContext;metrics;options;streamParts;knownStreamPartEntryPoints=new Map;started=!1;destroyed=!1;constructor(e){super(),this.options=e,this.streamParts=new Map,this.metricsContext=e.metricsContext??new $v,this.metrics={broadcastMessagesPerSecond:new Hv,broadcastBytesPerSecond:new Hv},this.metricsContext.addMetrics("node",this.metrics)}async start(e,t,r){this.started||this.destroyed||(this.started=!0,this.controlLayerNode=e,this.transport=t,this.connectionLocker=r)}async destroy(){this.started&&!this.destroyed&&(hW.trace("Destroying ContentDeliveryManager"),this.destroyed=!0,await Promise.all(Array.from(this.streamParts.values()).map((e=>e.stop()))),this.streamParts.clear(),this.removeAllListeners(),this.controlLayerNode=void 0,this.transport=void 0,this.connectionLocker=void 0)}broadcast(e,t){const r=EE(e.messageId.streamId,e.messageId.streamPartition);hW.debug(`Broadcasting to stream part ${r}`),this.joinStreamPart(r,t),this.streamParts.get(r).broadcast(e),"contentMessage"===e.body.oneofKind&&(this.metrics.broadcastMessagesPerSecond.record(1),this.metrics.broadcastBytesPerSecond.record(e.body.contentMessage.content.length))}async leaveStreamPart(e){const t=this.streamParts.get(e);t&&(await t.stop(),this.streamParts.delete(e))}joinStreamPart(e,t){let r=this.streamParts.get(e);if(void 0!==r)return;hW.debug(`Join stream part ${e}`);const n=this.createDiscoveryLayerNode(e,this.knownStreamPartEntryPoints.get(e)??[]),i=new PV({key:dW(e),localPeerDescriptor:this.getPeerDescriptor(),fetchDataFromDht:e=>this.controlLayerNode.fetchDataFromDht(e),storeDataToDht:(e,t)=>this.controlLayerNode.storeDataToDht(e,t),deleteDataFromDht:async(e,t)=>this.controlLayerNode.deleteDataFromDht(e,t)}),s=new _V({discoveryLayerNode:n,discoverEntryPoints:async()=>i.fetchNodes()}),o=this.createContentDeliveryLayerNode(e,n,(()=>i.isLocalNodeStored()),t),a=new NV(n,i);r={proxied:!1,discoveryLayerNode:n,node:o,networkSplitAvoidance:s,broadcast:e=>o.broadcast(e),stop:async()=>{a.destroy(),s.destroy(),await i.destroy(),o.stop(),await n.stop()},getDiagnosticInfo:()=>o.getDiagnosticInfo()},this.streamParts.set(e,r),o.on("message",(e=>{this.emit("newMessage",e)}));const c=async()=>{if(this.destroyed||i.isLocalNodeStored()||this.knownStreamPartEntryPoints.has(e))return;(await i.fetchNodes()).length<8&&await i.storeAndKeepLocalNode()};n.on("manualRejoinRequired",(async()=>{a.isRunning()||s.isRunning()||(hW.debug("Manual rejoin required for stream part",{streamPartId:e}),await a.reconnect())})),o.on("entryPointLeaveDetected",(()=>c())),setImmediate((async()=>{try{await this.startLayersAndJoinDht(e,i)}catch(t){hW.warn(`Failed to join to stream part ${e}`,{err:t})}}))}async startLayersAndJoinDht(e,t){hW.debug(`Start layers and join DHT for stream part ${e}`);const r=this.streamParts.get(e);if(void 0===r||r.proxied)return;this.transport.isPrivateClientMode()&&await this.transport.disablePrivateClientMode(),await r.discoveryLayerNode.start(),await r.node.start();const n=this.knownStreamPartEntryPoints.get(e);if(void 0!==n)await Promise.all([r.discoveryLayerNode.joinDht(n),r.discoveryLayerNode.joinRing()]);else{const e=await t.fetchNodes();await Promise.all([r.discoveryLayerNode.joinDht(wV(e,4)),r.discoveryLayerNode.joinRing()]),e.length<8&&(await t.storeAndKeepLocalNode(),r.discoveryLayerNode.getNeighborCount()<4&&setImmediate((()=>r.networkSplitAvoidance.avoidNetworkSplit())))}}createDiscoveryLayerNode(e,t){return new oV({transport:this.controlLayerNode,connectionsView:this.controlLayerNode.getConnectionsView(),serviceId:"layer1::"+e,peerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),entryPoints:t,numberOfNodesPerKBucket:4,rpcRequestTimeout:Fz,dhtJoinTimeout:2e4,periodicallyPingNeighbors:!0,periodicallyPingRingContacts:!0,neighborPingLimit:16})}createContentDeliveryLayerNode(e,t,r,n){return sW({streamPartId:e,transport:this.transport,discoveryLayerNode:t,connectionLocker:this.connectionLocker,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),minPropagationTargets:this.options.streamPartitionMinPropagationTargets,neighborTargetCount:this.options.streamPartitionNeighborTargetCount,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize,acceptProxyConnections:this.options.acceptProxyConnections,rpcRequestTimeout:this.options.rpcRequestTimeout,neighborUpdateInterval:this.options.neighborUpdateInterval,isLocalNodeEntryPoint:r,bufferWhileConnecting:this.options.bufferWhileConnecting,plumtreeOptimization:n?.plumtreeOptimization?.enabled,plumtreeMaxPausedNeighbors:!0===n?.plumtreeOptimization?.enabled?n?.plumtreeOptimization?.maxPausedNeighbors:void 0})}async setProxies(e,t,r,n,i){if(this.options.acceptProxyConnections)throw new Error("cannot set proxies when acceptProxyConnections=true");if(t.length>0&&(void 0===i||i>0)){let s;this.isProxiedStreamPart(e)?s=this.streamParts.get(e).client:(s=this.createProxyClient(e),this.streamParts.set(e,{proxied:!0,client:s,broadcast:e=>s.broadcast(e),stop:async()=>s.stop(),getDiagnosticInfo:()=>s.getDiagnosticInfo()}),s.on("message",(e=>{this.emit("newMessage",e)})),Array.from(this.streamParts.values()).every((e=>e.proxied))&&await this.transport.enablePrivateClientMode(),await s.start()),await s.setProxies(t,r,n,i)}else await(this.streamParts.get(e)?.stop()),this.streamParts.delete(e)}createProxyClient(e){return new lW({transport:this.transport,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),streamPartId:e,connectionLocker:this.connectionLocker,minPropagationTargets:this.options.streamPartitionMinPropagationTargets??2,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize??150,propagationBufferTtl:1e4})}async inspect(e,t){const r=this.streamParts.get(t);return void 0!==r&&!r.proxied&&r.node.inspect(e)}getNodeInfo(){const e=Array.from(this.streamParts.entries()).filter((([e,t])=>!1===t.proxied));return e.map((([e])=>{const t=this.streamParts.get(e);return{id:e,controlLayerNeighbors:t.discoveryLayerNode.getNeighbors(),deprecatedContentDeliveryLayerNeighbors:[],contentDeliveryLayerNeighbors:t.node.getInfos()}}))}setStreamPartEntryPoints(e,t){this.knownStreamPartEntryPoints.set(e,t)}isProxiedStreamPart(e,t){const r=this.streamParts.get(e);return void 0!==r&&r.proxied&&(void 0===t||r.client.getDirection()===t)}getStreamPartDelivery(e){return this.streamParts.get(e)}hasStreamPart(e){return this.streamParts.has(e)}getPeerDescriptor(){return this.controlLayerNode.getLocalPeerDescriptor()}getNodeId(){return Xj(this.controlLayerNode.getLocalPeerDescriptor())}getNeighbors(e){const t=this.streamParts.get(e);return!1===t?.proxied?t.node.getNeighbors().map((e=>Xj(e))):[]}getStreamParts(){return Array.from(this.streamParts.keys()).map((e=>AE.parse(e)))}getDiagnosticInfo(){return{streamParts:this.getStreamParts().map((e=>({id:e,info:this.getStreamPartDelivery(e).getDiagnosticInfo()})))}}}class pW extends jz{async getInfo(){return this.getClient().getInfo({},this.formDhtRpcOptions())}}class gW{ownPeerDescriptor;rpcCommunicator;constructor(e,t){this.ownPeerDescriptor=e,this.rpcCommunicator=t}async getInfo(e){return new pW(this.ownPeerDescriptor,e,this.rpcCommunicator,g$).getInfo()}}class mW{stack;rpcCommunicator;constructor(e,t){this.stack=e,this.rpcCommunicator=t,this.registerDefaultServerMethods()}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcMethod(YH,XH,"getInfo",(()=>this.getInfo()))}async getInfo(){return this.stack.createNodeInfo()}}const yW=new Bv("NetworkStack"),bW=[],wW=async()=>{const e=[...bW];await Promise.all(e.map((e=>e.stop())))};if("object"==typeof process&&"function"==typeof process?.on){["exit","SIGINT","SIGUSR1","SIGUSR2","uncaughtException","unhandledRejection","SIGTERM"].forEach((e=>{process.on(e,(async t=>{const r="uncaughtException"===e||"unhandledRejection"===e;r&&yW.error(`exit event: ${e}`,t),await wW(),process.exit(r?1:0)}))}))}"object"==typeof window&&window.addEventListener("unload",(async()=>{await wW()}));class vW{controlLayerNode;contentDeliveryManager;stopped=!1;metricsContext;options;nodeInfoRpcLocal;nodeInfoClient;constructor(e){this.options=e,this.metricsContext=e.metricsContext??new $v,this.controlLayerNode=new oV({...e.layer0,metricsContext:this.metricsContext,allowIncomingPrivateConnections:e.networkNode?.acceptProxyConnections}),this.contentDeliveryManager=new fW({...e.networkNode,metricsContext:this.metricsContext}),bW.push(this)}async joinStreamPart(e,t,r){if(this.getContentDeliveryManager().isProxiedStreamPart(e))throw new Error(`Cannot join to ${e} as proxy connections have been set`);await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().joinStreamPart(e,r),void 0!==t&&await iE((()=>this.getContentDeliveryManager().getNeighbors(e).length>=t.minCount),t.timeout)}async broadcast(t,r){const n=EE(t.messageId.streamId,t.messageId.streamPartition);if(this.getContentDeliveryManager().isProxiedStreamPart(n,e.ProxyDirection.SUBSCRIBE)&&"contentMessage"===t.body.oneofKind)throw new Error(`Cannot broadcast to ${n} as proxy subscribe connections have been set`);this.contentDeliveryManager.isProxiedStreamPart(n)||await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().broadcast(t,r)}async start(e=!0){yW.info("Starting a Streamr Network Node"),await this.controlLayerNode.start(),yW.info(`Node id is ${Xj(this.controlLayerNode.getLocalPeerDescriptor())}`);const t=this.controlLayerNode.getTransport();if(this.options.layer0?.entryPoints?.some((e=>eq(e,this.controlLayerNode.getLocalPeerDescriptor())))?await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints)):e&&await this.ensureConnectedToControlLayer(),await(this.contentDeliveryManager?.start(this.controlLayerNode,t,t)),this.contentDeliveryManager){const e=new lK("system/node-info-rpc",this.getConnectionManager());this.nodeInfoRpcLocal=new mW(this,e),this.nodeInfoClient=new gW(this.controlLayerNode.getLocalPeerDescriptor(),e)}}async ensureConnectedToControlLayer(){this.controlLayerNode.hasJoined()||(setImmediate((async()=>{void 0!==this.options.layer0?.entryPoints&&await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints))})),await this.controlLayerNode.waitForNetworkConnectivity())}getContentDeliveryManager(){return this.contentDeliveryManager}getControlLayerNode(){return this.controlLayerNode}getMetricsContext(){return this.metricsContext}async fetchNodeInfo(e){return eq(e,this.getControlLayerNode().getLocalPeerDescriptor())?this.createNodeInfo():this.nodeInfoClient.getInfo(e)}createNodeInfo(){return{peerDescriptor:this.getControlLayerNode().getLocalPeerDescriptor(),controlLayer:{connections:this.getControlLayerNode().getConnectionsView().getConnections(),neighbors:this.getControlLayerNode().getNeighbors()},streamPartitions:this.getContentDeliveryManager().getNodeInfo(),applicationVersion:"103.6.0-rc.0"}}getOptions(){return this.options}getConnectionManager(){return this.controlLayerNode.getTransport()}async stop(){this.stopped||(this.stopped=!0,Ej(bW,this),await this.contentDeliveryManager.destroy(),await this.controlLayerNode.stop(),this.contentDeliveryManager=void 0,this.controlLayerNode=void 0)}}class EW{stack;stopped=!1;externalNetworkRpc;constructor(e){this.stack=e}async start(e){await this.stack.start(e),this.externalNetworkRpc=new RV(this.stack.getControlLayerNode().getTransport())}async inspect(e,t){return this.stack.getContentDeliveryManager().inspect(e,t)}async broadcast(e,t){await this.stack.broadcast(e,t)}async join(e,t,r){await this.stack.joinStreamPart(e,t,r)}async setProxies(e,t,r,n,i){await this.stack.getContentDeliveryManager().setProxies(e,t,r,n,i)}isProxiedStreamPart(e){return this.stack.getContentDeliveryManager().isProxiedStreamPart(e)}addMessageListener(e){this.stack.getContentDeliveryManager().on("newMessage",e)}setStreamPartEntryPoints(e,t){this.stack.getContentDeliveryManager().setStreamPartEntryPoints(e,t)}removeMessageListener(e){this.stack.getContentDeliveryManager().off("newMessage",e)}async leave(e){this.stopped||await this.stack.getContentDeliveryManager().leaveStreamPart(e)}getNeighbors(e){return this.stack.getContentDeliveryManager().getNeighbors(e)}hasStreamPart(e){return this.stack.getContentDeliveryManager().hasStreamPart(e)}async stop(){this.stopped=!0,this.externalNetworkRpc.destroy(),await this.stack.stop()}getPeerDescriptor(){return this.stack.getControlLayerNode().getLocalPeerDescriptor()}getMetricsContext(){return this.stack.getMetricsContext()}getNodeId(){return this.stack.getContentDeliveryManager().getNodeId()}getOptions(){return this.stack.getOptions()}getStreamParts(){return this.stack.getContentDeliveryManager().getStreamParts()}async fetchNodeInfo(e){return this.stack.fetchNodeInfo(e)}getDiagnosticInfo(){return{controlLayer:this.stack.getControlLayerNode().getDiagnosticInfo(),contentLayer:this.stack.getContentDeliveryManager().getDiagnosticInfo()}}registerExternalNetworkRpcMethod(e,t,r,n){this.externalNetworkRpc.registerRpcMethod(e,t,r,n)}createExternalRpcClient(e){return this.externalNetworkRpc.createRpcClient(e)}}class AW extends Error{code;constructor(e,t){super(e),this.code=t}}function SW(e,t){if(void 0===t)throw new AW(`Expected ${e} to not be undefined.`)}function kW(e,t,r=!1){if(!r||void 0!==t){if(SW(e,t),!Number.isInteger(t))throw new AW(`Expected ${e} to be an integer but was a ${typeof t} (${t}).`);if(t<0)throw new AW(`Expected ${e} to not be negative (${t}).`)}}class RW{timestamp;sequenceNumber;constructor(e,t){kW("timestamp",e),kW("sequenceNumber",t,!0),this.timestamp=e,this.sequenceNumber=t}compareTo(e){return this.timestamp<e.timestamp?-1:this.timestamp>e.timestamp?1:this.sequenceNumber<e.sequenceNumber?-1:this.sequenceNumber>e.sequenceNumber?1:0}}class CW{streamId;streamPartition;timestamp;sequenceNumber;publisherId;msgChainId;constructor(e,t,r,n,i,s){kW("streamPartition",t),kW("timestamp",r),kW("sequenceNumber",n),this.streamId=e,this.streamPartition=t,this.timestamp=r,this.sequenceNumber=n,this.publisherId=i,this.msgChainId=s}getStreamPartID(){return EE(this.streamId,this.streamPartition)}toMessageRef(){return new RW(this.timestamp,this.sequenceNumber)}}var IW;e.StreamMessageType=void 0,(IW=e.StreamMessageType||(e.StreamMessageType={}))[IW.MESSAGE=0]="MESSAGE",IW[IW.GROUP_KEY_REQUEST=1]="GROUP_KEY_REQUEST",IW[IW.GROUP_KEY_RESPONSE=2]="GROUP_KEY_RESPONSE";class PW{messageId;prevMsgRef;messageType;content;contentType;signature;signatureType;encryptionType;groupKeyId;newGroupKey;constructor({messageId:t,prevMsgRef:r,messageType:n=e.StreamMessageType.MESSAGE,content:i,contentType:s,signature:o,signatureType:a,encryptionType:c,groupKeyId:u,newGroupKey:l}){!function(e,t){if(void 0===t)return;const r=e.toMessageRef().compareTo(t);if(0===r)throw new AW(`prevMessageRef cannot be identical to current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`);if(r<0)throw new AW(`prevMessageRef must come before current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`)}(t,r),c===e.EncryptionType.AES&&SW("groupKeyId",u),this.messageId=t,this.prevMsgRef=r,this.messageType=n,this.contentType=s,this.encryptionType=c,this.groupKeyId=u,this.newGroupKey=l,this.signature=o,this.signatureType=a,this.content=i}getStreamId(){return this.messageId.streamId}getStreamPartition(){return this.messageId.streamPartition}getStreamPartID(){return this.messageId.getStreamPartID()}getTimestamp(){return this.messageId.timestamp}getSequenceNumber(){return this.messageId.sequenceNumber}getPublisherId(){return this.messageId.publisherId}getMsgChainId(){return this.messageId.msgChainId}getMessageRef(){return new RW(this.getTimestamp(),this.getSequenceNumber())}getParsedContent(){if(this.encryptionType!==e.EncryptionType.NONE||this.contentType===e.ContentType.BINARY)return this.content;if(this.contentType!==e.ContentType.JSON)throw new uA(`Unknown content type: ${this.contentType}`,"ASSERTION_FAILED",this);try{return JSON.parse(fw(this.content))}catch(e){throw new uA(`Unable to parse JSON: ${e}`,"INVALID_MESSAGE_CONTENT",this)}}static isAESEncrypted(t){return t.encryptionType===e.EncryptionType.AES}}class TW{static toProtobuf(t){const r={timestamp:t.getTimestamp(),sequenceNumber:t.getSequenceNumber(),streamId:t.getStreamId(),streamPartition:t.getStreamPartition(),publisherId:RE(t.getPublisherId()),messageChainId:t.getMsgChainId()};let n,i;if(t.prevMsgRef&&(n={timestamp:t.prevMsgRef.timestamp,sequenceNumber:t.prevMsgRef.sequenceNumber}),t.messageType===e.StreamMessageType.MESSAGE){let e;t.newGroupKey&&(e={id:t.newGroupKey.id,data:t.newGroupKey.data}),i={oneofKind:"contentMessage",contentMessage:{content:t.content,contentType:t.contentType,encryptionType:t.encryptionType,groupKeyId:t.groupKeyId??void 0,newGroupKey:e}}}else if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)i={oneofKind:"groupKeyRequest",groupKeyRequest:DH.fromBinary(t.content)};else{if(t.messageType!==e.StreamMessageType.GROUP_KEY_RESPONSE)throw new Error("invalid message type");i={oneofKind:"groupKeyResponse",groupKeyResponse:BH.fromBinary(t.content)}}return{messageId:r,previousMessageRef:n,signature:t.signature,signatureType:t.signatureType,body:i}}static toClientProtocol(t){let r,n,i,s,o=e.ContentType.BINARY,a=e.EncryptionType.NONE;if("contentMessage"===t.body.oneofKind)r=e.StreamMessageType.MESSAGE,n=t.body.contentMessage.content,o=t.body.contentMessage.contentType,a=t.body.contentMessage.encryptionType,i=t.body.contentMessage.newGroupKey,s=t.body.contentMessage.groupKeyId;else if("groupKeyRequest"===t.body.oneofKind){r=e.StreamMessageType.GROUP_KEY_REQUEST;try{n=DH.toBinary(t.body.groupKeyRequest)}catch(e){throw new Error(`invalid group key request: ${e}`)}}else{if("groupKeyResponse"!==t.body.oneofKind)throw new Error("invalid message type");r=e.StreamMessageType.GROUP_KEY_RESPONSE;try{n=BH.toBinary(t.body.groupKeyResponse)}catch(e){throw new Error(`invalid group key response: ${e}`)}}const c=new CW(t.messageId.streamId,t.messageId.streamPartition,Number(t.messageId.timestamp),t.messageId.sequenceNumber,kE(t.messageId.publisherId),t.messageId.messageChainId);let u;t.previousMessageRef&&(u=new RW(Number(t.previousMessageRef.timestamp),t.previousMessageRef.sequenceNumber));return new PW({messageId:c,prevMsgRef:u,messageType:r,content:n,contentType:o,signature:t.signature,signatureType:t.signatureType,encryptionType:a,groupKeyId:s,newGroupKey:i})}}function _W(e){return TW.toClientProtocol(xH.fromBinary(e))}async function*NW(e,t,r){let n=0;for await(const r of e){try{await t(r,n,e)}catch(e){throw e}finally{n+=1}yield r}}async function*MW(e,t,r){let n=0;for await(const r of e)try{yield await t(r,n,e)}catch(e){throw e}finally{n+=1}}async function*xW(e,t,r){let n=0;for await(const i of e){let s;try{s=await t(i,n,e)}catch(e){if(r){await r(e,i);continue}throw e}finally{n+=1}s&&(yield i)}}class OW{isLocked=!1;pending;open(){this.isLocked||this.clearPending()}lock(){this.isLocked||(this.isLocked=!0,this.clearPending())}error(e){this.isLocked||this.clearPending(e)}close(){this.isLocked||(this.pending??=new eb)}setOpenState(e){e?this.open():this.close()}isOpen(){return!this.isLocked&&!this.pending}clearPending(e){const{pending:t}=this;t&&(this.pending=void 0,e?t.reject(e):t.resolve(void 0))}async check(){return this.pending&&await this.pending,!this.isLocked}}class DW{buffer=[];bufferSize;writeGate;readGate;error;iterator;isIterating=!1;constructor(e=256){if(!(e>0&&Number.isSafeInteger(e)))throw new uA(`bufferSize must be a safe positive integer, got: ${e}`,"INVALID_ARGUMENT");this.bufferSize=e,this.writeGate=new OW,this.readGate=new OW,this.writeGate.close(),this.readGate.close(),this.iterator=this.iterate()}async push(e){return!!this.isWritable()&&(this.buffer.push(e),this.updateWriteGate(),this.readGate.open(),this.writeGate.check())}updateWriteGate(){this.writeGate.setOpenState(!this.isFull())}end(e){e&&(this.error=e),this.lock()}lock(){this.writeGate.lock(),this.readGate.lock()}endWrite(e){e&&!this.error&&(this.error=e),this.readGate.open(),this.writeGate.lock()}isFull(){return this.buffer.length>=this.bufferSize}isDone(){return this.writeGate.isLocked&&this.readGate.isLocked}isWritable(){return!this.writeGate.isLocked&&!this.readGate.isLocked}async*iterate(){this.isIterating=!0;try{for(;!this.readGate.isLocked;){for(;this.buffer.length&&!this.readGate.isLocked;){const t=this.buffer.shift();if(this.updateWriteGate(),(e=t)&&(e instanceof Error||e?.stack&&e.message&&"string"==typeof e.stack&&"string"==typeof e.message))throw t;yield t}if(0===this.buffer.length&&this.writeGate.isLocked)break;if(this.isDone())break;this.readGate.close();if(!await this.readGate.check())break}const{error:t}=this;if(t)throw this.error=void 0,t}finally{this.buffer=[],this.lock()}var e}get length(){return this.buffer.length}clear(){this.buffer=[]}async throw(e){return this.endWrite(e),this.iterator.throw(e)}async return(e){return this.end(),this.iterator.return(e)}next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new this.constructor.Error(this,"already iterating");return this}async[Symbol.asyncDispose](){this.end()}}var BW,LW,FW=pt();function UW(e,t){if("pipe"in e)return e;const r=new Tr.PassThrough(t);return async function(e,t){const r=e.getReader(),n=new AbortController;try{for(;;){const{value:e,done:i}=await r.read();if(i)break;if(!t.writable)break;if(!t.write(e))try{await FW.once(t,"drain",n)}catch(e){if("AbortError"===e.name)break;throw e}}}catch(e){t.destroy(e),n.abort()}finally{t.end();try{await r.cancel()}catch(e){}r.releaseLock()}}(e,r),r}var jW=function(){if(LW)return BW;LW=1;var e=Ju(),t=0;return BW=function(r){var n=++t;return e(r)+n},BW}(),qW=n(jW);let zW;function KW(e=""){return void 0===zW&&(zW=xF()),qW(`${zW}${e?`-${e}`:""}`)}const GW=new Bv("sdk-utils"),VW=((e,{maxPrefixes:t=256}={})=>{let r={},n=!1;const i=(i="ID",s="-")=>{if(r[i]=(r[i]+1||0)%Number.MAX_SAFE_INTEGER,!n){const e=Object.keys(r).length;e>t&&(n=!0,console.warn(`counterId should not be used for a large number of unique prefixes: ${e} > ${t}`))}return[e,i,r[i]].filter((e=>null!=e)).join(s)};return i.clear=(...e)=>{if(e.length){const[t]=e;delete r[t]}else r={}},i})();function HW(e){return bE("/assignments",nb(e))}class $W{delegate;constructor(e){this.delegate=new Mj({maxSize:e,sizeCalculation:()=>1})}add(e){this.delegate.set(e,!0)}has(e){return this.delegate.has(e)}delete(e){this.delegate.delete(e)}}function WW(t){const r=t.type===e.NetworkNodeType.BROWSER?bq.BROWSER:bq.NODEJS,n={...t,nodeId:Yj(t.nodeId??t.id),type:r,websocket:t.websocket};return void 0!==n.id&&delete n.id,n}function JW(t){return{nodeId:Zj(t.nodeId),type:t.type===bq.NODEJS?e.NetworkNodeType.NODEJS:e.NetworkNodeType.BROWSER,websocket:t.websocket,region:t.region}}const QW=e=>Array.isArray(e)?e.map((e=>e.toString())).join("|"):e.toString();class ZW extends Error{response;constructor(e){super(`Fetch error, url=${e.url}`),this.response=e}}var YW,XW={exports:{}};var eJ=function(){if(YW)return XW.exports;YW=1;class e extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}}return XW.exports=({limit:t,interval:r,strict:n})=>{if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(r))throw new TypeError("Expected `interval` to be a finite number");const i=new Map;let s=0,o=0;const a=[];const c=n?function(){const e=Date.now();if(a.length<t)return a.push(e),0;const n=a.shift()+r;return e>=n?(a.push(e),0):(a.push(n),n-e)}:function(){const e=Date.now();return e-s>r?(o=1,s=e,0):(o<t?o++:(s+=r,o=1),s-e)};return t=>{const r=function(...e){if(!r.isEnabled)return(async()=>t.apply(this,e))();let n;return new Promise(((r,s)=>{n=setTimeout((()=>{r(t.apply(this,e)),i.delete(n)}),c()),i.set(n,s)}))};return r.abort=()=>{for(const t of i.keys())clearTimeout(t),i.get(t)(new e);i.clear(),a.splice(0,a.length)},r.isEnabled=!0,r}},XW.exports.AbortError=e,XW.exports}(),tJ=n(eJ);function rJ(e,t=1){const r=gD(t);return Object.assign(((...t)=>r((()=>e(...t)))),{clear(){r.clearQueue()}})}function nJ(e){let t={status:"init"};return Object.assign((async function(...r){const n=t;if("pending"===n.status)return n.promise;if("fulfilled"===n.status)return n.value;if("rejected"===n.status)throw n.reason;t=n;const i=(async()=>{try{const t=await e(...r);return Object.assign(n,{promise:void 0,status:"fulfilled",value:t}),t}catch(e){throw Object.assign(n,{promise:void 0,status:"rejected",reason:e}),e}})();return i.catch((()=>{})),Object.assign(n,{status:"pending",promise:i}),i}),{isStarted:()=>"init"!==t.status,reset(){t={status:"init"}}})}var iJ;!function(e){e.ONCE="ONCE",e.ONE="ONE",e.QUEUE="QUEUE",e.PARALLEL="PARALLEL"}(iJ||(iJ={}));class sJ{static TRIGGER_TYPE=iJ;static create(e=iJ.PARALLEL){return new this(e)}static once(){return this.create(iJ.ONCE)}static one(){return this.create(iJ.ONE)}static queue(){return this.create(iJ.QUEUE)}static parallel(){return this.create(iJ.PARALLEL)}listeners=[];isEnded=!1;triggerCountValue=0;triggerType;constructor(e=iJ.PARALLEL){switch(this.triggerType=e,this.trigger=Function.prototype.bind.call(this.trigger,this),e){case iJ.ONCE:this.trigger=nJ(this.trigger);break;case iJ.QUEUE:this.trigger=rJ(this.trigger);break;case iJ.ONE:this.trigger=function(e){const t=nJ(e);return async(...e)=>{try{return await t(...e)}finally{t.reset()}}}(this.trigger);break;case iJ.PARALLEL:break;default:throw new Error(`unknown trigger type: ${e}`)}}triggerCount(){return this.triggerCountValue}lastValue;end=(...e)=>{this.lastValue=e,this.isEnded=!0};wait(){return new Promise((e=>{this.once(((...t)=>e(t[0])))}))}async getLastValue(){if(this.currentTask&&await this.currentTask,!this.lastValue)throw new Error("Signal ended with no value");return this.lastValue}listen(e){return e?this.isEnded?(this.getLastValue().then((t=>e(...t))).catch((()=>{})),this):(this.listeners.push(e),this):new Promise((e=>{this.once(((...t)=>{e(t[0])}))}))}once(e){if(!e)return this.listen();const t=Object.assign(((...t)=>(this.unlisten(e),e(...t))),{listener:e});return this.listen(t)}countListeners(){return this.listeners.length}unlisten(e){const t=this.listeners.findIndex((t=>t===e||"listener"in t&&t.listener===e));return this.listeners.splice(t,1),this}async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{await t,await r(...e)}),Promise.resolve())}currentTask;async trigger(...e){const t=this.execTrigger(...e);this.currentTask=t;try{await this.currentTask}finally{this.currentTask===t&&(this.currentTask=void 0)}}async*[Symbol.asyncIterator](){for(;!this.isEnded;)yield await this.listen()}}class oJ extends sJ{seenErrors=new WeakSet;ignoredErrors=new WeakSet;minListeners=1;async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{try{await t}catch(e){return void await r(e)}await r(...e)}),Promise.resolve())}async trigger(...e){const t=e[0];if(this.ignoredErrors.has(t))return;if(this.seenErrors.has(t))throw t;this.seenErrors.add(t);const r=!!(this.countListeners()>=this.minListeners);try{if(await super.trigger(...e),!r)throw t;this.ignoredErrors.add(t)}catch(e){throw this.seenErrors.add(e),e}}}class aJ{source;transforms;constructor(e,t=[]){this.source=this.setSource(e),this.transforms=t}pipe(e){return this.transforms.push(e),this}clearTransforms(){this.transforms=[]}setSource(e){const t="id"in e?e.id:function(e,t=""){return VW(e.constructor.name)+t}(e,"Source");return this.source=Object.assign(e,{id:t}),this.source}getTransforms(){return this.transforms}}class cJ{source;iterator;isIterating=!1;isCleaningUp=!1;definition;constructor(e,t){this.source=e,this.definition=t??new aJ(e),this.cleanup=nJ(this.cleanup.bind(this)),this.iterator=function(e,t){if(!t)return async function*(){yield*e}();let r,n,i=!1,s=!1,o=e=>(n??=Promise.resolve(t(e)).finally((()=>{o=()=>{}})),n);function a(e){return async(...t)=>{if(s=!0,i)return e(...t);try{return await e(...t)}catch(e){throw r??=e,e}finally{await o(r)}}}const c=async function*(){i=!0;try{yield*e}catch(e){throw r??=e,e}finally{await o(r)}}(),u=c[Symbol.asyncIterator].bind(c);let l;return l="cancel"in e?Object.assign(c,{cancel:t=>e.cancel(t),isCancelled:()=>e.isCancelled()}):c,Object.assign(l,{return:a(l.return.bind(l)),throw:a(l.throw.bind(l)),[Symbol.asyncIterator]:()=>s&&!i?async function*(){try{"return"in e&&await e.return(void 0)}finally{await o()}}():u()})}(this.iterate(),this.cleanup),this.handleError=this.handleError.bind(this)}pipe(e){if(this.isIterating)throw new uA(`cannot pipe after already iterating: ${this.isIterating}`,"PIPELINE_ERROR");return this.definition.pipe(e),this}onFinally=sJ.once();onBeforeFinally=sJ.once();onMessage=sJ.create();onError=oJ.create();filter(e){return this.pipe((t=>xW(t,e,this.onError.trigger)))}flow(){return setImmediate((()=>{this.isIterating||async function(e,t=e=>e){(async e=>{for await(const t of e);})(NW(e,t))}(this)})),this}async cleanup(e){this.isCleaningUp=!0;try{try{e&&await this.onError.trigger(e)}finally{await this.definition.source.return(void 0)}}finally{await this.onBeforeFinally.trigger(),await this.onFinally.trigger(e),this.definition.clearTransforms()}}async handleError(e){await this.onError.trigger(e)}async*iterate(){if(this.isIterating=!0,!this.definition.source)throw new uA("no source","PIPELINE_ERROR");const e=this.definition.getTransforms().reduce(((e,t)=>t(e)),this.definition.source);try{for await(const t of e)await this.onMessage.trigger(t),yield t;this.isCleaningUp=!0}catch(e){this.isCleaningUp=!0,await this.handleError(e)}finally{this.isCleaningUp=!0,this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger()}}async throw(e){if(this.isCleaningUp)throw e;return this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.throw(e).catch((()=>{})),this.iterator.throw(e)}async return(e){return this.isCleaningUp?Promise.resolve({done:!0,value:e}):(this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.return(void 0),this.iterator.return(e))}async next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new uA("already iterating","PIPELINE_ERROR");return this}[Symbol.asyncDispose](){return this.cleanup()}}class uJ extends cJ{source;constructor(e=256){const t=new DW(e);super(t),this.source=t}pipe(e){return super.pipe(e),this}filter(e){return super.filter(e)}async push(e){return this.source.push(e)}async handleError(e){try{await this.onError.trigger(e)}catch(e){if(this.isCleaningUp)throw e;await this.push(e)}}end(e){this.source.end(e)}endWrite(e){this.source.endWrite(e)}isDone(){return this.source.isDone()}get length(){return this.source.length||0}clear(){this.source.clear()}}var lJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},hJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let dJ=class{onDestroy=sJ.once();trigger=this.destroy;abortSignal;constructor(){const e=new AbortController;this.abortSignal=e.signal,this.onDestroy.listen((()=>{e.abort()}))}destroy(){return this.onDestroy.trigger()}assertNotDestroyed(){if(this.isDestroyed())throw new uA("Client is destroyed. Create a new instance","CLIENT_DESTROYED")}isDestroyed(){return this.onDestroy.triggerCount()>0}};var fJ,pJ,gJ,mJ,yJ,bJ;dJ=lJ([q(d.ContainerScoped),hJ("design:paramtypes",[])],dJ);var wJ=function(){if(bJ)return yJ;bJ=1;var e=Jc(),t=function(){if(pJ)return fJ;pJ=1;var e=Vc(),t=$c(),r=Wc(),n=Jc(),i=Qc(),s=Zc(),o=Math.min;return fJ=function(a,c,u){for(var l=u?r:t,h=a[0].length,d=a.length,f=d,p=Array(d),g=1/0,m=[];f--;){var y=a[f];f&&c&&(y=n(y,i(c))),g=o(y.length,g),p[f]=!u&&(c||h>=120&&y.length>=120)?new e(f&&y):void 0}y=a[0];var b=-1,w=p[0];e:for(;++b<h&&m.length<g;){var v=y[b],E=c?c(v):v;if(v=u||0!==v?v:0,!(w?s(w,E):l(m,E,u))){for(f=d;--f;){var A=p[f];if(!(A?s(A,E):l(a[f],E,u)))continue e}w&&w.push(E),m.push(v)}}return m},fJ}(),r=nu(),n=function(){if(mJ)return gJ;mJ=1;var e=ou();return gJ=function(t){return e(t)?t:[]}}(),i=r((function(r){var i=e(r,n);return i.length&&i[0]===r[0]?t(i):[]}));return yJ=i}(),vJ=n(wJ),EJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},AJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},SJ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function kJ(e){const t=e;if(void 0!==t.id)return t.id;if(void 0!==t.stream)return t.stream;if(void 0!==t.streamId)return t.streamId;throw new Error('streamDefinition: object must have property: "id", "stream", or "streamId"')}let RJ=class{identity;constructor(e){this.identity=e}async toStreamID(e){let t;return wE.isPathOnlyFormat(e)&&(t=nb(await this.identity.getUserId())),bE(e,t)}async toStreamPartID(e){const[t,r]=await this.toStreamPartElements(e);return EE(t,r??0)}async toStreamPartElements(e){const[t,r]=function(e){if("string"==typeof e)return AE.parseRawElements(e);if("object"==typeof e)return[kJ(e),e.partition];throw new Error("streamDefinition: must be of type string or object")}(e);return[await this.toStreamID(t),r]}async getMatcher(e){const[t,r]=await this.toStreamPartElements(e);return e=>t===AE.getStreamID(e)&&(void 0===r||r===AE.getStreamPartition(e))}};RJ=EJ([q(d.ContainerScoped),SJ(0,U(kA)),AJ("design:paramtypes",[RA])],RJ);const CJ=e=>{try{return JSON.parse(e)}catch(e){return{}}},IJ=e=>{const t=e.partitions;if(void 0!==t)try{!function(e){if(!Number.isSafeInteger(e)||e<0||e>100)throw new Error(`invalid streamPartition value: ${e}`)}(t)}catch{throw new uA(`Invalid partition count: ${t}`,"INVALID_STREAM_METADATA")}return t??1};var PJ;e.StreamPermission=void 0,(PJ=e.StreamPermission||(e.StreamPermission={})).EDIT="edit",PJ.DELETE="delete",PJ.PUBLISH="publish",PJ.SUBSCRIBE="subscribe",PJ.GRANT="grant";const TJ="0x0000000000000000000000000000000000000000",_J=e=>!0===e.public,NJ=e=>"userId"in e?{...e,userId:kE(e.userId)}:e,MJ=t=>{switch(t){case e.StreamPermission.EDIT:return 0n;case e.StreamPermission.DELETE:return 1n;case e.StreamPermission.PUBLISH:return 2n;case e.StreamPermission.SUBSCRIBE:return 3n;case e.StreamPermission.GRANT:return 4n}return 0n},xJ=t=>{const r=Math.round(Date.now()/1e3),n=[];return t.canEdit&&n.push(e.StreamPermission.EDIT),t.canDelete&&n.push(e.StreamPermission.DELETE),t.publishExpiration>r&&n.push(e.StreamPermission.PUBLISH),t.subscribeExpiration>r&&n.push(e.StreamPermission.SUBSCRIBE),t.canGrant&&n.push(e.StreamPermission.GRANT),n};class OJ{delegate;pendingPromises=new Map;opts;constructor(e){this.delegate="maxSize"in e?new Mj({maxSize:e.maxSize,sizeCalculation:()=>1,ttl:e.maxAge}):new Map,this.opts={isCacheableValue:()=>!0,...e}}async get(e){const t=QW(e),r=this.pendingPromises.get(t);if(void 0!==r)return await r;{let r=this.delegate.get(t);if(void 0===r){const n=this.opts.valueFactory(e);let i;this.pendingPromises.set(t,n);try{i=await n}finally{this.pendingPromises.delete(t)}r={key:e,value:i},this.opts.isCacheableValue(i)&&this.delegate.set(t,r)}return r.value}}set(e,t){this.delegate.set(QW(e),{key:e,value:t})}invalidate(e){for(const[t,r]of this.delegate.entries())e(r.key)&&this.delegate.delete(t)}*values(){for(const e of this.delegate.values())yield e.value}}const DJ=e=>new OJ(e),BJ=e=>new OJ(e);var LJ,FJ,UJ,jJ,qJ,zJ,KJ,GJ;function VJ(){if(jJ)return UJ;jJ=1;var e=Pl(),t=uj(),r=function(){if(FJ)return LJ;FJ=1;var e=sL(),t=Ku();return LJ=function(r,n){return n.length<2?r:e(r,t(n,0,-1))},LJ}(),n=_l();return UJ=function(i,s){return s=e(s,i),null==(i=r(i,s))||delete i[n(t(s))]},UJ}var HJ,$J,WJ,JJ,QJ,ZJ,YJ,XJ,eQ=function(){if(GJ)return KJ;GJ=1;var e=uL(),t=function(){if(zJ)return qJ;zJ=1;var e=VJ(),t=Tl(),r=Array.prototype.splice;return qJ=function(n,i){for(var s=n?i.length:0,o=s-1;s--;){var a=i[s];if(s==o||a!==c){var c=a;t(a)?r.call(n,a,1):e(n,a)}}return n},qJ}();return KJ=function(r,n){var i=[];if(!r||!r.length)return i;var s=-1,o=[],a=r.length;for(n=e(n,3);++s<a;){var c=r[s];n(c,s,r)&&(i.push(c),o.push(s))}return t(r,o),i},KJ}(),tQ=n(eQ);function rQ(){if(JJ)return WJ;JJ=1;var e=YB(),t=$J?HJ:($J=1,HJ=function(){}),r=VB(),n=e&&1/r(new e([,-0]))[1]==1/0?function(t){return new e(t)}:t;return WJ=n}var nQ=function(){if(XJ)return YJ;XJ=1;var e=function(){if(ZJ)return QJ;ZJ=1;var e=Vc(),t=$c(),r=Wc(),n=Zc(),i=rQ(),s=VB();return QJ=function(o,a,c){var u=-1,l=t,h=o.length,d=!0,f=[],p=f;if(c)d=!1,l=r;else if(h>=200){var g=a?null:i(o);if(g)return s(g);d=!1,l=n,p=new e}else p=a?[]:f;e:for(;++u<h;){var m=o[u],y=a?a(m):m;if(m=c||0!==m?m:0,d&&y==y){for(var b=p.length;b--;)if(p[b]===y)continue e;a&&p.push(y),f.push(m)}else l(p,y,c)||(p!==f&&p.push(y),f.push(m))}return f},QJ}();return YJ=function(t){return t&&t.length?e(t):[]},YJ}(),iQ=n(nQ),sQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},oQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},aQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let cQ=class{listeners=[];providers;pollInterval;abortController;constructor(e,t){this.providers=e.getSubProviders(),this.pollInterval=t.contracts.pollInterval}on(e){const t=this.listeners.length>0;this.listeners.push(e),t||this.start()}off(e){const t=this.listeners.length>0;tQ(this.listeners,(t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.topicHash===e.contractInterfaceFragment.topicHash&&t.onEvent==e.onEvent)),t&&0===this.listeners.length&&this.abortController.abort()}start(){const e=new AbortController;this.abortController=e,setImmediate((async()=>{const t=new Bv("ChainEventPoller",{sessionId:Wv(6)});let r;t.debug("Start polling",{pollInterval:this.pollInterval});do{try{r=await oA(this.providers).getBlockNumber()}catch(e){t.debug("Failed to query block number",{err:e}),await Qv(1e3)}}while(void 0===r);let n=0;await Jv((async()=>{const i=oA(this.providers),s=this.listeners.map((e=>e.contractInterfaceFragment.name));let o,a=0;try{if(n>=30&&(a=await i.getBlockNumber()+1,t.debug("Fetch next block number explicitly",{newFromBlock:a}),e.signal.aborted))return;t.debug("Polling",{fromBlock:r,eventNames:s});const c={address:iQ(this.listeners.map((e=>e.contractAddress))),topics:[iQ(this.listeners.map((e=>e.contractInterfaceFragment.topicHash)))],fromBlock:r},u=await i.getLogs(c);o=[];for(const e of u){const t=this.listeners.find((t=>t.contractAddress===nb(e.address)&&t.contractInterfaceFragment.topicHash===e.topics[0]));if(void 0!==t){const r=new uN([t.contractInterfaceFragment.format("minimal")]).decodeEventLog(t.contractInterfaceFragment.name,e.data,e.topics);o.push({contractAddress:t.contractAddress,name:t.contractInterfaceFragment.name,args:r,blockNumber:e.blockNumber})}}t.debug("Polled",{fromBlock:r,events:o.length})}catch(e){t.debug("Failed to poll",{reason:e?.reason,eventNames:s,fromBlock:r})}if(!e.signal.aborted){if(void 0!==o&&o.length>0){for(const e of o){const t=this.listeners.filter((t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.name===e.name));for(const r of t)r.onEvent(e.args,e.blockNumber)}a=Math.max(...o.map((e=>e.blockNumber)))+1}void 0!==o&&a>r?(t.debug("Forward fromBlock",{before:r,after:a}),r=a,n=0):n+=1}}),this.pollInterval,!0,e.signal)}))}};cQ=sQ([q(d.ContainerScoped),aQ(1,U(cA)),oQ("design:paramtypes",[e.RpcProviderSource,Object])],cQ);const uQ=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),lQ=e=>`"${e}"`,hQ=e=>`{ ${e} }`,dQ=(t,r,n)=>{const i=[];return t.includes(e.StreamPermission.EDIT)&&i.push("canEdit: true"),t.includes(e.StreamPermission.DELETE)&&i.push("canDelete: true"),t.includes(e.StreamPermission.PUBLISH)&&i.push(`publishExpiration_gt: "${n}"`),t.includes(e.StreamPermission.SUBSCRIBE)&&i.push(`subscribeExpiration_gt: "${n}"`),t.includes(e.StreamPermission.GRANT)&&i.push("canGrant: true"),`${r}: [${i.map(hQ).join(", ")}]`},fQ=(t,r,n,i)=>{const s=[];if(s.push(`id_gt: "${uQ(n)}"`),void 0!==t&&s.push(`idAsString_contains: "${uQ(t)}"`),void 0!==r){const t=[],n=[r.userId];r.allowPublic&&n.push(TJ),t.push(`userId_in: [${n.map(lQ).join(",")}]`);const i=Math.round(Date.now()/1e3);void 0!==r.allOf&&t.push(dQ(r.allOf,"and",i));const o=r.anyOf??(void 0===r.allOf||0===r.allOf.length?Object.values(e.StreamPermission):void 0);void 0!==o&&t.push(dQ(o,"or",i)),s.push(`permissions_: { and: [${t.map(hQ).join(", ")}] }`)}return{query:`\n query {\n streams (\n first: ${i}\n orderBy: "id"\n where: {\n ${s.join(", ")}\n }\n ) {\n id\n metadata\n }\n }`}};var pQ,gQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},mQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},yQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const bQ=t=>{for(const r of t){const t=[e.StreamPermission.EDIT,e.StreamPermission.DELETE,e.StreamPermission.GRANT],n=vJ(r.permissions,t);if(n.length>0){const e=e=>new uA(`${e} is not supported for permission types: ${n.map((e=>e.toUpperCase())).join(", ")}`,"UNSUPPORTED_OPERATION");if(_J(r))throw e("Public permission");if(42!==r.userId.length)throw e("Non-Ethereum user id")}}},wQ=(e,t,r)=>{throw"CALL_EXCEPTION"===e.reason?.code?new uA("Stream not found: id="+t,"STREAM_NOT_FOUND"):new Error(`Could not reach the ${r} Smart Contract: ${e.message}`)},vQ=(e,t)=>{e.invalidate((e=>(Array.isArray(e)?e[0]:e)===t))};let EQ=pQ=class{streamRegistryContract;streamRegistryContractReadonly;contractFactory;rpcProviderSource;theGraphClient;streamIdBuilder;config;identity;logger;metadataCache;publisherCache;subscriberCache;publicSubscribePermissionCache;constructor(t,r,n,i,s,o,a,c,u){this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.streamIdBuilder=s,this.config=o,this.identity=a,this.logger=u.createLogger("StreamRegistry"),this.streamRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,this.rpcProviderSource.getProvider(),"streamRegistry"),wD({sourceDefinition:{contractInterfaceFragment:new uN(SA.StreamRegistryABI).getEvent("StreamCreated"),contractAddress:nb(this.config.contracts.streamRegistryChainAddress)},sourceEmitter:n,targetName:"streamCreated",targetEmitter:c,transformation:([e,t],r)=>({streamId:bE(e),metadata:CJ(t),blockNumber:r}),loggerFactory:u}),this.metadataCache=DJ({valueFactory:e=>this.getStreamMetadata_nonCached(e),...o.cache}),this.publisherCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.PUBLISH),...o.cache}),this.subscriberCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.SUBSCRIBE),...o.cache}),this.publicSubscribePermissionCache=DJ({valueFactory:t=>this.hasPermission({streamId:t,public:!0,permission:e.StreamPermission.SUBSCRIBE}),...o.cache})}async connectToContract(){if(void 0===this.streamRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,e,"streamRegistry")}}async createStream(e,t){const r=await nD(this.rpcProviderSource,this.config),n=wE.getDomainAndPath(e);if(void 0===n)throw new Error(`stream id "${e}" not valid`);const[i,s]=n;if(await this.connectToContract(),function(e){return tb(e)}(i)){await mD(this.streamRegistryContract.createStreamWithENS(i,s,JSON.stringify(t),r));try{await iE((async()=>this.streamExistsOnChain(e)),this.config._timeouts.ensStreamCreation.timeout,this.config._timeouts.ensStreamCreation.retryInterval)}catch{throw new Error(`unable to create stream "${e}"`)}}else await this.ensureStreamIdInNamespaceOfAuthenticatedUser(i,e),await mD(this.streamRegistryContract.createStream(s,JSON.stringify(t),r));this.populateMetadataCache(e,t)}async ensureStreamIdInNamespaceOfAuthenticatedUser(e,t){const r=nb(await this.identity.getUserId());if(e!==r)throw new Error(`stream id "${t}" not in namespace of authenticated user "${r}"`)}async setStreamMetadata(e,t){await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.updateStreamMetadata(e,JSON.stringify(t),r)),this.populateMetadataCache(e,t)}async deleteStream(e){const t=await this.streamIdBuilder.toStreamID(e);await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.deleteStream(t,r)),vQ(this.metadataCache,t),this.invalidatePermissionCaches(t)}async streamExistsOnChain(e){const t=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream exists on chain",{streamId:t}),this.streamRegistryContractReadonly.exists(t)}async getStreamMetadata_nonCached(e){let t;try{t=await this.streamRegistryContractReadonly.getStreamMetadata(e)}catch(t){return wQ(t,e,"StreamRegistry")}return CJ(t)}async*searchStreams(e,t){const r=async function*(e,t,r){yield*r.queryEntities(((r,n)=>fQ(e,t,r,n)))}(e,t,this.theGraphClient);for await(const e of r){const t=bE(e.id);this.populateMetadataCache(t,CJ(e.metadata)),yield t}}getStreamPublishers(e){return this.getStreamPublishersOrSubscribersList(e,"publishExpiration")}getStreamSubscribers(e){return this.getStreamPublishersOrSubscribersList(e,"subscribeExpiration")}async*getStreamPublishersOrSubscribersList(e,t){const r=await this.streamIdBuilder.toStreamID(e),n=xW(this.theGraphClient.queryEntities(((e,n)=>pQ.buildStreamPublishersOrSubscribersQuery(r,t,e,n))),(e=>null!==e.stream));yield*MW(n,(e=>kE(e.userId)))}static buildStreamPublishersOrSubscribersQuery(e,t,r,n){return{query:`\n {\n streamPermissions (\n first: ${n}\n orderBy: "id"\n where: {\n id_gt: "${r}"\n stream: "${e}"\n ${t}_gt: "${Math.round(Date.now()/1e3)}"\n }\n ) {\n id\n userId\n stream {\n id\n }\n }\n }`}}async hasPermission(e){if((e=>!0===e.public)(e)){const t=MJ(e.permission);return this.streamRegistryContractReadonly.hasPublicPermission(e.streamId,t)}{const t=e.allowPublic?await this.streamRegistryContractReadonly.getPermissionsForUserId(e.streamId,e.userId):await this.streamRegistryContractReadonly.getDirectPermissionsForUserId(e.streamId,e.userId);return xJ(t).includes(e.permission)}}async getPermissions(e){const t=await this.streamIdBuilder.toStreamID(e),r=await cE(this.theGraphClient.queryEntities(((e,r)=>({query:`{\n stream (id: "${t}") {\n id\n metadata\n permissions(first: ${r} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n userId\n canEdit\n canDelete\n publishExpiration\n subscribeExpiration\n canGrant\n }\n }\n }`})),(e=>{if(null!==e.stream)return e.stream.permissions;throw new uA("Stream not found: id="+t,"STREAM_NOT_FOUND")}))),n=[];return r.forEach((e=>{const t=xJ(e);t.length>0&&(e.userId===TJ?n.push({public:!0,permissions:t}):n.push({userId:kE(e.userId),permissions:t}))})),n}async grantPermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.grantPublicPermission(e,n,r):this.streamRegistryContract.grantPermissionForUserId(e,t,n,r)),...t)}async revokePermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.revokePublicPermission(e,n,r):this.streamRegistryContract.revokePermissionForUserId(e,t,n,r)),...t)}async updatePermissions(e,t,...r){const n=await this.streamIdBuilder.toStreamID(e);this.invalidatePermissionCaches(n),await this.connectToContract();for(const e of r)for(const r of e.permissions){const i=MJ(r),s=t(n,_J(e)?void 0:e.userId,i);await mD(s)}}async setPermissions(...t){const r=[],n=[],i=[];for(const s of t){bQ(s.assignments);const t=await this.streamIdBuilder.toStreamID(s.streamId);this.invalidatePermissionCaches(t),r.push(t),n.push(s.assignments.map((e=>_J(e)?TJ:e.userId))),i.push(s.assignments.map((t=>{return{canEdit:(r=t.permissions).includes(e.StreamPermission.EDIT),canDelete:r.includes(e.StreamPermission.DELETE),publishExpiration:r.includes(e.StreamPermission.PUBLISH)?PI:0n,subscribeExpiration:r.includes(e.StreamPermission.SUBSCRIBE)?PI:0n,canGrant:r.includes(e.StreamPermission.GRANT)};var r})))}await this.connectToContract();const s=await nD(this.rpcProviderSource,this.config),o=this.streamRegistryContract.setMultipleStreamPermissionsForUserIds(r,n,i,s);await mD(o)}async isStreamPublisherOrSubscriber_nonCached(e,t,r){try{return await this.hasPermission({streamId:e,userId:t,permission:r,allowPublic:!0})}catch(t){return wQ(t,e,"StreamPermission")}}getStreamMetadata(e){return this.metadataCache.get(e)}isStreamPublisher(e,t){return this.publisherCache.get([e,t])}isStreamSubscriber(e,t){return this.subscriberCache.get([e,t])}hasPublicSubscribePermission(e){return this.publicSubscribePermissionCache.get(e)}populateMetadataCache(e,t){this.metadataCache.set(e,t)}invalidatePermissionCaches(e){this.logger.trace("Clear permission caches for stream",{streamId:e}),vQ(this.publisherCache,e),vQ(this.subscriberCache,e)}};var AQ,SQ,kQ,RQ,CQ,IQ;EQ=pQ=gQ([q(d.ContainerScoped),yQ(5,U(cA)),yQ(6,U(kA)),mQ("design:paramtypes",[SD,e.RpcProviderSource,cQ,lE,RJ,Object,RA,sD,uD])],EQ);var PQ=function(){if(IQ)return CQ;IQ=1;var e=function(){if(SQ)return AQ;SQ=1;var e=Le();return AQ=function(t,r,n){for(var i=-1,s=t.length;++i<s;){var o=t[i],a=r(o);if(null!=a&&(void 0===c?a==a&&!e(a):n(a,c)))var c=a,u=o}return u},AQ}(),t=RQ?kQ:(RQ=1,kQ=function(e,t){return e<t}),r=Yc();return CQ=function(n){return n&&n.length?e(n,r,t):void 0},CQ}(),TQ=n(PQ),_Q=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},NQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},MQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const xQ=Symbol("GET_ALL_STORAGE_NODES");let OQ=class{streamStorageRegistryContract;streamStorageRegistryContractReadonly;streamIdBuilder;contractFactory;rpcProviderSource;theGraphClient;config;identity;logger;storageNodesCache;constructor(e,t,r,n,i,s,o,a,c){this.streamIdBuilder=e,this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.config=s,this.identity=o,this.logger=c.createLogger("StreamStorageRegistry"),this.streamStorageRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,r.getProvider(),"streamStorageRegistry"),this.initStreamAssignmentEventListeners(a,n,c),this.storageNodesCache=DJ({valueFactory:e=>this.getStorageNodes_nonCached(e),...s.cache})}initStreamAssignmentEventListeners(e,t,r){const n=([e,t],r)=>({streamId:bE(e),nodeAddress:nb(t),blockNumber:r}),i=nb(this.config.contracts.streamStorageRegistryChainAddress),s=new uN(SA.StreamStorageRegistryABI);wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Added"),contractAddress:i},sourceEmitter:t,targetName:"streamAddedToStorageNode",targetEmitter:e,transformation:n,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Removed"),contractAddress:i},sourceEmitter:t,targetName:"streamRemovedFromStorageNode",targetEmitter:e,transformation:n,loggerFactory:r})}async connectToContract(){if(!this.streamStorageRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamStorageRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,e,"streamStorageRegistry")}}async addStreamToStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Add stream to storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.addStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async removeStreamFromStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Remove stream from storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.removeStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async isStoredStream(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream is stored in storage node",{streamId:r,nodeAddress:t}),await this.streamStorageRegistryContractReadonly.isStorageNodeOf(r,t)}async getStoredStreams(e){this.logger.debug("Get stored streams of storage node",{nodeAddress:e});const t=[],r=(await cE(this.theGraphClient.queryEntities(((t,r)=>({query:`{\n node (id: "${e}") {\n id\n metadata\n lastSeen\n storedStreams (first: ${r} orderBy: "id" where: { id_gt: "${t}"}) {\n id,\n metadata\n }\n }\n _meta {\n block {\n number\n }\n }\n }`})),(e=>(t.push(e._meta.block.number),null!==e.node?e.node.storedStreams:[]))))).map((e=>({id:bE(e.id),metadata:CJ(e.metadata)})));return{streams:r,blockNumber:TQ(t)}}async getStorageNodes(e){const t=void 0!==e?await this.streamIdBuilder.toStreamID(e):xQ;return this.storageNodesCache.get(t)}async getStorageNodes_nonCached(e){let t;if(e!==xQ){const r=e;this.logger.debug("Get storage nodes of stream",{streamId:r}),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n stream (id: "${r}") {\n id\n metadata\n storageNodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }\n }`})),(e=>null!==e.stream?e.stream.storageNodes:[])))}else this.logger.debug("Get all storage nodes"),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n nodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }`}))));return t.map((e=>nb(e.id)))}};OQ=_Q([q(d.ContainerScoped),MQ(5,U(cA)),MQ(6,U(kA)),NQ("design:paramtypes",[RJ,SD,e.RpcProviderSource,cQ,lE,Object,RA,sD,uD])],OQ);
68
+ const lU=Symbol("Comlink.proxy"),hU=Symbol("Comlink.endpoint"),dU=Symbol("Comlink.releaseProxy"),fU=Symbol("Comlink.finalizer"),pU=Symbol("Comlink.thrown"),gU=e=>"object"==typeof e&&null!==e||"function"==typeof e,mU=new Map([["proxy",{canHandle:e=>gU(e)&&e[lU],serialize(e){const{port1:t,port2:r}=new MessageChannel;return yU(e,t),[r,[r]]},deserialize:e=>(e.start(),wU(e))}],["throw",{canHandle:e=>gU(e)&&pU in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function yU(e,t=globalThis,r=["*"]){t.addEventListener("message",(function n(i){if(!i||!i.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:s,type:o,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(TU);let u;try{const t=a.slice(0,-1).reduce(((e,t)=>e[t]),e),r=a.reduce(((e,t)=>e[t]),e);switch(o){case"GET":u=r;break;case"SET":t[a.slice(-1)[0]]=TU(i.data.value),u=!0;break;case"APPLY":u=r.apply(t,c);break;case"CONSTRUCT":u=IU(new r(...c));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;yU(e,r),u=function(e,t){return CU.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[pU]:0}}Promise.resolve(u).catch((e=>({value:e,[pU]:0}))).then((r=>{const[i,a]=PU(r);t.postMessage(Object.assign(Object.assign({},i),{id:s}),a),"RELEASE"===o&&(t.removeEventListener("message",n),bU(t),fU in e&&"function"==typeof e[fU]&&e[fU]())})).catch((e=>{const[r,n]=PU({value:new TypeError("Unserializable return value"),[pU]:0});t.postMessage(Object.assign(Object.assign({},r),{id:s}),n)}))})),t.start&&t.start()}function bU(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function wU(e,t){const r=new Map;return e.addEventListener("message",(function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}})),kU(e,r,[],t)}function vU(e){if(e)throw new Error("Proxy has been released and is not useable")}function EU(e){return _U(e,new Map,{type:"RELEASE"}).then((()=>{bU(e)}))}const AU=new WeakMap,SU="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(AU.get(e)||0)-1;AU.set(e,t),0===t&&EU(e)}));function kU(e,t,r=[],n=function(){}){let i=!1;const s=new Proxy(n,{get(n,o){if(vU(i),o===dU)return()=>{!function(e){SU&&SU.unregister(e)}(s),EU(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>s};const n=_U(e,t,{type:"GET",path:r.map((e=>e.toString()))}).then(TU);return n.then.bind(n)}return kU(e,t,[...r,o])},set(n,s,o){vU(i);const[a,c]=PU(o);return _U(e,t,{type:"SET",path:[...r,s].map((e=>e.toString())),value:a},c).then(TU)},apply(n,s,o){vU(i);const a=r[r.length-1];if(a===hU)return _U(e,t,{type:"ENDPOINT"}).then(TU);if("bind"===a)return kU(e,t,r.slice(0,-1));const[c,u]=RU(o);return _U(e,t,{type:"APPLY",path:r.map((e=>e.toString())),argumentList:c},u).then(TU)},construct(n,s){vU(i);const[o,a]=RU(s);return _U(e,t,{type:"CONSTRUCT",path:r.map((e=>e.toString())),argumentList:o},a).then(TU)}});return function(e,t){const r=(AU.get(t)||0)+1;AU.set(t,r),SU&&SU.register(e,t,e)}(s,e),s}function RU(e){const t=e.map(PU);return[t.map((e=>e[0])),(r=t.map((e=>e[1])),Array.prototype.concat.apply([],r))];var r}const CU=new WeakMap;function IU(e){return Object.assign(e,{[lU]:!0})}function PU(e){for(const[t,r]of mU)if(r.canHandle(e)){const[n,i]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},i]}return[{type:"RAW",value:e},CU.get(e)||[]]}function TU(e){switch(e.type){case"HANDLER":return mU.get(e.name).deserialize(e.value);case"RAW":return e.value}}function _U(e,t,r,n){return new Promise((i=>{const s=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");t.set(s,i),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)}))}var NU,MU;var xU,OU,DU,BU,LU="1.0.35";var FU=function(){if(BU)return DU;var e;if(BU=1,"object"==typeof globalThis)e=globalThis;else try{e=function(){if(MU)return NU;MU=1;var e=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};return NU=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(t){return e()}try{return __global__||e()}finally{delete Object.prototype.__global__}}()}()}catch(e){}finally{if(e||"undefined"==typeof window||(e=window),!e)throw new Error("Could not determine global this")}var t=e.WebSocket||e.MozWebSocket,r=OU?xU:(OU=1,xU=LU);function n(e,r){return r?new t(e,r):new t(e)}return t&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(n,e,{get:function(){return t[e]}})})),DU={w3cwebsocket:t?n:null,version:r}}();var UU,jU,qU,zU,KU,GU,VU,HU;function $U(){if(jU)return UU;jU=1;var e=BE();return UU=function(t,r){var n=-1,i=t.length,s=i-1;for(r=void 0===r?i:r;++n<r;){var o=e(n,s),a=t[o];t[o]=t[n],t[n]=a}return t.length=r,t},UU}var WU=function(){if(HU)return VU;HU=1;var e=function(){if(zU)return qU;zU=1;var e=Th(),t=$U();return qU=function(r){return t(e(r))},qU}(),t=function(){if(GU)return KU;GU=1;var e=$U(),t=nA();return KU=function(r){return e(t(r))}}(),r=qu();return VU=function(n){return(r(n)?e:t)(n)}}(),JU=n(WU),QU=function(e,t){return QU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},QU(e,t)};function ZU(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}QU(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}"function"==typeof SuppressedError&&SuppressedError;var YU=function(){function e(e,t,r){void 0===r&&(r=1),this.t=void 0,this.i=void 0,this.h=void 0,this.u=e,this.o=t,this.l=r}return e.prototype.v=function(){var e=this,t=e.h.h===e;if(t&&1===e.l)e=e.i;else if(e.t)for(e=e.t;e.i;)e=e.i;else{if(t)return e.h;for(var r=e.h;r.t===e;)r=(e=r).h;e=r}return e},e.prototype.p=function(){var e=this;if(e.i){for(e=e.i;e.t;)e=e.t;return e}for(var t=e.h;t.i===e;)t=(e=t).h;return e.i!==t?t:e},e.prototype.T=function(){var e=this.h,t=this.i,r=t.t;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.t=this,this.h=t,this.i=r,r&&(r.h=this),t},e.prototype.I=function(){var e=this.h,t=this.t,r=t.i;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.i=this,this.h=t,this.t=r,r&&(r.h=this),t},e}(),XU=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.O=1,t}return ZU(t,e),t.prototype.T=function(){var t=e.prototype.T.call(this);return this.M(),t.M(),t},t.prototype.I=function(){var t=e.prototype.I.call(this);return this.M(),t.M(),t},t.prototype.M=function(){this.O=1,this.t&&(this.O+=this.t.O),this.i&&(this.O+=this.i.O)},t}(YU),ej=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.C===e.C},e}(),tj=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ZU(t,e),t}(function(){function e(){this._=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this._},e.prototype.empty=function(){return 0===this._},e}());function rj(){throw new RangeError("Iterator access denied!")}var nj,ij,sj=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.N=void 0,n.g=t,n.enableIndex=r,n.S=r?XU:YU,n.A=new n.S,n}return ZU(t,e),t.prototype.m=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)e=e.i;else{if(!(n>0))return e;r=e,e=e.t}}return r},t.prototype.B=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<=0?e=e.i:(r=e,e=e.t)}return r},t.prototype.j=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)r=e,e=e.i;else{if(!(n>0))return e;e=e.t}}return r},t.prototype.k=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<0?(r=e,e=e.i):e=e.t}return r},t.prototype.R=function(e){for(;;){var t,r=e.h;if(r===this.A)return;if(1===e.l)return void(e.l=0);if(e===r.t)if(1===(t=r.i).l)t.l=0,r.l=1,r===this.N?this.N=r.T():r.T();else{if(t.i&&1===t.i.l)return t.l=r.l,r.l=0,t.i.l=0,void(r===this.N?this.N=r.T():r.T());t.t&&1===t.t.l?(t.l=1,t.t.l=0,t.I()):(t.l=1,e=r)}else if(1===(t=r.t).l)t.l=0,r.l=1,r===this.N?this.N=r.I():r.I();else{if(t.t&&1===t.t.l)return t.l=r.l,r.l=0,t.t.l=0,void(r===this.N?this.N=r.I():r.I());t.i&&1===t.i.l?(t.l=1,t.i.l=0,t.T()):(t.l=1,e=r)}}},t.prototype.G=function(e){if(1!==this._){for(var t=e;t.t||t.i;){if(t.i)for(t=t.i;t.t;)t=t.t;else t=t.t;var r=e.u;e.u=t.u,t.u=r;var n=e.o;e.o=t.o,t.o=n,e=t}this.A.t===t?this.A.t=t.h:this.A.i===t&&(this.A.i=t.h),this.R(t);var i=t.h;if(t===i.t?i.t=void 0:i.i=void 0,this._-=1,this.N.l=0,this.enableIndex)for(;i!==this.A;)i.O-=1,i=i.h}else this.clear()},t.prototype.P=function(e){for(var t="number"==typeof e?e:void 0,r="function"==typeof e?e:void 0,n=void 0===e?[]:void 0,i=0,s=this.N,o=[];o.length||s;)if(s)o.push(s),s=s.t;else{if(s=o.pop(),i===t)return s;n&&n.push(s),r&&r(s,i,this),i+=1,s=s.i}return n},t.prototype.q=function(e){for(;;){var t=e.h;if(0===t.l)return;var r=t.h;if(t===r.t){if((n=r.i)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.i)return t.l=0,r===this.N?this.N=r.I():r.I(),void(r.l=1);e.l=0,e.t&&(e.t.h=t),e.i&&(e.i.h=r),t.i=e.t,r.t=e.i,e.t=t,e.i=r,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}else{var n,i;if((n=r.t)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.t)return t.l=0,r===this.N?this.N=r.T():r.T(),void(r.l=1);e.l=0,e.t&&(e.t.h=r),e.i&&(e.i.h=t),r.i=e.t,t.t=e.i,e.t=r,e.i=t,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}return void(this.enableIndex&&(t.M(),r.M(),e.M()))}},t.prototype.D=function(e,t,r){if(void 0===this.N)return this._+=1,this.N=new this.S(e,t,0),this.N.h=this.A,this.A.h=this.A.t=this.A.i=this.N,this._;var n,i=this.A.t,s=this.g(i.u,e);if(0===s)return i.o=t,this._;if(s>0)i.t=new this.S(e,t),i.t.h=i,n=i.t,this.A.t=n;else{var o=this.A.i,a=this.g(o.u,e);if(0===a)return o.o=t,this._;if(a<0)o.i=new this.S(e,t),o.i.h=o,n=o.i,this.A.i=n;else{if(void 0!==r){var c=r.C;if(c!==this.A){var u=this.g(c.u,e);if(0===u)return c.o=t,this._;if(u>0){var l=c.v(),h=this.g(l.u,e);if(0===h)return l.o=t,this._;h<0&&(n=new this.S(e,t),void 0===l.i?(l.i=n,n.h=l):(c.t=n,n.h=c))}}}if(void 0===n)for(n=this.N;;){var d=this.g(n.u,e);if(d>0){if(void 0===n.t){n.t=new this.S(e,t),n.t.h=n,n=n.t;break}n=n.t}else{if(!(d<0))return n.o=t,this._;if(void 0===n.i){n.i=new this.S(e,t),n.i.h=n,n=n.i;break}n=n.i}}}}if(this.enableIndex)for(var f=n.h;f!==this.A;)f.O+=1,f=f.h;return this.q(n),this._+=1,this._},t.prototype.F=function(e,t){for(;e;){var r=this.g(e.u,t);if(r<0)e=e.i;else{if(!(r>0))return e;e=e.t}}return e||this.A},t.prototype.clear=function(){this._=0,this.N=void 0,this.A.h=void 0,this.A.t=this.A.i=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.C;if(r===this.A&&rj(),1===this._)return r.u=t,!0;var n=r.p().u;if(r===this.A.t)return this.g(n,t)>0&&(r.u=t,!0);var i=r.v().u;return r===this.A.i?this.g(i,t)<0&&(r.u=t,!0):!(this.g(i,t)>=0||this.g(n,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return this.G(t),this._},t.prototype.eraseElementByKey=function(e){if(0===this._)return!1;var t=this.F(this.N,e);return t!==this.A&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.C;t===this.A&&rj();var r=void 0===t.i;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.t||e.next(),this.G(t),e},t.prototype.getHeight=function(){if(0===this._)return 0;return function e(t){return t?Math.max(e(t.t),e(t.i))+1:0}(this.N)},t}(tj),oj=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.C=t,i.A=r,0===i.iteratorType?(i.pre=function(){return this.C===this.A.t&&rj(),this.C=this.C.v(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.p(),this}):(i.pre=function(){return this.C===this.A.i&&rj(),this.C=this.C.p(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.v(),this}),i}return ZU(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.C,t=this.A.h;if(e===this.A)return t?t.O-1:0;var r=0;for(e.t&&(r+=e.t.O);e!==t;){var n=e.h;e===n.i&&(r+=1,n.t&&(r+=n.t.O)),e=n}return r},enumerable:!1,configurable:!0}),t.prototype.isAccessible=function(){return this.C!==this.A},t}(ej),aj=function(e){function t(t,r,n,i){var s=e.call(this,t,r,i)||this;return s.container=n,s}return ZU(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){this.C===this.A&&rj();var e=this;return new Proxy([],{get:function(t,r){return"0"===r?e.C.u:"1"===r?e.C.o:(t[0]=e.C.u,t[1]=e.C.o,t[r])},set:function(t,r,n){if("1"!==r)throw new TypeError("prop must be 1");return e.C.o=n,!0}})},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.C,this.A,this.container,this.iteratorType)},t}(oj),cj=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,s=i;return t.forEach((function(e){s.setElement(e[0],e[1])})),i}return ZU(t,e),t.prototype.begin=function(){return new aj(this.A.t||this.A,this.A,this)},t.prototype.end=function(){return new aj(this.A,this.A,this)},t.prototype.rBegin=function(){return new aj(this.A.i||this.A,this.A,this,1)},t.prototype.rEnd=function(){return new aj(this.A,this.A,this,1)},t.prototype.front=function(){if(0!==this._){var e=this.A.t;return[e.u,e.o]}},t.prototype.back=function(){if(0!==this._){var e=this.A.i;return[e.u,e.o]}},t.prototype.lowerBound=function(e){var t=this.m(this.N,e);return new aj(t,this.A,this)},t.prototype.upperBound=function(e){var t=this.B(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseLowerBound=function(e){var t=this.j(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseUpperBound=function(e){var t=this.k(this.N,e);return new aj(t,this.A,this)},t.prototype.forEach=function(e){this.P((function(t,r,n){e([t.u,t.o],r,n)}))},t.prototype.setElement=function(e,t,r){return this.D(e,t,r)},t.prototype.getElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return[t.u,t.o]},t.prototype.find=function(e){var t=this.F(this.N,e);return new aj(t,this.A,this)},t.prototype.getElementByKey=function(e){return this.F(this.N,e).o},t.prototype.union=function(e){var t=this;return e.forEach((function(e){t.setElement(e[0],e[1])})),this._},t.prototype[Symbol.iterator]=function(){var e,t,r,n;return function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}}(this,(function(i){switch(i.label){case 0:e=this._,t=this.P(),r=0,i.label=1;case 1:return r<e?[4,[(n=t[r]).u,n.o]]:[3,4];case 2:i.sent(),i.label=3;case 3:return++r,[3,1];case 4:return[2]}}))},t}(sj);function uj(){if(ij)return nj;return ij=1,nj=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0},nj}var lj,hj,dj,fj,pj,gj,mj,yj,bj=n(uj());function wj(){if(fj)return dj;fj=1;var e=Jc(),t=Hc(),r=(hj||(hj=1,lj=function(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}),lj),n=Qc(),i=Th(),s=Array.prototype.splice;return dj=function(o,a,c,u){var l=u?r:t,h=-1,d=a.length,f=o;for(o===a&&(a=i(a)),c&&(f=e(o,n(c)));++h<d;)for(var p=0,g=a[h],m=c?c(g):g;(p=l(f,m,p,u))>-1;)f!==o&&s.call(f,p,1),s.call(o,p,1);return o},dj}var vj=function(){if(yj)return mj;yj=1;var e=nu(),t=function(){if(gj)return pj;gj=1;var e=wj();return pj=function(t,r){return t&&t.length&&r&&r.length?e(t,r):t},pj}(),r=e(t);return mj=r}(),Ej=n(vj);const Aj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,Sj=new Set,kj="object"==typeof process&&process?process:{},Rj=(e,t,r,n)=>{"function"==typeof kj.emitWarning?kj.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let Cj=globalThis.AbortController,Ij=globalThis.AbortSignal;if(void 0===Cj){Ij=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Cj=class{constructor(){t()}signal=new Ij;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==kj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,Rj("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const Pj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Tj=e=>Pj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?_j:null:null;class _j extends Array{constructor(e){super(e),this.fill(0)}}class Nj{heap;length;static#Lt=!1;static create(e){const t=Tj(e);if(!t)return[];Nj.#Lt=!0;const r=new Nj(e,t);return Nj.#Lt=!1,r}constructor(e,t){if(!Nj.#Lt)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Mj{#Ft;#Ut;#jt;#qt;#zt;#Kt;#Gt;#Vt;get perf(){return this.#Vt}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Ht;#$t;#Wt;#Jt;#Qt;#Zt;#Yt;#Xt;#er;#tr;#rr;#nr;#ir;#sr;#or;#ar;#cr;#ur;static unsafeExposeInternals(e){return{starts:e.#ir,ttls:e.#sr,sizes:e.#nr,keyMap:e.#Wt,keyList:e.#Jt,valList:e.#Qt,next:e.#Zt,prev:e.#Yt,get head(){return e.#Xt},get tail(){return e.#er},free:e.#tr,isBackgroundFetch:t=>e.#lr(t),backgroundFetch:(t,r,n,i)=>e.#hr(t,r,n,i),moveToTail:t=>e.#dr(t),indexes:t=>e.#fr(t),rindexes:t=>e.#pr(t),isStale:t=>e.#gr(t)}}get max(){return this.#Ft}get maxSize(){return this.#Ut}get calculatedSize(){return this.#$t}get size(){return this.#Ht}get fetchMethod(){return this.#Kt}get memoMethod(){return this.#Gt}get dispose(){return this.#jt}get onInsert(){return this.#qt}get disposeAfter(){return this.#zt}constructor(e){const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:o,allowStale:a,dispose:c,onInsert:u,disposeAfter:l,noDisposeOnSet:h,noUpdateTTL:d,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:g,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:A,perf:S}=e;if(void 0!==S&&"function"!=typeof S?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#Vt=S??Aj,0!==t&&!Pj(t))throw new TypeError("max option must be a nonnegative integer");const k=t?Tj(t):Array;if(!k)throw new Error("invalid max value: "+t);if(this.#Ft=t,this.#Ut=f,this.maxEntrySize=p||this.#Ut,this.sizeCalculation=g,this.sizeCalculation){if(!this.#Ut&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==y&&"function"!=typeof y)throw new TypeError("memoMethod must be a function if defined");if(this.#Gt=y,void 0!==m&&"function"!=typeof m)throw new TypeError("fetchMethod must be a function if specified");if(this.#Kt=m,this.#ar=!!m,this.#Wt=new Map,this.#Jt=new Array(t).fill(void 0),this.#Qt=new Array(t).fill(void 0),this.#Zt=new k(t),this.#Yt=new k(t),this.#Xt=0,this.#er=0,this.#tr=Nj.create(t),this.#Ht=0,this.#$t=0,"function"==typeof c&&(this.#jt=c),"function"==typeof u&&(this.#qt=u),"function"==typeof l?(this.#zt=l,this.#rr=[]):(this.#zt=void 0,this.#rr=void 0),this.#or=!!this.#jt,this.#ur=!!this.#qt,this.#cr=!!this.#zt,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#Ut&&!Pj(this.#Ut))throw new TypeError("maxSize must be a positive integer if specified");if(!Pj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#mr()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!o,this.ttlResolution=Pj(n)||0===n?n:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Pj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#yr()}if(0===this.#Ft&&0===this.ttl&&0===this.#Ut)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Ft&&!this.#Ut){const e="LRU_CACHE_UNBOUNDED";if((e=>!Sj.has(e))(e)){Sj.add(e);Rj("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,Mj)}}}getRemainingTTL(e){return this.#Wt.has(e)?1/0:0}#yr(){const e=new _j(this.#Ft),t=new _j(this.#Ft);this.#sr=e,this.#ir=t,this.#br=(r,n,i=this.#Vt.now())=>{if(t[r]=0!==n?i:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{this.#gr(r)&&this.#wr(this.#Jt[r],"expire")}),n+1);e.unref&&e.unref()}},this.#vr=r=>{t[r]=0!==e[r]?this.#Vt.now():0},this.#Er=(i,s)=>{if(e[s]){const o=e[s],a=t[s];if(!o||!a)return;i.ttl=o,i.start=a,i.now=r||n();const c=i.now-a;i.remainingTTL=o-c}};let r=0;const n=()=>{const e=this.#Vt.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const s=this.#Wt.get(i);if(void 0===s)return 0;const o=e[s],a=t[s];if(!o||!a)return 1/0;return o-((r||n())-a)},this.#gr=i=>{const s=t[i],o=e[i];return!!o&&!!s&&(r||n())-s>o}}#vr=()=>{};#Er=()=>{};#br=()=>{};#gr=()=>!1;#mr(){const e=new _j(this.#Ft);this.#$t=0,this.#nr=e,this.#Ar=t=>{this.#$t-=e[t],e[t]=0},this.#Sr=(e,t,r,n)=>{if(this.#lr(t))return 0;if(!Pj(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!Pj(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#kr=(t,r,n)=>{if(e[t]=r,this.#Ut){const r=this.#Ut-e[t];for(;this.#$t>r;)this.#Rr(!0)}this.#$t+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#$t)}}#Ar=e=>{};#kr=(e,t,r)=>{};#Sr=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#fr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#er;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#Xt);)t=this.#Yt[t]}*#pr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#Xt;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#er);)t=this.#Zt[t]}#Cr(e){return void 0!==e&&this.#Wt.get(this.#Jt[e])===e}*entries(){for(const e of this.#fr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*rentries(){for(const e of this.#pr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*keys(){for(const e of this.#fr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*rkeys(){for(const e of this.#pr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*values(){for(const e of this.#fr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}*rvalues(){for(const e of this.#pr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#Jt[r],this))return this.get(this.#Jt[r],t)}}forEach(e,t=this){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}rforEach(e,t=this){for(const r of this.#pr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}purgeStale(){let e=!1;for(const t of this.#pr({allowStale:!0}))this.#gr(t)&&(this.#wr(this.#Jt[t],"expire"),e=!0);return e}info(e){const t=this.#Wt.get(e);if(void 0===t)return;const r=this.#Qt[t],n=this.#lr(r)?r.__staleWhileFetching:r;if(void 0===n)return;const i={value:n};if(this.#sr&&this.#ir){const e=this.#sr[t],r=this.#ir[t];if(e&&r){const t=e-(this.#Vt.now()-r);i.ttl=t,i.start=Date.now()}}return this.#nr&&(i.size=this.#nr[t]),i}dump(){const e=[];for(const t of this.#fr({allowStale:!0})){const r=this.#Jt[t],n=this.#Qt[t],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0===i||void 0===r)continue;const s={value:i};if(this.#sr&&this.#ir){s.ttl=this.#sr[t];const e=this.#Vt.now()-this.#ir[t];s.start=Math.floor(Date.now()-e)}this.#nr&&(s.size=this.#nr[t]),e.unshift([r,s])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#Vt.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const u=this.#Sr(e,t,r.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#wr(e,"set"),this;let l=0===this.#Ht?void 0:this.#Wt.get(e);if(void 0===l)l=0===this.#Ht?this.#er:0!==this.#tr.length?this.#tr.pop():this.#Ht===this.#Ft?this.#Rr(!1):this.#Ht,this.#Jt[l]=e,this.#Qt[l]=t,this.#Wt.set(e,l),this.#Zt[this.#er]=l,this.#Yt[l]=this.#er,this.#er=l,this.#Ht++,this.#kr(l,u,a),a&&(a.set="add"),c=!1,this.#ur&&this.#qt?.(t,e,"add");else{this.#dr(l);const r=this.#Qt[l];if(t!==r){if(this.#ar&&this.#lr(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||s||(this.#or&&this.#jt?.(t,e,"set"),this.#cr&&this.#rr?.push([t,e,"set"]))}else s||(this.#or&&this.#jt?.(r,e,"set"),this.#cr&&this.#rr?.push([r,e,"set"]));if(this.#Ar(l),this.#kr(l,u,a),this.#Qt[l]=t,a){a.set="replace";const e=r&&this.#lr(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#ur&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#sr||this.#yr(),this.#sr&&(c||this.#br(l,n,i),a&&this.#Er(a,l)),!s&&this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return this}pop(){try{for(;this.#Ht;){const e=this.#Qt[this.#Xt];if(this.#Rr(!0),this.#lr(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}#Rr(e){const t=this.#Xt,r=this.#Jt[t],n=this.#Qt[t];return this.#ar&&this.#lr(n)?n.__abortController.abort(new Error("evicted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(n,r,"evict"),this.#cr&&this.#rr?.push([n,r,"evict"])),this.#Ar(t),e&&(this.#Jt[t]=void 0,this.#Qt[t]=void 0,this.#tr.push(t)),1===this.#Ht?(this.#Xt=this.#er=0,this.#tr.length=0):this.#Xt=this.#Zt[t],this.#Wt.delete(r),this.#Ht--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#Wt.get(e);if(void 0!==i){const e=this.#Qt[i];if(this.#lr(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#gr(i))return r&&this.#vr(i),n&&(n.has="hit",this.#Er(n,i)),!0;n&&(n.has="stale",this.#Er(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#Wt.get(e);if(void 0===n||!r&&this.#gr(n))return;const i=this.#Qt[n];return this.#lr(i)?i.__staleWhileFetching:i}#hr(e,t,r,n){const i=void 0===t?void 0:this.#Qt[t];if(this.#lr(i))return i;const s=new Cj,{signal:o}=r;o?.addEventListener("abort",(()=>s.abort(o.reason)),{signal:s.signal});const a={signal:s.signal,options:r,context:n},c=(n,i=!1)=>{const{aborted:o}=s.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(o&&!i?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),o&&!c&&!i)return u(s.signal.reason);const h=l,d=this.#Qt[t];return(d===l||c&&i&&void 0===d)&&(void 0===n?void 0!==h.__staleWhileFetching?this.#Qt[t]=h.__staleWhileFetching:this.#wr(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,a.options))),n},u=n=>{const{aborted:i}=s.signal,o=i&&r.allowStaleOnFetchAbort,a=o||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,u=l;if(this.#Qt[t]===l){!c||void 0===u.__staleWhileFetching?this.#wr(e,"fetch"):o||(this.#Qt[t]=u.__staleWhileFetching)}if(a)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const l=new Promise(((t,n)=>{const o=this.#Kt?.(e,i,a);o&&o instanceof Promise&&o.then((e=>t(void 0===e?void 0:e)),n),s.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),h=Object.assign(l,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...a.options,status:void 0}),t=this.#Wt.get(e)):this.#Qt[t]=h,h}#lr(e){if(!this.#ar)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Cj}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:p,forceRefresh:g=!1,status:m,signal:y}=t;if(!this.#ar)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const b={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:d,status:m,signal:y};let w=this.#Wt.get(e);if(void 0===w){m&&(m.fetch="miss");const t=this.#hr(e,w,b,p);return t.__returned=t}{const t=this.#Qt[w];if(this.#lr(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#gr(w);if(!g&&!i)return m&&(m.fetch="hit"),this.#dr(w),n&&this.#vr(w),m&&this.#Er(m,w),t;const s=this.#hr(e,w,b,p),o=void 0!==s.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",o&&i&&(m.returnedStale=!0)),o?s.__staleWhileFetching:s.__returned=s}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#Gt;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...s}=t,o=this.get(e,s);if(!i&&void 0!==o)return o;const a=r(e,o,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,o=this.#Wt.get(e);if(void 0!==o){const t=this.#Qt[o],a=this.#lr(t);return s&&this.#Er(s,o),this.#gr(o)?(s&&(s.get="stale"),a?(s&&r&&void 0!==t.__staleWhileFetching&&(s.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#wr(e,"expire"),s&&r&&(s.returnedStale=!0),r?t:void 0)):(s&&(s.get="hit"),a?t.__staleWhileFetching:(this.#dr(o),n&&this.#vr(o),t))}s&&(s.get="miss")}#Et(e,t){this.#Yt[t]=e,this.#Zt[e]=t}#dr(e){e!==this.#er&&(e===this.#Xt?this.#Xt=this.#Zt[e]:this.#Et(this.#Yt[e],this.#Zt[e]),this.#Et(this.#er,e),this.#er=e)}delete(e){return this.#wr(e,"delete")}#wr(e,t){let r=!1;if(0!==this.#Ht){const n=this.#Wt.get(e);if(void 0!==n)if(r=!0,1===this.#Ht)this.#Ir(t);else{this.#Ar(n);const r=this.#Qt[n];if(this.#lr(r)?r.__abortController.abort(new Error("deleted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(r,e,t),this.#cr&&this.#rr?.push([r,e,t])),this.#Wt.delete(e),this.#Jt[n]=void 0,this.#Qt[n]=void 0,n===this.#er)this.#er=this.#Yt[n];else if(n===this.#Xt)this.#Xt=this.#Zt[n];else{const e=this.#Yt[n];this.#Zt[e]=this.#Zt[n];const t=this.#Zt[n];this.#Yt[t]=this.#Yt[n]}this.#Ht--,this.#tr.push(n)}}if(this.#cr&&this.#rr?.length){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return r}clear(){return this.#Ir("delete")}#Ir(e){for(const t of this.#pr({allowStale:!0})){const r=this.#Qt[t];if(this.#lr(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#Jt[t];this.#or&&this.#jt?.(r,n,e),this.#cr&&this.#rr?.push([r,n,e])}}if(this.#Wt.clear(),this.#Qt.fill(void 0),this.#Jt.fill(void 0),this.#sr&&this.#ir&&(this.#sr.fill(0),this.#ir.fill(0)),this.#nr&&this.#nr.fill(0),this.#Xt=0,this.#er=0,this.#tr.length=0,this.#$t=0,this.#Ht=0,this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}var xj,Oj={exports:{}};var Dj=(xj||(xj=1,function(e){var t,r,n,i=(t={km:6371,mile:3960,meter:6371e3,nmi:3440},r=function(e){return e*Math.PI/180},n=function(e,t){switch(e){case"[lat,lon]":return{latitude:t[0],longitude:t[1]};case"[lon,lat]":return{latitude:t[1],longitude:t[0]};case"{lon,lat}":return{latitude:t.lat,longitude:t.lon};case"{lat,lng}":return{latitude:t.lat,longitude:t.lng};case"geojson":return{latitude:t.geometry.coordinates[1],longitude:t.geometry.coordinates[0]};default:return t}},function(e,i,s){var o=(s=s||{}).unit in t?t[s.unit]:t.km,a=n(s.format,e),c=n(s.format,i),u=r(c.latitude-a.latitude),l=r(c.longitude-a.longitude),h=r(a.latitude),d=r(c.latitude),f=Math.sin(u/2)*Math.sin(u/2)+Math.sin(l/2)*Math.sin(l/2)*Math.cos(h)*Math.cos(d),p=2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f));return s.threshold?s.threshold>o*p:o*p});e.exports&&(e.exports=i)}(Oj)),Oj.exports),Bj=n(Dj);const Lj={JFK:[100,40.639447,-73.779317],LGA:[200,40.777199,-73.872597],EWR:[300,40.692501,-74.168701],BUF:[400,42.94049835,-78.73220062],BFI:[500,47.529999,-122.302002],SEA:[600,47.449162,-122.311134],PDX:[700,45.58869934,-122.5979996],HIO:[800,45.540401,-122.949997],SMF:[900,38.69540023803711,-121.59100341796875],SFO:[1e3,37.61899948120117,-122.375],PAO:[1100,37.461101532,-122.114997864],SJC:[1200,37.362452,-121.929188],WVI:[1300,36.9356994629,-121.790000916],BUR:[1400,34.197703,-118.356378],LAX:[1500,33.942501,-118.407997],SAN:[1600,32.7336006165,-117.190002441],LAS:[1700,36.083361,-115.151817],PHX:[1800,33.435302,-112.005905],ABQ:[1900,35.040199,-106.609001],DEN:[2e3,39.861698150635,-104.672996521],SLC:[2100,40.785749,-111.979746],STP:[2200,44.93479,-93.060036],MSP:[2300,44.882,-93.221802],FSD:[2400,43.585463,-96.741152],OMA:[2500,41.3032,-95.894096],MCI:[2600,39.2976,-94.713898],OKC:[2700,35.393101,-97.6007],ADS:[2800,32.9686012268,-96.8364028931],DFW:[2900,32.896801,-97.038002],IAH:[3e3,29.984399795532227,-95.34140014648438],AUS:[3100,30.197535,-97.662015],SAT:[3200,29.533701,-98.469803],MFE:[3300,26.176141,-98.237965],HNL:[3400,21.32062,-157.924228],ANC:[3500,61.1744,-149.996002],BOS:[3600,42.3643,-71.005203],BGR:[3700,44.8074,-68.828102],YTO:[3800,43.6772,-79.6306],YYZ:[3900,43.6772,-79.6306],YOW:[4e3,45.322498,-75.669197],YUL:[4100,45.4706,-73.740799],YHZ:[4200,44.8807983398,-63.5085983276],YVR:[4300,49.193901062,-123.183998108],YYC:[4400,51.113899231,-114.019996643],YXE:[4500,52.170799255371094,-106.69999694824219],YWG:[4600,49.909999847399995,-97.2398986816],KEF:[4700,63.985001,-22.6056],DUB:[4800,53.428713,-6.262121],ORK:[4900,51.841301,-8.49111],MAN:[5e3,53.349375,-2.279521],LHR:[5100,51.4706,-.461941],LON:[5200,51.4706,-.461941],LCY:[5300,51.505299,.055278],EDI:[5400,55.950145,-3.372288],BRU:[5500,50.901402,4.48444],AMS:[5600,52.308601,4.76389],DUS:[5700,51.289501,6.76678],FRA:[5800,50.036521,8.561268],WIE:[5900,50.049800872802734,8.325400352478027],STR:[6e3,48.689899,9.22196],MUC:[6100,48.353802,11.7861],TXL:[6200,52.362247,13.500672],HAM:[6300,53.630402,9.98823],LUX:[6400,49.6233333,6.2044444],DLP:[6500,49.012798,2.55],CDG:[6600,49.012798,2.55],PAR:[6700,49.012798,2.55],BOD:[6800,44.8283,-.715556],MRS:[6900,43.438088,5.2125],LYS:[7e3,45.725556,5.081111],GVA:[7100,46.238098,6.10895],ZRH:[7200,47.458056,8.548056],MXP:[7300,45.6306,8.72811],LIN:[7400,45.445099,9.27674],FCO:[7500,41.804532,12.251998],PMO:[7600,38.175999,13.091],PRG:[7700,50.103514,14.256992],CPH:[7800,55.617900848389,12.656000137329],OSL:[7900,60.193901,11.1004],ARN:[8e3,59.651901245117,17.918600082397],BMA:[8100,59.354400634765625,17.941699981689453],GOT:[8200,57.662799835205,12.279800415039],RIX:[8300,56.923599,23.9711],TLL:[8400,59.41329956049999,24.832799911499997],HEL:[8500,60.3172,24.963301],LED:[8600,59.80030059814453,30.262500762939453],KLD:[8700,56.82469940185547,35.7577018737793],DME:[8800,55.40879821777344,37.90629959106445],SVX:[8900,56.743099212646,60.802700042725],KJA:[9e3,56.173077,92.492437],KHV:[9100,48.528338,135.188588],MSQ:[9200,53.888071,28.039964],VNO:[9300,54.634102,25.285801],WAW:[9400,52.1656990051,20.967100143399996],KBP:[9500,50.345001,30.894699],KIV:[9600,46.9277,28.931],OTP:[9700,44.572127,26.103396],IST:[9800,41.261297,28.741951],ADB:[9900,38.2924,27.157],ATH:[1e4,37.936401,23.9445],SKG:[10100,40.51928,22.970009],SOF:[10200,42.696357,23.417671],TIA:[10300,41.4147,19.7206],BEG:[10400,44.818401,20.309099],BUD:[10500,47.43018,19.262393],BTS:[10600,48.1702,17.2127],VIE:[10700,48.110298,16.5697],ZAG:[10800,45.742901,16.0688],TUN:[10900,36.851002,10.2272],AAE:[11e3,36.826781,7.81334],ALG:[11100,36.693886,3.214531],ORN:[11200,35.623901,-.621183],MAD:[11300,40.471926,-3.56264],BCN:[11400,41.2971,2.07846],LIS:[11500,38.7813,-9.13592],CMN:[11600,33.3675,-7.58997],DKR:[11700,14.7397,-17.4902],OUA:[11800,12.3532,-1.51242],ACC:[11900,5.605189800262451,-.16678600013256073],LOS:[12e3,6.5773701667785645,3.321160078048706],FIH:[12100,-4.38575,15.4446],LAD:[12200,-8.85837,13.2312],CPT:[12300,-33.9648017883,18.6016998291],DUR:[12400,-29.6144444444,31.1197222222],JNB:[12500,-26.1392,28.246],MPM:[12600,-25.920799,32.572601],GBE:[12700,-24.555201,25.9182],HRE:[12800,-17.931801,31.0928],TNR:[12900,-18.7969,47.478802],RUN:[13e3,-20.890087,55.518894],MRU:[13100,-20.430201,57.683601],DAR:[13200,-6.87811,39.202599],MBA:[13300,-4.03483,39.5942],NBO:[13400,-1.31923997402,36.9277992249],KGL:[13500,-1.96863,30.1395],JIB:[13600,11.5473,43.1595],CAI:[13700,30.111534,31.396694],TLV:[13800,32.011398,34.8867],HFA:[13900,32.80939865112305,35.04309844970703],ZDM:[14e3,31.91123,35.20756],AMM:[14100,31.7226009369,35.9931983948],BEY:[14200,33.820899963378906,35.488399505615234],LCA:[14300,34.875099,33.624901],EVN:[14400,40.1473007202,44.3959007263],TBS:[14500,41.669201,44.9547],GYD:[14600,40.467498779296875,50.04669952392578],LLK:[14700,38.757919,48.807042],EBL:[14800,36.23759841918945,43.963199615478516],ISU:[14900,35.5617485046,45.316738128699996],BGW:[15e3,33.262501,44.2346],NJF:[15100,31.989853,44.404317],XNH:[15200,30.935801,46.090099],BSR:[15300,30.549101,47.662102],KWI:[15400,29.226601,47.968899],RUH:[15500,24.9576,46.698799],DMM:[15600,26.471200942993164,49.79790115356445],JED:[15700,21.6796,39.156502],BAH:[15800,26.267295,50.63764],DOH:[15900,25.273056,51.608056],DXB:[16e3,25.2527999878,55.3643989563],FJR:[16100,25.1122,56.324001],MCT:[16200,23.593299865722656,58.284400939941406],MLE:[16300,4.191830158233643,73.52909851074219],CMB:[16400,7.180759906768799,79.88410186767578],MAA:[16500,12.990005,80.169296],BLR:[16600,13.1979,77.706299],HYD:[16700,17.231318,78.429855],NAG:[16800,21.092199,79.047203],BBI:[16900,20.244400024399997,85.8178024292],CCU:[17e3,22.654699325561523,88.44670104980469],AMD:[17100,23.0772,72.634697],BOM:[17200,19.0886993408,72.8678970337],PNQ:[17300,18.5821,73.919701],CNN:[17400,11.918614,75.547211],COK:[17500,10.152,76.401901],PAT:[17600,25.591299,85.087997],KNU:[17700,26.404301,80.410103],DEL:[17800,28.55563,77.09519],IXC:[17900,30.6735,76.788498],JSR:[18e3,23.1838,89.160797],CGP:[18100,22.249599,91.813301],DAC:[18200,23.843347,90.397783],PBH:[18300,27.4032,89.424599],KTM:[18400,27.6966,85.3591],LHE:[18500,31.521601,74.403603],ISB:[18600,33.549,72.82566],KHI:[18700,24.9065,67.160797],TAS:[18800,41.257900238,69.2811965942],ALA:[18900,43.354267,77.042828],ULN:[19e3,47.843102,106.766998],ICN:[19100,37.46910095214844,126.45099639892578],TYO:[19200,35.764702,140.386002],NRT:[19300,35.764702,140.386002],HND:[19400,35.552299,139.779999],ITM:[19500,34.785499572753906,135.43800354003906],KIX:[19600,34.427299,135.244003],FUK:[19700,33.585899353027344,130.4510040283203],OKA:[19800,26.195801,127.646004],GUM:[19900,13.4834,144.796005],CGY:[2e4,8.612203,124.456496],CEB:[20100,10.309261,123.97974],MNL:[20200,14.5086,121.019997],BWN:[20300,4.9442,114.928001],SGN:[20400,10.8188,106.652],HAN:[20500,21.221201,105.806999],PNH:[20600,11.5466,104.844002],VTE:[20700,17.988300323500003,102.56300354],MFM:[20800,22.149599,113.592003],HKG:[20900,22.308901,113.915001],KHH:[21e3,22.577101,120.349998],TPE:[21100,25.0777,121.233002],FOC:[21200,25.934669,119.66318],HYN:[21300,28.562201,121.429001],HGH:[21400,30.23609,120.428865],SHA:[21500,31.198104,121.33426],CZX:[21600,31.919701,119.778999],WHU:[21700,31.3906,118.408997],KHN:[21800,28.864815,115.90271],CGD:[21900,28.9189,111.639999],KWE:[22e3,26.541466,106.803331],KMG:[22100,25.110313,102.936743],LHW:[22200,36.515202,103.620003],ZHY:[22300,37.573125,105.154454],SJW:[22400,38.280701,114.696999],PKX:[22500,39.509945,116.41092],BJS:[22600,40.080101013183594,116.58499908447266],TSN:[22700,39.124401092499994,117.346000671],TNA:[22800,36.857201,117.216003],TAO:[22900,36.361953,120.088171],HAK:[23e3,19.9349,110.459],FUO:[23100,23.0833,113.07],ZGN:[23200,23.392401,113.299004],CAN:[23300,23.392401,113.299004],SZX:[23400,22.639299,113.810997],MDL:[23500,21.702199935913086,95.97789764404297],RGN:[23600,16.907300949099998,96.1332015991],CNX:[23700,18.766799926799997,98.962600708],BKK:[23800,13.681099891662598,100.74700164794922],URT:[23900,9.13259983063,99.135597229],KUL:[24e3,2.74558,101.709999],JHB:[24100,1.64131,103.669998],QPG:[24200,1.36042,103.910004],SIN:[24300,1.35019,103.994003],CGK:[24400,-6.1255698204,106.65599823],JOG:[24500,-7.78818,110.431999],DPS:[24600,-8.74817,115.167],DEX:[24700,-4.8557,139.482006],PER:[24800,-31.94029998779297,115.96700286865234],ADL:[24900,-34.947512,138.533393],MEL:[25e3,-37.673302,144.843002],HBA:[25100,-42.836101532,147.509994507],CBR:[25200,-35.3069,149.195007],SYD:[25300,-33.94609832763672,151.177001953125],BNE:[25400,-27.384199142456055,153.11700439453125],CHC:[25500,-43.48939895629883,172.53199768066406],WLG:[25600,-41.3272018433,174.804992676],AKL:[25700,-37.01199,174.786331],NOU:[25800,-22.014601,166.212997],SUV:[25900,-18.04330062866211,178.5590057373047],PPT:[26e3,-17.553699,-149.606995],GDL:[26100,20.52504,-103.301557],QRO:[26200,20.6173,-100.185997],MEX:[26300,19.435433,-99.082432],GUA:[26400,14.5833,-90.527496],TGU:[26500,14.0609,-87.217201],SJO:[26600,9.99386,-84.208801],PTY:[26700,9.0713596344,-79.3834991455],MDE:[26800,6.16454,-75.4231],BOG:[26900,4.70159,-74.1469],UIO:[27e3,-.125399,-78.354306],GYE:[27100,-2.15742,-79.883598],LIM:[27200,-12.0219,-77.114305],ARI:[27300,-18.348499,-70.338699],SCL:[27400,-33.393001556396484,-70.78579711914062],COR:[27500,-31.323601,-64.208],NQN:[27600,-38.949001,-68.155701],EZE:[27700,-34.8222,-58.5358],ASU:[27800,-25.240156,-57.519227],CGB:[27900,-15.6529,-56.116699],GYN:[28e3,-16.632,-49.220699],BSB:[28100,-15.869167,-47.920834],UDI:[28200,-18.883579,-48.225936],SJP:[28300,-20.817113,-49.406963],RAO:[28400,-21.134314,-47.774053],VCP:[28500,-23.007404,-47.134502],SOD:[28600,-23.478001,-47.490002],GRU:[28700,-23.431944,-46.467778],QWJ:[28800,-23.431944,-46.467778],SJK:[28900,-23.2292,-45.8615],GIG:[29e3,-22.809999,-43.250557],CNF:[29100,-19.63571,-43.966928],CAW:[29200,-21.698299,-41.301701],VIX:[29300,-20.258,-40.285],SSA:[29400,-12.908611,-38.322498],REC:[29500,-8.125984,-34.923316],JDO:[29600,-7.21932,-39.269096],FOR:[29700,-3.775833,-38.532222],BEL:[29800,-1.379279,-48.476207],MAO:[29900,-3.03861,-60.049702],POA:[3e4,-29.994712,-51.166592],FLN:[30100,-27.670279,-48.552502],ITJ:[30200,-26.879431,-48.650979],NVT:[30300,-26.879431,-48.650979],BNU:[30400,-26.831661,-49.093569],JOI:[30500,-26.224501,-48.797401],CWB:[30600,-25.5285,-49.1758],CFC:[30700,-26.787423,-50.939942],XAP:[30800,-27.134199,-52.656601],PBM:[30900,5.45283,-55.187801],GEO:[31e3,6.49855,-58.254101],BGI:[31100,13.0746,-59.4925],GND:[31200,12.0042,-61.786201],CUR:[31300,12.1889,-68.959801],SDQ:[31400,18.42970085144,-69.668899536133],STI:[31500,19.406099319458008,-70.60469818115234],KIN:[31600,17.935699462890625,-76.7874984741211],MIA:[31700,25.79319953918457,-80.29060363769531],TPA:[31800,27.975500106811523,-82.533203125],GNV:[31900,29.6900997162,-82.2717971802],JAX:[32e3,30.49410057067871,-81.68789672851562],TLH:[32100,30.3965,-84.350304],MGM:[32200,32.300598,-86.393997],ATL:[32300,33.6367,-84.428101],PDK:[32400,33.8755989075,-84.3020019531],BNA:[32500,36.1245002746582,-86.6781997680664],MEM:[32600,35.04240036010742,-89.97669982910156],STL:[32700,38.748697,-90.370003],IND:[32800,39.7173,-86.294403],CHI:[32900,41.9786,-87.9048],ORD:[33e3,41.9786,-87.9048],DTW:[33100,42.212398529052734,-83.35340118408203],CLE:[33200,41.411701,-81.8498],PIT:[33300,40.49150085,-80.23290253],CMH:[33400,39.998001,-82.891899],LCK:[33500,39.813801,-82.927803],CLT:[33600,35.2140007019043,-80.94309997558594],RDU:[33700,35.877602,-78.787498],ORF:[33800,36.8946,-76.201202],RIC:[33900,37.50519943237305,-77.3197021484375],IAD:[34e3,38.9445,-77.455803],DCA:[34100,38.8521,-77.037697],PHL:[34200,39.87189865112305,-75.24109649658203],NYC:[34300,40.639447,-73.779317]},Fj=new Bv("fetchAirportCodeFromCdn"),Uj=async(e,t,r)=>(await Xv(fetch(e,{method:"HEAD"}),r)).headers.get(t),jj=async()=>{const e=2e3;try{return await(async(e,t)=>{const r=await Uj(e,"X-Amz-Cf-Pop",t);if(!r||r.length<3)throw new Error("Could not get airport code from Amazon");return r.substring(0,3)})("https://d47ahk2wrqweh.cloudfront.net/cdn-location",e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.fastly.com","X-Served-By",e);if(!t||t.length<3)throw new Error("Could not get airport code from Fastly");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.cloudflare.com","CF-RAY",e);if(!t||t.length<3)throw new Error("Could not get airport code from Cloudflare");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}throw new Error("Could not get airport code from any CDN")},qj=new Bv("getLocalRegion");let zj,Kj;const Gj=async()=>{let e;return e=await(async()=>{let e;try{e=await jj()}catch{return}return e})(),void 0!==e&&Lj[e]?Lj[e][0]:(()=>{const e=Object.keys(Lj),t=e[Math.floor(Math.random()*e.length)],r=Lj[t][0]+99;return qj.warn(`Could not get airport code, using random region: ${r}`),r})()};var Vj,Hj,$j={exports:{}},Wj=$j.exports;function Jj(){return Vj||(Vj=1,function(e){(function(){var t,r,n,i,s,o,a,c,u,l,h,d,f,p,g;n=Math.floor,l=Math.min,r=function(e,t){return e<t?-1:e>t?1:0},u=function(e,t,i,s,o){var a;if(null==i&&(i=0),null==o&&(o=r),i<0)throw new Error("lo must be non-negative");for(null==s&&(s=e.length);i<s;)o(t,e[a=n((i+s)/2)])<0?s=a:i=a+1;return[].splice.apply(e,[i,i-i].concat(t)),t},o=function(e,t,n){return null==n&&(n=r),e.push(t),p(e,0,e.length-1,n)},s=function(e,t){var n,i;return null==t&&(t=r),n=e.pop(),e.length?(i=e[0],e[0]=n,g(e,0,t)):i=n,i},c=function(e,t,n){var i;return null==n&&(n=r),i=e[0],e[0]=t,g(e,0,n),i},a=function(e,t,n){var i;return null==n&&(n=r),e.length&&n(e[0],t)<0&&(t=(i=[e[0],t])[0],e[0]=i[1],g(e,0,n)),t},i=function(e,t){var i,s,o,a,c,u;for(null==t&&(t=r),c=[],s=0,o=(a=function(){u=[];for(var t=0,r=n(e.length/2);0<=r?t<r:t>r;0<=r?t++:t--)u.push(t);return u}.apply(this).reverse()).length;s<o;s++)i=a[s],c.push(g(e,i,t));return c},f=function(e,t,n){var i;if(null==n&&(n=r),-1!==(i=e.indexOf(t)))return p(e,0,i,n),g(e,i,n)},h=function(e,t,n){var s,o,c,u,l;if(null==n&&(n=r),!(o=e.slice(0,t)).length)return o;for(i(o,n),c=0,u=(l=e.slice(t)).length;c<u;c++)s=l[c],a(o,s,n);return o.sort(n).reverse()},d=function(e,t,n){var o,a,c,h,d,f,p,g,m;if(null==n&&(n=r),10*t<=e.length){if(!(c=e.slice(0,t).sort(n)).length)return c;for(a=c[c.length-1],h=0,f=(p=e.slice(t)).length;h<f;h++)n(o=p[h],a)<0&&(u(c,o,0,null,n),c.pop(),a=c[c.length-1]);return c}for(i(e,n),m=[],d=0,g=l(t,e.length);0<=g?d<g:d>g;0<=g?++d:--d)m.push(s(e,n));return m},p=function(e,t,n,i){var s,o,a;for(null==i&&(i=r),s=e[n];n>t&&i(s,o=e[a=n-1>>1])<0;)e[n]=o,n=a;return e[n]=s},g=function(e,t,n){var i,s,o,a,c;for(null==n&&(n=r),s=e.length,c=t,o=e[t],i=2*t+1;i<s;)(a=i+1)<s&&!(n(e[i],e[a])<0)&&(i=a),e[t]=e[i],i=2*(t=i)+1;return e[t]=o,p(e,c,t,n)},t=function(){function e(e){this.cmp=null!=e?e:r,this.nodes=[]}return e.push=o,e.pop=s,e.replace=c,e.pushpop=a,e.heapify=i,e.updateItem=f,e.nlargest=h,e.nsmallest=d,e.prototype.push=function(e){return o(this.nodes,e,this.cmp)},e.prototype.pop=function(){return s(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return c(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return a(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return i(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return f(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var t;return(t=new e).nodes=this.nodes.slice(0),t},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),e.exports=t}).call(Wj)}($j)),$j.exports}Hj||(Hj=1,Jj());const Qj=(e,t)=>yL.distance(e,t),Zj=e=>gw(e),Yj=e=>mw(e),Xj=e=>Zj(e.nodeId),eq=(e,t)=>yw(e.nodeId,t.nodeId),tq=()=>Zj(so(20));class rq extends Sl{options;contactsById=new Map;contactIds=[];constructor(e){super(),this.options=e,this.compareIds=this.compareIds.bind(this)}getClosestContactId(){return this.contactIds[0]}getContactIds(){return this.contactIds}addContact(e){const t=e.getNodeId();if(!this.options.excludedNodeIds?.has(t)&&!(!this.options.allowToContainReferenceId&&this.options.referenceId===t||void 0!==this.options.nodeIdDistanceLimit&&this.compareIds(this.options.nodeIdDistanceLimit,t)<0||this.contactsById.has(t)))if(void 0===this.options.maxSize||this.contactIds.length<this.options.maxSize){this.contactsById.set(t,e);const r=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(r,0,t),this.hasEventListeners()&&this.emit("contactAdded",e)}else if(this.compareIds(this.contactIds[this.options.maxSize-1],t)>0){const r=this.contactIds.pop(),n=this.contactsById.get(r);this.contactsById.delete(r),this.contactsById.set(t,e);const i=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(i,0,t),this.hasEventListeners()&&(this.emit("contactRemoved",n),this.emit("contactAdded",e))}}addContacts(e){e.forEach((e=>this.addContact(e)))}getContact(e){return this.contactsById.get(e)}has(e){return this.contactsById.has(e)}getClosestContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}getFurthestContacts(e){const t=[...this.getClosestContacts()].reverse();return void 0===e?t:t.slice(0,Math.max(e,0))}compareIds(e,t){return this.distanceToReferenceId(e)-this.distanceToReferenceId(t)}distanceToReferenceId(e){return Qj(Yj(this.options.referenceId),Yj(e))}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.hasEventListeners()&&this.emit("contactRemoved",t),!0}return!1}getAllContactsInUndefinedOrder(){return this.contactsById.values()}getSize(e){let t=0;if(void 0!==e)for(const r of e)this.has(r)&&t++;return this.contactIds.length-t}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}hasEventListeners(){return this.eventNames().length>0}}class nq{values=new Set;queue=[];maxItemCount;constructor(e){this.maxItemCount=e}add(e){if(this.values.add(e),this.queue.push(e),this.queue.length>this.maxItemCount){const e=this.queue.shift();this.values.delete(e)}}isMostLikelyDuplicate(e){return this.values.has(e)}size(){return this.values.size}clear(){this.values.clear(),this.queue=[]}}var iq;!function(e){e.CONNECTION_FAILED="CONNECTION_FAILED",e.COULD_NOT_ROUTE="COULD_NOT_ROUTE",e.STARTING_WEBSOCKET_SERVER_FAILED="STARTING_WEBSOCKET_SERVER_FAILED",e.WEBSOCKET_CONNECTION_REQUEST_REJECTED="WEBSOCKET_CONNECTION_REQUEST_REJECTED",e.COULD_NOT_START="COULD_NOT_START",e.COULD_NOT_STOP="COULD_NOT_STOP",e.CANNOT_CONNECT_TO_SELF="CANNOT_CONNECT_TO_SELF",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.ILLEGAL_RTC_PEER_CONNECTION_STATE="ILLEGAL_RTC_PEER_CONNECTION_STATE",e.ILLEGAL_ARGUMENTS="ILLEGAL_ARGUMENTS",e.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT="CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT",e.CONNECTION_LOCKER="CONNECTION_LOCKER",e.DHT_JOIN_TIMEOUT="DHT_JOIN_TIMEOUT",e.SEND_FAILED="SEND_FAILED",e.GETTING_DATA_FAILED="GETTING_DATA_FAILED",e.CONNECTION_NOT_OPEN="CONNECTION_NOT_OPEN"}(iq||(iq={}));class sq extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}}class oq extends sq{constructor(e,t){super(iq.CONNECTION_FAILED,e,t)}}class aq extends sq{constructor(e,t){super(iq.STARTING_WEBSOCKET_SERVER_FAILED,e,t)}}class cq extends sq{constructor(e,t){super(iq.COULD_NOT_START,e,t)}}class uq extends sq{constructor(e,t){super(iq.CANNOT_CONNECT_TO_SELF,e,t)}}class lq extends sq{constructor(e,t){super(iq.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT,e,t)}}class hq extends sq{constructor(e,t){super(iq.SEND_FAILED,e,t)}}const dq=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const fq=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var pq;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(pq||(pq={}));const gq=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>fq},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",pq]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>dq}])}};const mq=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var yq,bq,wq,vq,Eq,Aq;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(yq||(yq={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(bq||(bq={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(wq||(wq={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(vq||(vq={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(Eq||(Eq={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(Aq||(Aq={}));const Sq=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"ttl",kind:"scalar",T:13}])}};const kq=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const Rq=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq}])}};const Cq=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>Fq}])}};const Iq=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>Pq}])}};const Pq=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"storedAt",kind:"message",T:()=>mq},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const Tq=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const _q=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Nq=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Mq=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>Fq},{no:3,name:"requestId",kind:"scalar",T:9}])}};const xq=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",yq]}])}};const Oq=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>Pq},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>Fq}])}};const Dq=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Bq=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Lq=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const Fq=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",bq]},{no:3,name:"udp",kind:"message",T:()=>Uq},{no:4,name:"tcp",kind:"message",T:()=>Uq},{no:5,name:"websocket",kind:"message",T:()=>Uq},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const Uq=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const jq=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>Fq},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>Hq},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>Fq},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>Fq},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const qq=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",vq]}])}};const zq=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const Kq=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>Uq},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const Gq=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>Fq},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Vq=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",Eq]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Hq=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>Fq},{no:3,name:"targetDescriptor",kind:"message",T:()=>Fq},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>gq},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>zq},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>Kq},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>Gq},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>Vq},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>xq}])}};const $q=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const Wq=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const Jq=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Qq=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Zq=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const Yq=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const Xq=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const ez=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const tz=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",Aq]}])}};const rz=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const nz=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const iz=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>Pq}])}};const sz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const oz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>Fq}])}},az=new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:Tq,O:_q},{name:"getClosestRingPeers",options:{},I:Nq,O:Mq},{name:"ping",options:{},I:Dq,O:Bq},{name:"leaveNotice",options:{},I:Lq,O:dq}]),cz=new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:jq,O:qq},{name:"forwardMessage",options:{},I:jq,O:qq}]),uz=new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:jq,O:qq}]),lz=new vF("dht.StoreRpc",[{name:"storeData",options:{},I:Sq,O:kq},{name:"replicateData",options:{},I:Iq,O:dq}]),hz=new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:Oq,O:dq}]),dz=new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:$q,O:dq}]),fz=new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:Wq,O:dq},{name:"rtcOffer",options:{},I:Jq,O:dq},{name:"rtcAnswer",options:{},I:Qq,O:dq},{name:"iceCandidate",options:{},I:Zq,O:dq}]),pz=new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:Yq,O:ez},{name:"unlockRequest",options:{},I:Xq,O:dq},{name:"gracefulDisconnect",options:{},I:tz,O:dq},{name:"setPrivate",options:{},I:rz,O:dq}]),gz=new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:nz,O:iz},{name:"externalStoreData",options:{},I:Rq,O:Cq},{name:"externalFindClosestNodes",options:{},I:sz,O:oz}]);class mz{_transport;typeName=az.typeName;methods=az.methods;options=az.options;constructor(e){this._transport=e}getClosestPeers(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}getClosestRingPeers(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}ping(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveNotice(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class yz{_transport;typeName=cz.typeName;methods=cz.methods;options=cz.options;constructor(e){this._transport=e}routeMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}forwardMessage(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class bz{_transport;typeName=uz.typeName;methods=uz.methods;options=uz.options;constructor(e){this._transport=e}routeRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class wz{_transport;typeName=lz.typeName;methods=lz.methods;options=lz.options;constructor(e){this._transport=e}storeData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}replicateData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class vz{_transport;typeName=hz.typeName;methods=hz.methods;options=hz.options;constructor(e){this._transport=e}sendResponse(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Ez{_transport;typeName=dz.typeName;methods=dz.methods;options=dz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Az{_transport;typeName=fz.typeName;methods=fz.methods;options=fz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcOffer(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcAnswer(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}iceCandidate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Sz{_transport;typeName=pz.typeName;methods=pz.methods;options=pz.options;constructor(e){this._transport=e}lockRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}unlockRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}gracefulDisconnect(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}setPrivate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class kz{_transport;typeName=gz.typeName;methods=gz.methods;options=gz.options;constructor(e){this._transport=e}externalFetchData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalStoreData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalFindClosestNodes(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const Rz={connect:!0,sendIfStopped:!1,bufferWhileConnecting:!0};class Cz extends WF{targetDescriptor;sourceDescriptor;clientId;connect;sendIfStopped;bufferWhileConnecting;incomingSourceDescriptor}class Iz extends nU{ownServiceId;constructor(e,t,r){super(r),this.ownServiceId=e,this.setOutgoingMessageListener(((e,r,n)=>{let i;i=n.targetDescriptor?n.targetDescriptor:n.incomingSourceDescriptor;const s={messageId:xF(),serviceId:this.ownServiceId,body:{oneofKind:"rpcMessage",rpcMessage:e},targetDescriptor:i},o=void 0!==e.header.response?{connect:!1,sendIfStopped:!0,bufferWhileConnecting:!0}:{connect:n?.connect??Rz.connect,sendIfStopped:n?.sendIfStopped??Rz.sendIfStopped,bufferWhileConnecting:n?.bufferWhileConnecting??Rz.bufferWhileConnecting};return t(s,o)}))}handleMessageFromPeer(e){if(e.serviceId===this.ownServiceId&&"rpcMessage"===e.body.oneofKind){const t=new Cz;t.incomingSourceDescriptor=e.sourceDescriptor,this.handleIncomingMessage(e.body.rpcMessage,t)}}}class Pz{localLocks=new Map;remoteLocks=new Map;weakLocks=new Map;remotePrivateConnections=new Set;getLocalLockedConnectionCount(){return this.localLocks.size}getRemoteLockedConnectionCount(){return this.remoteLocks.size}getWeakLockedConnectionCount(){return this.weakLocks.size}isLocalLocked(e,t){return void 0===t?this.localLocks.has(e):this.localLocks.has(e)&&this.localLocks.get(e).has(t)}isRemoteLocked(e,t){return void 0===t?this.remoteLocks.has(e):!(!this.remoteLocks.has(e)||!this.remoteLocks.get(e).has(t))}isWeakLocked(e){return this.weakLocks.has(e)}isLocked(e){return this.isLocalLocked(e)||this.isRemoteLocked(e)||this.isWeakLocked(e)}addLocalLocked(e,t){this.localLocks.has(e)||this.localLocks.set(e,new Set),this.localLocks.get(e).add(t)}addRemoteLocked(e,t){this.remoteLocks.has(e)||this.remoteLocks.set(e,new Set),this.remoteLocks.get(e).add(t)}addWeakLocked(e,t){this.weakLocks.has(e)||this.weakLocks.set(e,new Set),this.weakLocks.get(e).add(t)}removeLocalLocked(e,t){this.localLocks.has(e)&&(this.localLocks.get(e)?.delete(t),0===this.localLocks.get(e)?.size&&this.localLocks.delete(e))}removeRemoteLocked(e,t){this.remoteLocks.has(e)&&(this.remoteLocks.get(e)?.delete(t),0===this.remoteLocks.get(e)?.size&&this.remoteLocks.delete(e))}removeWeakLocked(e,t){this.weakLocks.has(e)&&(this.weakLocks.get(e)?.delete(t),0===this.weakLocks.get(e)?.size&&this.weakLocks.delete(e))}addPrivate(e){this.remotePrivateConnections.add(e)}removePrivate(e){this.remotePrivateConnections.delete(e)}getPrivateConnections(){return this.remotePrivateConnections}isPrivate(e){return this.remotePrivateConnections.has(e)}clearAllLocks(e){this.localLocks.delete(e),this.remoteLocks.delete(e),this.weakLocks.delete(e)}clear(){this.localLocks.clear(),this.remoteLocks.clear(),this.weakLocks.clear()}}const Tz=e=>void 0!==e?Xj(e):"unknown",_z=()=>xF(),Nz=new Bv("ManagedConnection");class Mz extends Sl{connection;connectionId;remotePeerDescriptor;lastUsedTimestamp=Date.now();replacedAsDuplicate=!1;stopped=!1;openedAt=Date.now();bytesSent=0;bytesReceived=0;messagesSent=0;messagesReceived=0;constructor(e,t){super(),this.connectionId=_z(),this.connection=t,t.on("data",(e=>{this.lastUsedTimestamp=Date.now(),this.messagesReceived+=1,this.bytesReceived+=e.length,this.emit("managedData",e,this.getPeerDescriptor())})),t.on("disconnected",(e=>this.onDisconnected(e))),this.lastUsedTimestamp=Date.now(),this.remotePeerDescriptor=e}onDisconnected(e){Nz.trace(Tz(this.remotePeerDescriptor)+" onDisconnected() "+e),this.replacedAsDuplicate||this.emit("disconnected",e),this.removeAllListeners()}replaceAsDuplicate(){Nz.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}send(e){if(this.stopped)throw new hq("ManagedConnection is stopped");this.lastUsedTimestamp=Date.now(),this.messagesSent+=1,this.bytesSent+=e.length,this.connection.send(e)}async close(e){this.stopped||(await this.connection.close(e),this.removeAllListeners())}getNodeId(){return Xj(this.remotePeerDescriptor)}getLastUsedTimestamp(){return this.lastUsedTimestamp}getPeerDescriptor(){return this.remotePeerDescriptor}getDiagnosticInfo(){return{remotePeerDescriptor:this.remotePeerDescriptor,lastUsedTimestamp:this.lastUsedTimestamp,replacedAsDuplicate:this.replacedAsDuplicate,stopped:this.stopped,openedAt:this.openedAt,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}}var xz;!function(e){e.WEBSOCKET_SERVER="websocket-server",e.WEBSOCKET_CLIENT="websocket-client",e.WEBRTC="webrtc",e.SIMULATOR_SERVER="simulator-server",e.SIMULATOR_CLIENT="simulator-client"}(xz||(xz={}));const Oz=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8"].map((e=>uU.parseCIDR(e)));function Dz(e){if(uU.IPv4.isValid(e)){const t=uU.IPv4.parse(e);for(const e of Oz)if(t.match(e))return!0}return!1}const Bz=e=>{const t="localhost"===e.host||Dz(e.host);return e.tls||t},Lz=(e,t)=>t.websocket&&(e.type!==bq.BROWSER||Bz(t.websocket))?xz.WEBSOCKET_CLIENT:e.websocket&&(t.type!==bq.BROWSER||Bz(e.websocket))?xz.WEBSOCKET_SERVER:xz.WEBRTC,Fz=5e3,Uz=(e,t)=>{const r=Lz(e,t);return r===xz.WEBSOCKET_CLIENT?5e3:r===xz.WEBSOCKET_SERVER?7500:(xz.WEBRTC,1e4)};class jz{localPeerDescriptor;remotePeerDescriptor;client;timeout;constructor(e,t,r,n,i){this.localPeerDescriptor=e,this.remotePeerDescriptor=t,this.client=iU(new n(r.getRpcClientTransport())),this.timeout=i}getPeerDescriptor(){return this.remotePeerDescriptor}getLocalPeerDescriptor(){return this.localPeerDescriptor}getClient(){return this.client}formDhtRpcOptions(e){return{sourceDescriptor:this.localPeerDescriptor,targetDescriptor:this.remotePeerDescriptor,timeout:this.timeout??Uz(this.localPeerDescriptor,this.remotePeerDescriptor),...e}}}const qz=new Bv("ConnectionLockRpcRemote");class zz extends jz{async lockRequest(e){qz.trace(`Requesting locked connection to ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions();try{return(await this.getClient().lockRequest(t,r)).accepted}catch(e){return qz.debug("Connection lock rejected",{err:e}),!1}}unlockRequest(e){qz.trace(`Requesting connection to be unlocked from ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions({notification:!0});this.getClient().unlockRequest(t,r).catch((e=>{qz.trace("failed to send unlockRequest")}))}async gracefulDisconnect(e){qz.trace(`Notifying a graceful disconnect to ${Xj(this.getPeerDescriptor())}`);const t={disconnectMode:e},r=this.formDhtRpcOptions({connect:!1,sendIfStopped:!0,timeout:2e3});await this.getClient().gracefulDisconnect(t,r)}async setPrivate(e){qz.trace(`Setting isPrivate: ${e} for ${Xj(this.getPeerDescriptor())}`);const t={isPrivate:e},r=this.formDhtRpcOptions({connect:!1,notification:!0});await this.getClient().setPrivate(t,r)}}const Kz=new Bv("ConnectionLockRpcLocal");class Gz{options;constructor(e){this.options=e}async lockRequest(e,t){const r=t.incomingSourceDescriptor;if(eq(r,this.options.getLocalPeerDescriptor())){return{accepted:!1}}const n=Xj(r);this.options.addRemoteLocked(n,e.lockId);return{accepted:!0}}async unlockRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.removeRemoteLocked(n,e.lockId),{}}async gracefulDisconnect(e,t){const r=t.incomingSourceDescriptor;return Kz.trace(Tz(r)+" received gracefulDisconnect notice"),e.disconnectMode===Aq.LEAVING?await this.options.closeConnection(r,!0,"graceful leave notified"):await this.options.closeConnection(r,!1,"graceful disconnect notified"),{}}async setPrivate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.setPrivate(n,e.isPrivate),{}}}const Vz=(e,t)=>Hz(e+","+t)<Hz(t+","+e)?"local":"remote",Hz=e=>_v(e).readInt32LE(0);class $z{buffer=[];deferredPromise=new eb;push(e){return this.buffer.push(e),this.deferredPromise}getBuffer(){return this.buffer}resolve(){this.buffer.length=0,this.deferredPromise.resolve()}reject(){this.buffer.length=0,this.deferredPromise.reject(new hq("Could not send buffered messages"))}}var Wz;!function(e){e.OPEN_INTERNET="open_internet",e.UNKNOWN="unknown"}(Wz||(Wz={}));const Jz=new Bv("ConnectionManager");var Qz;!function(e){e.IDLE="idle",e.RUNNING="running",e.STOPPING="stopping",e.STOPPED="stopped"}(Qz||(Qz={}));const Zz="system/connection-manager";class Yz extends Sl{options;metricsContext;duplicateMessageDetector=new nq(1e4);metrics;locks=new Pz;endpoints=new Map;connectorFacade;rpcCommunicator;disconnectorIntervalRef;state=Qz.IDLE;privateClientMode=!1;constructor(e){super(),this.options=e,this.onData=this.onData.bind(this),this.send=this.send.bind(this),this.onNewConnection=this.onNewConnection.bind(this),this.metricsContext=this.options.metricsContext??new $v,this.metrics={sendMessagesPerSecond:new Hv,sendBytesPerSecond:new Hv,receiveMessagesPerSecond:new Hv,receiveBytesPerSecond:new Hv,connectionAverageCount:new Gv(0),connectionTotalFailureCount:new qv},this.metricsContext.addMetrics("node",this.metrics),this.connectorFacade=this.options.createConnectorFacade(),this.send=this.send.bind(this),this.rpcCommunicator=new Iz(Zz,this.send,{rpcRequestTimeout:1e4});const t=new Gz({addRemoteLocked:(e,t)=>this.locks.addRemoteLocked(e,t),removeRemoteLocked:(e,t)=>this.locks.removeRemoteLocked(e,t),closeConnection:(e,t,r)=>this.closeConnection(e,t,r),getLocalPeerDescriptor:()=>this.getLocalPeerDescriptor(),setPrivate:(e,t)=>{this.options.allowIncomingPrivateConnections?t?this.locks.addPrivate(e):this.locks.removePrivate(e):Jz.debug(`node ${e} attemted to set a connection as private, but it is not allowed`)}});this.rpcCommunicator.registerRpcMethod(Yq,ez,"lockRequest",((e,r)=>t.lockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(Xq,"unlockRequest",((e,r)=>t.unlockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(tz,"gracefulDisconnect",((e,r)=>t.gracefulDisconnect(e,r))),this.rpcCommunicator.registerRpcNotification(rz,"setPrivate",((e,r)=>t.setPrivate(e,r)))}garbageCollectConnections(e,t){if(this.endpoints.size<=e)return;const r=new rq({referenceId:Xj(this.getLocalPeerDescriptor()),maxSize:1e5,allowToContainReferenceId:!1});this.endpoints.forEach((e=>{if(e.connected){const n=e.connection,i=n.getNodeId();!this.locks.isLocked(i)&&!this.locks.isPrivate(i)&&Date.now()-n.getLastUsedTimestamp()>t&&(Jz.trace("disconnecting in timeout interval: "+Tz(n.getPeerDescriptor())),r.addContact(n))}}));const n=r.getFurthestContacts(this.endpoints.size-e);for(const e of n){const t=e.getPeerDescriptor();Jz.trace("garbageCollecting "+Xj(t)),this.gracefullyDisconnectAsync(t,Aq.NORMAL).catch((e=>{}))}}async start(){if(this.state===Qz.RUNNING||this.state===Qz.STOPPED)throw new cq(`Cannot start already ${this.state} module`);this.state=Qz.RUNNING,Jz.trace("Starting ConnectionManager..."),await this.connectorFacade.start((e=>this.onNewConnection(e)),(e=>this.hasConnection(e)),this),this.disconnectorIntervalRef=setInterval((()=>{Jz.trace("disconnectorInterval");this.garbageCollectConnections(this.options.maxConnections??80,2e4)}),5e3)}async stop(){this.state!==Qz.STOPPED&&this.state!==Qz.STOPPING&&(this.state=Qz.STOPPING,Jz.trace("Stopping ConnectionManager"),this.disconnectorIntervalRef&&clearInterval(this.disconnectorIntervalRef),await Promise.all(Array.from(this.endpoints.values()).map((async e=>{if(e.connected)try{await this.gracefullyDisconnectAsync(e.connection.getPeerDescriptor(),Aq.LEAVING)}catch(e){Jz.error(e)}else{const t=e.connection;Jz.trace("handshake of connection not completed, force-closing");const r=eE(t,"disconnected",2e3);t.close(!0);try{await r,Jz.trace("resolving after receiving disconnected event from non-handshaked connection")}catch(t){e.buffer.reject(),Jz.trace("force-closing non-handshaked connection timed out "+t)}}}))),await this.connectorFacade.stop(),this.state=Qz.STOPPED,this.rpcCommunicator.stop(),this.duplicateMessageDetector.clear(),this.locks.clear(),this.removeAllListeners())}getLocalLockedConnectionCount(){return this.locks.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.locks.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.locks.getWeakLockedConnectionCount()}async send(e,t=Rz){if((this.state===Qz.STOPPED||this.state===Qz.STOPPING)&&!t.sendIfStopped)return;const r=e.targetDescriptor;if(this.isConnectionToSelf(r))throw new uq("Cannot send to self");const n=Xj(r);Jz.trace(`Sending message to: ${n}`),e={...e,sourceDescriptor:this.getLocalPeerDescriptor()};let i=this.endpoints.get(n)?.connection;if(!i&&t.connect)i=this.connectorFacade.createConnection(r),this.onNewConnection(i);else if(!i||i&&!this.endpoints.get(n).connected&&!t.connect)throw new hq("No connection to target, connect flag is false");const s=Hq.toBinary(e);if(this.metrics.sendBytesPerSecond.record(s.byteLength),this.metrics.sendMessagesPerSecond.record(1),this.endpoints.get(n).connected)i.send(s);else if(t.bufferWhileConnecting)return this.endpoints.get(n).buffer.push(s)}isConnectionToSelf(e){return eq(e,this.getLocalPeerDescriptor())||this.isOwnWebsocketServer(e)}isOwnWebsocketServer(e){const t=this.getLocalPeerDescriptor();return void 0!==e.websocket&&void 0!==t.websocket&&(e.websocket.port===t.websocket.port&&e.websocket.host===t.websocket.host)}getLocalPeerDescriptor(){return this.connectorFacade.getLocalPeerDescriptor()}hasConnection(e){return this.getConnections().some((t=>Xj(t)==e))}getConnectionCount(){return this.getConnections().length}hasLocalLockedConnection(e){return this.locks.isLocalLocked(e)}hasRemoteLockedConnection(e){return this.locks.isRemoteLocked(e)}handleMessage(e){const t=e.body.oneofKind;Jz.trace("Received message of type "+t),"rpcMessage"===t?this.duplicateMessageDetector.isMostLikelyDuplicate(e.messageId)?Jz.trace("handleMessage filtered duplicate "+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId):(this.duplicateMessageDetector.add(e.messageId),e.serviceId===Zz?this.rpcCommunicator?.handleMessageFromPeer(e):(Jz.trace('emit "message" '+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId),this.emit("message",e))):Jz.trace("Filtered out non-RPC message of type "+t)}onData(e,t){if(this.state===Qz.STOPPED)return;let r;this.metrics.receiveBytesPerSecond.record(e.byteLength),this.metrics.receiveMessagesPerSecond.record(1);try{r=Hq.fromBinary(e)}catch(e){return void Jz.debug(`Parsing incoming data into Message failed: ${e}`)}r.sourceDescriptor=t;try{this.handleMessage(r)}catch(e){Jz.debug(`Handling incoming data failed: ${e}`)}}onConnected(e,t){const r=new Mz(e,t);r.on("managedData",this.onData),r.once("disconnected",(t=>this.onDisconnected(e,t)));const n=Xj(e),i=this.endpoints.get(n),s=i.buffer,o=i.connection,a=s.getBuffer();for(;a.length>0;)Jz.trace("emptying buffer"),r.send(a.shift());s.resolve(),o.destroy(),this.endpoints.set(n,{connected:!0,connection:r}),this.privateClientMode&&this.setPrivateForConnection(e,this.privateClientMode).catch((()=>{})),this.emit("connected",e),this.onConnectionCountChange()}onDisconnected(e,t){const r=Xj(e);Jz.trace(r+" onDisconnected() gracefulLeave: "+t);const n=this.endpoints.get(r);n&&(this.locks.clearAllLocks(r),!1===n.connected&&n.buffer.reject(),this.endpoints.delete(r),Jz.trace(r+" deleted connection in onDisconnected() gracefulLeave: "+t),this.emit("disconnected",e,t),this.onConnectionCountChange())}onNewConnection(e){return this.state!==Qz.STOPPED&&(Jz.trace("onNewConnection()"),!!this.acceptNewConnection(e)&&(e.once("connected",((e,t)=>this.onConnected(e,t))),e.once("disconnected",(t=>this.onDisconnected(e.getPeerDescriptor(),t))),!0))}acceptNewConnection(e){const t=Xj(e.getPeerDescriptor());if(Jz.trace(t+" acceptNewConnection()"),this.endpoints.has(t)){if("remote"===Vz(Xj(this.getLocalPeerDescriptor()),t)){let r;const n=this.endpoints.get(t);this.endpoints.get(t).connected?(Jz.debug("replacing connected connection",{nodeId:t}),r=new $z):r=n.buffer;const i=n.connection;return Jz.trace("replaced: "+t),i.replaceAsDuplicate(),this.endpoints.set(t,{connected:!1,connection:e,buffer:r}),!0}return!1}return Jz.trace(t+" added to connections at acceptNewConnection"),this.endpoints.set(t,{connected:!1,buffer:new $z,connection:e}),!0}async closeConnection(e,t,r){const n=Xj(e);if(Jz.trace(n+" closeConnection() "+r),this.locks.clearAllLocks(n),this.endpoints.has(n)){const e=this.endpoints.get(n).connection;await e.close(t)}else Jz.trace(n+" closeConnection() this.endpoints did not have the id"),this.emit("disconnected",e,!1)}lockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e),n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.locks.addLocalLocked(r,t),n.lockRequest(t).then((e=>Jz.trace("LockRequest successful"))).catch((e=>{Jz.debug(e)}))}unlockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e);this.locks.removeLocalLocked(r,t);const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.endpoints.has(r)&&n.unlockRequest(t)}weakLockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.addWeakLocked(e,t)}weakUnlockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.removeWeakLocked(e,t)}async enablePrivateClientMode(){this.privateClientMode=!0,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!0)})))}async disablePrivateClientMode(){this.privateClientMode=!1,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!1)})))}getConnectedEndpoints(){return Array.from(this.endpoints.values()).filter((e=>e.connected))}isPrivateClientMode(){return this.privateClientMode}async setPrivateForConnection(e,t){const r=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);await r.setPrivate(t)}async gracefullyDisconnectAsync(e,t){const r=this.endpoints.get(Xj(e));if(r)if(r.connected){const n=r.connection,i=new Promise(((e,t)=>{eE(n,"disconnected",2e3).then((()=>{Jz.trace("disconnected event received in gracefullyDisconnectAsync()")})).catch((e=>{Jz.trace("force-closing connection after timeout "+e),n.close(!0)})).finally((()=>{Jz.trace("resolving after receiving disconnected event"),e()}))}));await Promise.all([i,this.doGracefullyDisconnectAsync(e,t)])}else r.connection.close(!0);else Jz.debug("gracefullyDisconnectedAsync() tried on a non-existing connection")}async doGracefullyDisconnectAsync(e,t){const r=Xj(e);Jz.trace(r+" gracefullyDisconnectAsync()");const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);try{await n.gracefulDisconnect(t)}catch(e){Jz.trace(r+" remote.gracefulDisconnect() failed"+e)}}getConnections(){return Array.from(this.endpoints.values()).map((e=>e)).filter((e=>e.connected&&!this.locks.isPrivate(Xj(e.connection.getPeerDescriptor())))).map((e=>e.connection.getPeerDescriptor()))}onConnectionCountChange(){this.metrics.connectionAverageCount.record(this.endpoints.size)}getDiagnosticInfo(){return{connections:Array.from(this.endpoints.values()).filter((e=>e.connected)).map((e=>e.connection)).map((e=>e.getDiagnosticInfo())),connectionCount:this.endpoints.size}}}new Bv("SimulatorConnection");const Xz="1.1",eK=e=>{const t=tK(Xz).major,r=tK(e)?.major;return!(void 0===r||r<t)},tK=e=>{const t=e.split(".");if(2===t.length){const e=t.map((e=>Number(e)));if(!e.some((e=>isNaN(e))))return{major:e[0],minor:e[1]}}};var rK="103.7.0-rc.2";const nK=new Bv("Handshaker"),iK=(e,t,r,n)=>{const i=new aK(e,r),s=()=>{i.stop(),r.off("disconnected",u),r.off("connected",c),i.off("handshakeCompleted",a),i.off("handshakeFailed",o),t.off("disconnected",l)},o=e=>{e!==Eq.INVALID_TARGET_PEER_DESCRIPTOR&&e!==Eq.UNSUPPORTED_PROTOCOL_VERSION||(t.close(!1),s())},a=e=>{nK.trace("handshake completed for outgoing connection, "+Xj(e)),t.onHandshakeCompleted(r),s()},c=()=>i.sendHandshakeRequest(n),u=e=>{t.close(e),s()},l=()=>{r.close(!1),s()};return i.once("handshakeFailed",o),i.once("handshakeCompleted",a),r.once("connected",c),r.once("disconnected",u),t.once("disconnected",l),i},sK=(e,t,r,n)=>{r.sendHandshakeResponse(n),t.destroy(),e.destroy()},oK=(e,t,r)=>{e.sendHandshakeResponse(),t.onHandshakeCompleted(r)};let aK=class extends Sl{static HANDSHAKER_SERVICE_ID="system/handshaker";localPeerDescriptor;connection;onDataListener;constructor(e,t){super(),this.localPeerDescriptor=e,this.connection=t,this.onDataListener=e=>this.onData(e),this.connection.on("data",this.onDataListener)}onData(e){try{const t=Hq.fromBinary(e);if("handshakeRequest"===t.body.oneofKind){nK.trace("handshake request received");const e=t.body.handshakeRequest;this.emit("handshakeRequest",e.sourcePeerDescriptor,e.protocolVersion,e.targetPeerDescriptor)}if("handshakeResponse"===t.body.oneofKind){nK.trace("handshake response received");const e=t.body.handshakeResponse,r=eK(e.protocolVersion)?e.error:Eq.UNSUPPORTED_PROTOCOL_VERSION;void 0!==r?this.emit("handshakeFailed",r):this.emit("handshakeCompleted",e.sourcePeerDescriptor)}}catch(e){nK.debug("error while parsing handshake message",e)}}sendHandshakeRequest(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,targetPeerDescriptor:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeRequest",handshakeRequest:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake request sent")}sendHandshakeResponse(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,error:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeResponse",handshakeResponse:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake response sent")}stop(){this.connection.off("data",this.onDataListener),this.removeAllListeners()}};const cK=new Bv("PendingConnection");class uK extends Sl{connectingAbortController=new AbortController;remotePeerDescriptor;replacedAsDuplicate=!1;stopped=!1;constructor(e,t=15e3){super(),this.remotePeerDescriptor=e,Yy((()=>{this.close(!1)}),t,this.connectingAbortController.signal)}replaceAsDuplicate(){cK.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}onHandshakeCompleted(e){this.replacedAsDuplicate||this.emit("connected",this.remotePeerDescriptor,e)}close(e){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.replacedAsDuplicate||this.emit("disconnected",e))}destroy(){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.removeAllListeners())}getPeerDescriptor(){return this.remotePeerDescriptor}}new Bv("SimulatorConnector");class lK extends Iz{transport;messageListener;disconnectedListener;constructor(e,t,r){super(e,((e,r)=>t.send(e,r)),r),this.messageListener=e=>{this.handleMessageFromPeer(e)},this.disconnectedListener=e=>{this.getRequestIds((t=>eq(e,t.getCallContext().targetDescriptor))).forEach((e=>this.handleClientError(e,new qF.Disconnected("Peer disconnected"))))},this.transport=t,t.on("message",this.messageListener),t.on("disconnected",this.disconnectedListener)}destroy(){this.transport.off("message",this.messageListener),this.transport.off("disconnected",this.disconnectedListener),this.stop()}}const hK="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;var dK;!function(e){e.OFFER="offer",e.ANSWER="answer"}(dK||(dK={}));var fK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(fK||(fK={}));const pK=new Bv("DirectWebrtcConnection (browser)");let gK;const mK=new Promise((e=>{gK=e}));if(hK){const e=t=>{if("streamr-webrtc-bridge-port"===t.data?.type&&t.data.port){const r=wU(t.data.port);gK(r),self.removeEventListener("message",e)}};self.addEventListener("message",e)}var yK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(yK||(yK={}));const bK=new Bv("WorkerWebrtcConnection");const wK=hK?class extends Sl{connectionId;connectionType=xz.WEBRTC;iceServers;bufferThresholdHigh;bufferThresholdLow;dataChannel;bridge;closed=!1;connected=!1;earlyTimeout;messageQueue=[];startPromise;constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.bufferThresholdHigh=e.bufferThresholdHigh??2**17,this.bufferThresholdLow=e.bufferThresholdLow??32768,this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.startPromise=this.doStart(e),this.startPromise.catch((e=>{bK.warn("Failed to start worker WebRTC connection",{err:e}),this.doClose(!1,"Failed to start")}))}async doStart(e){this.bridge=await mK;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));await this.bridge.start(this.connectionId,t,e,IU({onLocalCandidate:(e,t)=>{this.closed||this.emit("localCandidate",e,t)},onLocalDescription:(e,t)=>{this.closed||this.emit("localDescription",e,t)},onConnectionStateChange:e=>{e!==yK.CLOSED&&e!==yK.DISCONNECTED&&e!==yK.FAILED||this.doClose(!1,`pcState=${e}`)},onDataChannel:e=>{this.closed||(this.setupDataChannel(e),"open"===e.readyState&&this.onDataChannelOpen())}}))}async setRemoteDescription(e,t){if(this.startPromise&&await this.startPromise,!this.bridge||this.closed)return;await this.bridge.setRemoteDescription(this.connectionId,e,t)&&clearTimeout(this.earlyTimeout)}addRemoteCandidate(e,t){this.doAddRemoteCandidate(e,t).catch((e=>{bK.warn("Failed to add remote candidate via bridge",{err:e})}))}async doAddRemoteCandidate(e,t){this.startPromise&&await this.startPromise,this.bridge&&!this.closed&&await this.bridge.addRemoteCandidate(this.connectionId,e,t)}isOpen(){return this.connected}async close(e,t){this.doClose(e,t)}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){this.connected&&this.dataChannel?(this.dataChannel.bufferedAmount,this.messageQueue.length,this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel.send(e)):this.closed||this.messageQueue.push(e)}setConnectionId(e){const t=this.connectionId;this.connectionId=e,this.bridge&&t!==e&&this.bridge.renameConnection(t,e).catch((()=>{}))}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{bK.trace("dc.onOpen (worker)"),this.onDataChannelOpen()},e.onclose=()=>{bK.trace("dc.onClosed (worker)"),this.doClose(!1,"dataChannel.onclose")},e.onerror=e=>{bK.warn("Data channel error (worker)",{err:e})},e.onmessage=e=>{bK.trace("dc.onmessage (worker)"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(bK.trace("dc.onBufferedAmountLow (worker)");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}onDataChannelOpen(){this.connected=!0,this.flushMessageQueue(),this.emit("connected")}flushMessageQueue(){for(;this.messageQueue.length>0&&this.dataChannel&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}doClose(e,t){if(!this.closed){if(this.closed=!0,this.connected=!1,this.messageQueue.length=0,clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){bK.warn("Failed to close data channel (worker)",{err:e})}this.dataChannel=void 0,this.bridge?.close(this.connectionId).catch((()=>{}))}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null)}}:class extends Sl{connectionId;connectionType=xz.WEBRTC;lastState="connecting";iceServers;peerConnection;bufferThresholdHigh=2**17;bufferThresholdLow=32768;dataChannel;makingOffer=!1;isOffering=!1;closed=!1;earlyTimeout;messageQueue=[];constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.isOffering=e;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));if(this.peerConnection=new RTCPeerConnection({iceServers:t}),this.peerConnection.onicecandidate=e=>{null!==e.candidate&&null!==e.candidate.sdpMid&&this.emit("localCandidate",e.candidate.candidate,e.candidate.sdpMid)},this.peerConnection.onicegatheringstatechange=()=>{pK.trace(`conn.onGatheringStateChange: ${this.peerConnection?.iceGatheringState}`)},this.peerConnection.onconnectionstatechange=()=>this.onStateChange(),e){this.peerConnection.onnegotiationneeded=async()=>{if(void 0!==this.peerConnection){this.makingOffer=!0;try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription?.sdp,this.peerConnection.localDescription?.type)}this.makingOffer=!1};const e=this.peerConnection.createDataChannel("streamrDataChannel");this.setupDataChannel(e)}else this.peerConnection.ondatachannel=e=>{this.setupDataChannel(e.channel)}}async setRemoteDescription(e,t){const r=t.toLowerCase()===dK.OFFER&&(this.makingOffer||"stable"!=this.peerConnection?.signalingState);if(!(this.isOffering&&r)){try{await(this.peerConnection?.setRemoteDescription({sdp:e,type:t.toLowerCase()})),clearTimeout(this.earlyTimeout)}catch(e){pK.warn("Failed to set remote description",{err:e})}if(t.toLowerCase()===dK.OFFER&&void 0!==this.peerConnection){try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription.sdp,this.peerConnection.localDescription.type)}}}addRemoteCandidate(e,t){this.peerConnection?.addIceCandidate({candidate:e,sdpMid:t}).catch((e=>{pK.warn("Failed to add ICE candidate",{err:e})}))}isOpen(){return"connected"===this.lastState}async close(e,t){this.doClose(e,t)}doClose(e,t){if(!this.closed){if(this.closed=!0,this.lastState="closed",clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){pK.warn("Failed to close data channel",{err:e})}if(this.dataChannel=void 0,void 0!==this.peerConnection)try{this.peerConnection.close()}catch(e){pK.warn("Failed to close connection",{err:e})}this.peerConnection=void 0}}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){"connected"===this.lastState?(this.dataChannel.bufferedAmount,this.messageQueue.length,this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel?.send(e)):pK.warn("Tried to send on a connection with last state "+this.lastState)}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{pK.trace("dc.onOpen"),this.onDataChannelOpen()},e.onclose=()=>{pK.trace("dc.onClosed"),this.doClose(!1)},e.onerror=e=>{pK.warn("Data channel error",{err:e})},e.onmessage=e=>{pK.trace("dc.onmessage"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(pK.trace("dc.onBufferedAmountLow");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null),void 0!==this.peerConnection&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.onicecandidate=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.ondatachannel=null)}onDataChannelOpen(){this.lastState="connected",this.emit("connected")}onStateChange(){this.peerConnection.connectionState!==fK.CLOSED&&this.peerConnection.connectionState!==fK.DISCONNECTED&&this.peerConnection.connectionState!==fK.FAILED||this.doClose(!1)}setConnectionId(e){this.connectionId=e}},vK=new Bv("WebrtcConnectorRpcRemote");class EK extends jz{requestConnection(){const e=this.formDhtRpcOptions({notification:!0});this.getClient().requestConnection({},e).catch((e=>{vK.trace("Failed to send requestConnection")}))}sendRtcOffer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcOffer(r,n).catch((e=>{vK.trace("Failed to send rtcOffer")}))}sendRtcAnswer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcAnswer(r,n).catch((e=>{vK.trace("Failed to send rtcAnswer")}))}sendIceCandidate(e,t,r){const n={connectionId:r,mid:t,candidate:e},i=this.formDhtRpcOptions();this.getClient().iceCandidate(n,i).catch((e=>{vK.trace("Failed to send iceCandidate")}))}}const AK=new Bv("WebrtcConnectorRpcLocal");class SK{options;constructor(e){this.options=e}async requestConnection(e){const t=e.incomingSourceDescriptor;if(this.options.ongoingConnectAttempts.has(Xj(t)))return{};const r=this.options.connect(t,!1);return this.options.onNewConnection(r),{}}async rtcOffer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);let i,s;return this.options.ongoingConnectAttempts.has(n)?(s=this.options.ongoingConnectAttempts.get(n).managedConnection,i=this.options.ongoingConnectAttempts.get(n).connection):(s=this.options.connect(r,!0),i=this.options.ongoingConnectAttempts.get(n).connection,this.options.onNewConnection(s)),i.setConnectionId(e.connectionId),i.setRemoteDescription(e.description,"offer"),{}}async rtcAnswer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring RTC answer due to connectionId mismatch"),{}):(i.setRemoteDescription(e.description,"answer"),{}):{}}async iceCandidate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring remote candidate due to connectionId mismatch"),{}):(this.isIceCandidateAllowed(e.candidate)&&i.addRemoteCandidate(e.candidate,e.mid),{}):{}}isIceCandidateAllowed(e){if(!this.options.allowPrivateAddresses){const t=function(e){const t=e.split(" ").filter((e=>e.length>0));return t.length>=5&&uU.isValid(t[4])?t[4]:void 0}(e);if(void 0!==t&&Dz(t))return!1}return!0}}const kK=new Bv("WebrtcConnector");class RK{static WEBRTC_CONNECTOR_SERVICE_ID="system/webrtc-connector";rpcCommunicator;ongoingConnectAttempts=new Map;localPeerDescriptor;stopped=!1;options;constructor(e){this.options=e,this.rpcCommunicator=new lK(RK.WEBRTC_CONNECTOR_SERVICE_ID,e.transport,{rpcRequestTimeout:15e3}),this.registerLocalRpcMethods(e)}registerLocalRpcMethods(e){const t=new SK({connect:(e,t)=>this.connect(e,t),onNewConnection:e=>this.options.onNewConnection(e),ongoingConnectAttempts:this.ongoingConnectAttempts,rpcCommunicator:this.rpcCommunicator,getLocalPeerDescriptor:()=>this.localPeerDescriptor,allowPrivateAddresses:e.allowPrivateAddresses??!0});this.rpcCommunicator.registerRpcNotification(Wq,"requestConnection",(async(e,r)=>this.stopped?{}:t.requestConnection(r))),this.rpcCommunicator.registerRpcNotification(Jq,"rtcOffer",(async(e,r)=>this.stopped?{}:t.rtcOffer(e,r))),this.rpcCommunicator.registerRpcNotification(Qq,"rtcAnswer",(async(e,r)=>this.stopped?{}:t.rtcAnswer(e,r))),this.rpcCommunicator.registerRpcNotification(Zq,"iceCandidate",(async(e,r)=>this.stopped?{}:t.iceCandidate(e,r)))}connect(e,t){if(eq(e,this.localPeerDescriptor))throw new uq("Cannot open WebRTC Connection to self");kK.trace(`Opening WebRTC connection to ${Xj(e)}`);const r=Xj(e),n=this.ongoingConnectAttempts.get(r);if(n)return n.managedConnection;const i=this.createConnection(e),s=Xj(this.localPeerDescriptor),o=Xj(e),a="local"===Vz(s,o);let c;const u=new EK(this.localPeerDescriptor,e,this.rpcCommunicator,Az),l=()=>{this.ongoingConnectAttempts.delete(r),i.off("disconnected",l),c.off("disconnected",l),c.off("connected",l)};if(a)c=new uK(e),iK(this.localPeerDescriptor,c,i,e),i.once("localDescription",(e=>{kK.trace("Sending offer to remote peer"),u.sendRtcOffer(e,i.connectionId)}));else{c=new uK(e);const t=((e,t,r)=>{const n=new aK(e,r),i=()=>{n.stop(),t.off("disconnected",s),r.off("disconnected",s)},s=e=>{t.close(e),i()};return n.on("handshakeRequest",(()=>{i()})),r.once("disconnected",s),t.once("disconnected",(()=>{r.close(!1),i()})),n})(this.localPeerDescriptor,c,i);i.once("localDescription",(e=>{u.sendRtcAnswer(e,i.connectionId)})),t.on("handshakeRequest",((e,r)=>{eK(r)?oK(t,c,i):sK(c,i,t,Eq.UNSUPPORTED_PROTOCOL_VERSION),l()}))}return this.ongoingConnectAttempts.set(o,{managedConnection:c,connection:i}),i.on("disconnected",l),c.on("disconnected",l),c.on("connected",l),i.on("localCandidate",((e,t)=>{void 0!==this.options.externalIp&&(e=((e,t)=>{const r=e.split(" ");return"host"===r[7]&&(r[4]=t),r.join(" ")})(e,this.options.externalIp),kK.debug(`onLocalCandidate injected external ip ${e} ${t}`)),u.sendIceCandidate(e,t,i.connectionId)})),i.start(a),t||a||u.requestConnection(),c}createConnection(e){return new wK({remotePeerDescriptor:e,iceServers:this.options.iceServers,bufferThresholdLow:this.options.bufferThresholdLow,bufferThresholdHigh:this.options.bufferThresholdHigh,portRange:this.options.portRange})}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async stop(){kK.trace("stop()"),this.stopped=!0;const e=Array.from(this.ongoingConnectAttempts.values());await Promise.allSettled(e.map((async e=>{e.connection.destroy(),e.managedConnection.close(!1)}))),this.rpcCommunicator.destroy()}}const CK=new Bv("AbstractWebsocketClientConnection");class IK extends Sl{connectionId;connectionType=xz.WEBSOCKET_CLIENT;destroyed=!1;constructor(){super(),this.connectionId=_z()}send(e){this.destroyed?CK.debug("Tried to send() on stopped connection"):1===this.socket?.readyState?(CK.trace(`Sending data with size ${e.byteLength}`),this.socket?.send(e)):CK.debug("Tried to send data on a non-open connection",{id:this.connectionId,readyState:this.socket.readyState,destroyed:this.destroyed})}async close(e){this.emit("disconnected",e,void 0,"close() called"),this.removeAllListeners(),this.destroyed?CK.debug("Tried to close() a stopped connection",{id:this.connectionId}):(CK.trace(`Closing socket for connection ${this.connectionId}`),this.socket?.close(e?3001:void 0))}destroy(){CK.trace("destroy() a connection"),this.destroyed?CK.debug("Tried to destroy() a stopped connection"):(this.removeAllListeners(),this.socket&&(this.stopListening(),this.socket.close(),this.socket=void 0),this.destroyed=!0)}onOpen(){this.destroyed||(CK.trace("WebSocket Client Connected"),1===this.socket?.readyState&&this.emit("connected"))}onMessage(e){this.emit("data",e)}onClose(e,t){this.destroyed||(CK.trace("Websocket Closed"),this.doDisconnect(e,t))}onError(e){this.destroyed||(CK.trace("WebSocket Client error: "+e?.message,{error:e}),this.emit("error",e.name))}doDisconnect(e,t){this.destroyed=!0,this.stopListening(),this.socket=void 0;const r=1001===e||3001===e;this.emit("disconnected",r,e,t),this.removeAllListeners()}}const PK=new Bv("WebsocketClientConnection (browser)");class TK extends IK{socket;connect(e,t){this.destroyed?PK.debug("Tried to connect() a stopped connection"):(this.socket=new FU.w3cwebsocket(e,void 0,void 0,void 0,{rejectUnauthorized:!t}),this.socket.binaryType="arraybuffer",this.socket.onerror=e=>this.onError(e),this.socket.onopen=()=>this.onOpen(),this.socket.onclose=e=>this.onClose(e.code,e.reason),this.socket.onmessage=e=>{this.destroyed||("string"==typeof e.data?PK.debug("Received string data, only binary data is supported"):this.onMessage(new Uint8Array(e.data)))})}stopListening(){this.socket&&(this.socket.onopen=void 0,this.socket.onclose=void 0,this.socket.onerror=void 0,this.socket.onmessage=void 0)}}class _K{options;constructor(e){this.options=e}async requestConnection(e,t){if(this.options.abortSignal.aborted)return{};const r=t.incomingSourceDescriptor;if(!this.options.hasConnection(Xj(r))){const e=this.options.connect(r);this.options.onNewConnection(e)}return{}}}const NK=(e,t)=>(e.tls?"wss://":"ws://")+e.host+":"+e.port+(void 0!==t?"?action="+t:"");class MK{static WEBSOCKET_CONNECTOR_SERVICE_ID="system/websocket-connector";websocketServer;geoIpLocator;localPeerDescriptor;connectingConnections=new Map;abortController=new AbortController;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new _K({connect:e=>this.connect(e),hasConnection:e=>this.connectingConnections.has(e)||this.options.hasConnection(e),onNewConnection:e=>this.options.onNewConnection(e),abortSignal:this.abortController.signal});this.options.rpcCommunicator.registerRpcNotification($q,"requestConnection",(async(t,r)=>this.abortController.signal.aborted?{}:e.requestConnection(t,r)))}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_CLIENT}connect(e){const t=Xj(e),r=this.connectingConnections.get(t);if(r)return r;const n=new TK,i=NK(e.websocket),s=new uK(e);iK(this.localPeerDescriptor,s,n,e),this.connectingConnections.set(t,s);const o=()=>{this.connectingConnections.has(t)&&this.connectingConnections.delete(t),n.off("disconnected",o),s.off("disconnected",o),s.off("connected",o)};return n.on("disconnected",o),s.on("disconnected",o),s.on("connected",o),n.connect(i,!1),s}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.connectingConnections.values()).forEach((e=>e.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}class xK extends Sl{constructor(e){super()}async start(){throw new Error("WebsocketServer is not supported in browser environment")}async stop(){throw new Error("WebsocketServer is not supported in browser environment")}updateCertificate(e,t){throw new Error("WebsocketServer is not supported in browser environment")}}const OK=new Bv("AutoCertifierClientFacade");class DK{autoCertifierClient;rpcCommunicator;options;constructor(e){this.options=e,this.rpcCommunicator=new lK("system/auto-certificer",e.transport),this.autoCertifierClient=e.createClientFactory?e.createClientFactory():(()=>{throw new Error("AutoCertifierClient is not supported in browser environment")})(e.configFile,e.url,this.rpcCommunicator,e.wsServerPort)}async start(){this.autoCertifierClient.on("updatedCertificate",(e=>{this.options.setHost(e.fqdn),this.options.updateCertificate(e.certificate,e.privateKey),OK.trace("Updated certificate")})),await Promise.all([eE(this.autoCertifierClient,"updatedCertificate",6e4),this.autoCertifierClient.start()])}stop(){this.autoCertifierClient.stop(),this.rpcCommunicator.destroy()}}const BK=new Bv("connectivityChecker"),LK=async({url:e,allowSelfSignedCertificate:t,timeoutMs:r=1e3})=>{const n=new TK;let i;try{const s=tE(n,["connected","error"],r);n.connect(e,t),i=await s}catch{throw new oq("WebSocket connection timed out")}if("error"===i.winnerName)throw new oq("Could not open WebSocket connection");return n},FK="system/connectivity-checker",UK=async(e,t)=>{let r;const n={host:t.websocket.host,port:t.websocket.port,tls:t.websocket.tls},i=NK(n,"connectivityRequest");BK.debug(`Attempting connectivity check with entrypoint ${i}`);try{r=await LK({url:i,allowSelfSignedCertificate:e.allowSelfSignedCertificate})}catch(e){throw new oq(`Failed to connect to entrypoint for connectivity check: ${i}`,e)}const s={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityRequest",connectivityRequest:e}};try{const e=new Promise(((e,t)=>{const n=setTimeout((()=>{r.close(!1),t(new lq("timeout"))}),5e3),i=s=>{r.close(!1);try{const o=Hq.fromBinary(s);if("connectivityResponse"===o.body.oneofKind){BK.debug("ConnectivityResponse received: "+JSON.stringify(Hq.toJson(o)));const s=o.body.connectivityResponse,a=s.protocolVersion;r.off("data",i),clearTimeout(n),eK(a)?e(s):t(`Unsupported version: ${a}`)}}catch(e){BK.trace("Could not parse message",{err:e})}};r.on("data",i)}));return r.send(Hq.toBinary(s)),BK.trace("ConnectivityRequest sent: "+JSON.stringify(Hq.toJson(s))),await e}catch(e){throw BK.error("error getting connectivityresponse"),e}},jK=new Bv("connectivityRequestHandler"),qK=async(e,t,r)=>{const n=t.host??e.getRemoteIpAddress(),i=e.getRemoteIpAddress();let s;if(0!==t.port?s=await zK(t,i,n):(jK.trace("ConnectivityRequest port is 0, replying without connectivityProbe"),s={host:n,natType:Wz.UNKNOWN,ipAddress:mE(i),protocolVersion:Xz}),void 0!==r){const e=r.lookup(i);void 0!==e&&(s.latitude=e.latitude,s.longitude=e.longitude)}const o={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityResponse",connectivityResponse:s}};e.send(Hq.toBinary(o)),jK.trace("ConnectivityResponse sent: "+JSON.stringify(Hq.toJson(o)))},zK=async(e,t,r)=>{let n,i;try{const s={host:r,port:e.port,tls:e.tls},o=NK(s,"connectivityProbe");jK.trace(`Attempting Connectivity Check to ${o}`),n=await LK({url:o,allowSelfSignedCertificate:e.allowSelfSignedCertificate}),jK.trace("Connectivity test produced positive result, communicating reply to the requester "+r+":"+e.port),i={host:r,natType:Wz.OPEN_INTERNET,websocket:{host:r,port:e.port,tls:e.tls},ipAddress:mE(t),protocolVersion:Xz}}catch(e){jK.debug("error",{err:e}),i={host:r,natType:Wz.UNKNOWN,ipAddress:mE(t),protocolVersion:Xz}}return n&&n.close(!1),i},KK=new Bv("WebsocketClientConnectorRpcRemote");class GK extends jz{async requestConnection(){KK.trace(`Requesting WebSocket connection from ${Xj(this.getLocalPeerDescriptor())}`);const e=this.formDhtRpcOptions();return this.getClient().requestConnection({},e)}}const VK=new Bv("WebsocketServerConnector");class HK{websocketServer;geoIpLocator;ongoingConnectRequests=new Map;host;autoCertifierClient;selectedPort;localPeerDescriptor;abortController=new AbortController;options;constructor(e){this.options=e,this.websocketServer=e.portRange?new xK({portRange:e.portRange,tlsCertificate:e.tlsCertificate,maxMessageSize:e.maxMessageSize,enableTls:e.serverEnableTls}):void 0,this.host=e.host}async start(){if(!this.abortController.signal.aborted&&this.websocketServer){if(this.websocketServer.on("connected",(e=>{const t=e,r=new URLSearchParams(t.resourceURL.query??"").get("action");var n,i;VK.trace("WebSocket client connected",{action:r,remoteAddress:t.getRemoteIpAddress()}),"connectivityRequest"===r?(n=t,i=this.geoIpLocator,n.on("data",(async e=>{jK.trace("server received data");try{const t=Hq.fromBinary(e);if("connectivityRequest"===t.body.oneofKind){jK.trace("ConnectivityRequest received: "+JSON.stringify(Hq.toJson(t)));try{await qK(n,t.body.connectivityRequest,i),jK.trace("handleIncomingConnectivityRequest ok")}catch(e){jK.error("handleIncomingConnectivityRequest",{err:e})}}}catch(e){jK.trace("Could not parse message",{err:e})}}))):"connectivityProbe"===r||(void 0!==this.localPeerDescriptor?this.attachHandshaker(e):(VK.trace("incoming Websocket connection before localPeerDescriptor was set, closing connection"),e.close(!1).catch((()=>{}))))})),this.options.geoIpDatabaseFolder)try{this.geoIpLocator=await(()=>{throw new Error("GeoIpLocator is not supported in browser environment")})(this.options.geoIpDatabaseFolder)}catch(e){VK.error("Failed to start GeoIpLocator",{err:e})}const e=await this.websocketServer.start();this.selectedPort=e}}attachHandshaker(e){const t=new aK(this.localPeerDescriptor,e);t.once("handshakeRequest",((r,n,i)=>{this.onServerSocketHandshakeRequest(r,e,t,n,i)}))}onServerSocketHandshakeRequest(e,t,r,n,i){const s=Xj(e);if(this.ongoingConnectRequests.has(s)){const{pendingConnection:e,delFunc:o}=this.ongoingConnectRequests.get(s);eK(n)?i&&!eq(this.localPeerDescriptor,i)?(sK(e,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR),o()):oK(r,e,t):(sK(e,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION),o())}else{const s=new uK(e);eK(n)?i&&!eq(this.localPeerDescriptor,i)?sK(s,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR):this.options.onNewConnection(s)?oK(r,s,t):sK(s,t,r,Eq.DUPLICATE_CONNECTION):sK(s,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION)}}async checkConnectivity(e){if(this.abortController.signal.aborted)return{host:"127.0.0.1",natType:Wz.UNKNOWN,ipAddress:mE("127.0.0.1"),protocolVersion:Xz};if(!this.options.entrypoints||0===this.options.entrypoints.length)return{host:this.host,natType:Wz.OPEN_INTERNET,websocket:{host:this.host,port:this.selectedPort,tls:void 0!==this.options.tlsCertificate},ipAddress:mE("127.0.0.1"),protocolVersion:Xz};const t=JU(this.options.entrypoints);for(;t.length>0&&!this.abortController.signal.aborted;){const r=t[0];try{const t={port:this.selectedPort??0,host:this.host,tls:!!this.websocketServer&&this.options.serverEnableTls,allowSelfSignedCertificate:e};if(this.abortController.signal.aborted)throw new oq("ConnectivityChecker is destroyed");return await UK(t,r)}catch(e){const n=`Failed to connect to entrypoint with id ${Xj(r)} and URL ${NK(r.websocket)}`;VK.error(n,{err:e}),t.shift(),await Qv(2e3,this.abortController.signal)}}throw new aq(`Failed to connect to the entrypoints after ${this.options.entrypoints.length} attempts\nAttempted hosts: ${this.options.entrypoints.map((e=>`${e.websocket.host}:${e.websocket.port}`)).join(", ")}`)}async autoCertify(){this.autoCertifierClient=new DK({configFile:this.options.autoCertifierConfigFile,transport:this.options.autoCertifierTransport,url:this.options.autoCertifierUrl,wsServerPort:this.selectedPort,setHost:e=>this.setHost(e),updateCertificate:(e,t)=>this.websocketServer.updateCertificate(e,t)}),VK.trace("AutoCertifying subdomain..."),await this.autoCertifierClient.start()}setHost(e){VK.trace(`Setting host name to ${e}`),this.host=e}connect(e){const t=Xj(e);return this.ongoingConnectRequests.has(t)?this.ongoingConnectRequests.get(t).pendingConnection:this.requestConnectionFromPeer(this.localPeerDescriptor,e)}requestConnectionFromPeer(e,t){setImmediate((()=>{new GK(e,t,this.options.rpcCommunicator,Ez).requestConnection().then((()=>{VK.trace("Sent WebsocketConnectionRequest notification to peer",{targetPeerDescriptor:t})}),(e=>{VK.debug("Failed to send WebsocketConnectionRequest notification to peer ",{error:e,targetPeerDescriptor:t})}))}));const r=new uK(t),n=Xj(t),i=()=>{r.off("connected",i),r.off("disconnected",i),this.ongoingConnectRequests.delete(n)};return r.on("connected",i),r.on("disconnected",i),this.ongoingConnectRequests.set(n,{pendingConnection:r,delFunc:i}),r}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_SERVER}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.ongoingConnectRequests.values()).forEach((e=>e.pendingConnection.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}const $K=new Bv("ConnectorFacade");class WK{options;localPeerDescriptor;websocketConnectorRpcCommunicator;websocketClientConnector;websocketServerConnector;webrtcConnector;constructor(e){this.options=e}async start(e,t,r){$K.trace("Creating WebsocketConnectorRpcLocal"),this.websocketConnectorRpcCommunicator=new lK(MK.WEBSOCKET_CONNECTOR_SERVICE_ID,this.options.transport,{rpcRequestTimeout:15e3});const n={onNewConnection:e,hasConnection:t,rpcCommunicator:this.websocketConnectorRpcCommunicator};this.websocketClientConnector=new MK(n);const i={rpcCommunicator:this.websocketConnectorRpcCommunicator,onNewConnection:e,hasConnection:t,portRange:this.options.websocketPortRange,host:this.options.websocketHost,entrypoints:this.options.entryPoints,tlsCertificate:this.options.tlsCertificate,serverEnableTls:this.options.websocketServerEnableTls,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,autoCertifierTransport:r,maxMessageSize:this.options.maxMessageSize,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder};this.websocketServerConnector=new HK(i),this.webrtcConnector=new RK({onNewConnection:e,transport:this.options.transport,iceServers:this.options.iceServers,allowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,bufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,bufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,externalIp:this.options.externalIp,portRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize}),await this.websocketServerConnector.start();const s=!this.options.tlsCertificate&&!0===this.options.websocketServerEnableTls,o=await this.websocketServerConnector.checkConnectivity(s),a=await this.options.createLocalPeerDescriptor(o);if(this.setLocalPeerDescriptor(a),a.websocket&&!this.options.tlsCertificate&&this.options.websocketServerEnableTls)try{await this.websocketServerConnector.autoCertify();const e=await this.websocketServerConnector.checkConnectivity(!1),t=await this.options.createLocalPeerDescriptor(e);void 0!==t.websocket?this.setLocalPeerDescriptor(t):($K.warn("Connectivity check failed after auto-certification, disabling WebSocket server TLS"),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1}))}catch(e){$K.warn("Failed to auto-certify, disabling WebSocket server TLS",{err:e}),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1})}}setLocalPeerDescriptor(e){this.localPeerDescriptor=e,this.websocketServerConnector.setLocalPeerDescriptor(e),this.websocketClientConnector.setLocalPeerDescriptor(e),this.webrtcConnector.setLocalPeerDescriptor(e)}async restartWebsocketServerConnector(e){await this.websocketServerConnector.destroy(),this.websocketServerConnector=new HK(e),await this.websocketServerConnector.start();const t=await this.websocketServerConnector.checkConnectivity(!1),r=await this.options.createLocalPeerDescriptor(t);this.setLocalPeerDescriptor(r)}createConnection(e){return this.websocketClientConnector.isPossibleToFormConnection(e)?this.websocketClientConnector.connect(e):this.websocketServerConnector.isPossibleToFormConnection(e)?this.websocketServerConnector.connect(e):this.webrtcConnector.connect(e,!1)}getLocalPeerDescriptor(){return this.localPeerDescriptor}async stop(){this.websocketConnectorRpcCommunicator.destroy(),await this.websocketServerConnector.destroy(),await this.websocketClientConnector.destroy(),await this.webrtcConnector.stop()}}function JK(e){const t=Buffer.alloc(4);return t.writeUInt32BE(e),t}const QK=new TE,ZK=async(e,t,r)=>{const n=so(32),i=so(20);let s;s=void 0!==r?Yj(r):await(async(e,t)=>{const r=Buffer.alloc(4);r.writeUInt32BE(e);const n=QK.keccakHash(r),i=await QK.createSignature(r,t);return Buffer.concat([n.subarray(n.length-13,n.length),i.subarray(i.length-7,i.length)])})(e.ipAddress,n);const o={nodeId:s,type:bq.BROWSER,ipAddress:e.ipAddress,region:t,publicKey:i};return e.websocket&&(o.websocket={host:e.websocket.host,port:e.websocket.port,tls:e.websocket.tls}),o.signature=await QK.createSignature((e=>{const t=Buffer.from(","),r=[void 0!==e.type?JK(e.type):new Uint8Array(0),t,void 0!==e.udp?Uq.toBinary(e.udp):new Uint8Array(0),t,void 0!==e.tcp?Uq.toBinary(e.tcp):new Uint8Array(0),t,void 0!==e.websocket?Uq.toBinary(e.websocket):new Uint8Array(0),t,void 0!==e.region?JK(e.region):new Uint8Array(0),t,void 0!==e.ipAddress?JK(e.ipAddress):new Uint8Array(0),t,void 0!==e.publicKey?Buffer.from(e.publicKey):new Uint8Array(0)];return Buffer.concat(r)})(o),n),o};class YK{peerDescriptor;constructor(e){this.peerDescriptor=e}getPeerDescriptor(){return this.peerDescriptor}getNodeId(){return Xj(this.peerDescriptor)}}const XK=(e,t,r)=>{const n=new rq({referenceId:e,allowToContainReferenceId:!0,excludedNodeIds:r?.excludedNodeIds,maxSize:r?.maxCount});for(const e of t)n.addContact(new YK(e));return n.getClosestContacts().map((e=>e.getPeerDescriptor()))},eG=new Bv("DhtNodeRpcLocal");class tG{options;constructor(e){this.options=e}async getClosestPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);return{peers:XK(Zj(e.nodeId),this.options.getNeighbors(),{maxCount:this.options.peerDiscoveryQueryBatchSize}),requestId:e.requestId}}async getClosestRingPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);const r=this.options.getClosestRingContactsTo(e.ringId,this.options.peerDiscoveryQueryBatchSize);return{leftPeers:r.left,rightPeers:r.right,requestId:e.requestId}}async ping(e,t){eG.trace("received ping request: "+Xj(t.incomingSourceDescriptor)),setImmediate((()=>{this.options.addContact(t.incomingSourceDescriptor)}));return{requestId:e.requestId}}async leaveNotice(e){const t=e.incomingSourceDescriptor,r=Xj(t);return eG.trace("received leave notice: "+r),this.options.removeContact(r),{}}}const rG=new Bv("DhtNodeRpcRemote");class nG extends jz{static counter=0;vectorClock;id;serviceId;constructor(e,t,r,n,i){super(e,t,n,mz,i),this.id=this.getPeerDescriptor().nodeId,this.vectorClock=nG.counter++,this.serviceId=r}async getClosestPeers(e){rG.trace(`Requesting getClosestPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={nodeId:Yj(e),requestId:xF()};try{return(await this.getClient().getClosestPeers(t,this.formDhtRpcOptions())).peers}catch(e){throw rG.trace(`getClosestPeers error ${this.serviceId}`,{err:e}),e}}async getClosestRingPeers(e){rG.trace(`Requesting getClosestRingPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={ringId:e,requestId:xF()};try{const e=await this.getClient().getClosestRingPeers(t,this.formDhtRpcOptions());return{left:e.leftPeers??[],right:e.rightPeers??[]}}catch(e){throw rG.trace(`getClosestRingPeers error ${this.serviceId}`,{err:e}),e}}async ping(){rG.trace(`Requesting ping on ${this.serviceId} from ${this.getNodeId()}`);const e={requestId:xF()},t=this.formDhtRpcOptions();try{if((await this.getClient().ping(e,t)).requestId===e.requestId)return!0}catch(e){rG.trace(`ping failed on ${this.serviceId} to ${this.getNodeId()}`,{err:e})}return!1}leaveNotice(){rG.trace(`Sending leaveNotice on ${this.serviceId} from ${this.getNodeId()}`);const e=this.formDhtRpcOptions({notification:!0});this.getClient().leaveNotice({},e).catch((e=>{rG.trace("Failed to send leaveNotice"+e)}))}getNodeId(){return Xj(this.getPeerDescriptor())}}class iG{options;constructor(e){this.options=e}async externalFetchData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.key),yq.FETCH_DATA,Xj(r));return iz.create({entries:n.dataEntries??[]})}async externalStoreData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.storeDataToDht(Zj(e.key),e.data,Xj(r));return Cq.create({storers:n})}async externalFindClosestNodes(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.nodeId),yq.FIND_CLOSEST_NODES,Xj(r));return oz.create({closestNodes:n.closestNodes})}}const sG=1e4;class oG extends jz{async externalFetchData(e){const t={key:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFetchData(t,r)).entries}catch{return[]}}async storeData(e,t){const r={key:Yj(e),data:t},n=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalStoreData(r,n)).storers}catch{return[]}}async externalFindClosestNode(e){const t={nodeId:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFindClosestNodes(t,r)).closestNodes}catch{return[]}}}class aG extends Sl{contactsById=new Map;contactIds=[];localNodeId;maxSize;constructor(e,t){super(),this.localNodeId=e,this.maxSize=t}getContact(e){return this.contactsById.get(e)}getSize(){return this.contactIds.length}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}}class cG extends aG{randomness;constructor(e,t,r=.2){super(e,t),this.randomness=r}addContact(e){if(this.localNodeId!==e.getNodeId()&&!this.contactsById.has(e.getNodeId())){if(Math.random()<this.randomness){if(this.getSize()===this.maxSize&&this.getSize()>0){const e=this.contactIds[0];this.removeContact(e)}this.contactIds.push(e.getNodeId()),this.contactsById.set(e.getNodeId(),e),this.emit("contactAdded",e)}}}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.emit("contactRemoved",t),!0}return!1}getContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}}const uG=2**120-1,lG=e=>e.reduce(((e,t)=>e<<BigInt(8)|BigInt(t)),BigInt(0)),hG=e=>Number(lG(e)),dG=e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e.region??0,0);const r=Buffer.alloc(4);r.writeUInt32BE(e.ipAddress??0,0);const n=[t,r,Buffer.from(e.nodeId.subarray(e.nodeId.length-7,e.nodeId.length))],i=Buffer.concat(n);return new Uint8Array(i)},fG=e=>{const t=dG(e);return Number(lG(t))},pG=(e,t)=>{const r=Math.abs(e-t);return e>t?r:uG-r},gG=(e,t)=>{const r=Math.abs(e-t);return e>t?uG-r:r};class mG extends Sl{numNeighborsPerSide=5;referenceId;excludedIds;leftNeighbors;rightNeighbors;constructor(e,t){super(),this.referenceId=hG(e),this.excludedIds=t??new Set,this.leftNeighbors=new cj,this.rightNeighbors=new cj}addContact(e){const t=fG(e.getPeerDescriptor());if(t===this.referenceId||this.excludedIds.has(Xj(e.getPeerDescriptor())))return;let r=!1,n=!1;const i=pG(this.referenceId,t),s=this.leftNeighbors.back();(void 0===s||i<s[0])&&(this.leftNeighbors.setElement(i,e),r=!0,this.leftNeighbors.size()>this.numNeighborsPerSide&&(this.leftNeighbors.eraseElementByIterator(this.leftNeighbors.rBegin()),n=!0));const o=gG(this.referenceId,t),a=this.rightNeighbors.back();(void 0===a||o<a[0])&&(this.rightNeighbors.setElement(o,e),r=!0,this.rightNeighbors.size()>this.numNeighborsPerSide&&(this.rightNeighbors.eraseElementByIterator(this.rightNeighbors.rBegin()),n=!0)),this.hasEventListeners()&&(r||n)&&(r&&this.emit("contactAdded",e),n&&this.emit("contactRemoved",e))}removeContact(e){if(void 0===e)return;const t=fG(e.getPeerDescriptor()),r=pG(this.referenceId,t),n=gG(this.referenceId,t);let i=!1;this.leftNeighbors.eraseElementByKey(r)&&(i=!0),this.rightNeighbors.eraseElementByKey(n)&&(i=!0),this.hasEventListeners()&&i&&this.emit("contactRemoved",e)}getContact(e){const t=fG(e),r=pG(this.referenceId,t),n=gG(this.referenceId,t);return this.leftNeighbors.getElementByKey(r)?this.leftNeighbors.getElementByKey(r):this.rightNeighbors.getElementByKey(n)?this.rightNeighbors.getElementByKey(n):void 0}getClosestContacts(e){const t=[],r=[];let n=0;for(const r of this.leftNeighbors){if(null!=e&&n>=e)break;t.push(r[1]),n++}let i=0;for(const t of this.rightNeighbors){if(null!=e&&i>=e)break;r.push(t[1]),i++}return{left:t,right:r}}getAllContacts(){const e=[];for(const t of this.leftNeighbors)e.push(t[1]);for(const t of this.rightNeighbors)e.push(t[1]);return e}hasEventListeners(){return this.eventNames().length>0}}const yG=new Bv("PeerManager");class bG extends Sl{neighbors;nearbyContacts;activeContacts;ringContacts;randomContacts;stopped=!1;options;constructor(e){super(),this.options=e,this.neighbors=new yL({localNodeId:Yj(this.options.localNodeId),numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,numberOfNodesToPing:this.options.numberOfNodesPerKBucket}),this.ringContacts=new mG(dG(this.options.localPeerDescriptor)),this.ringContacts.on("contactAdded",(e=>{this.emit("ringContactAdded",e.getPeerDescriptor())})),this.ringContacts.on("contactRemoved",(e=>{this.emit("ringContactRemoved",e.getPeerDescriptor())})),this.neighbors.on("ping",((e,t)=>this.onKBucketPing(e,t))),this.neighbors.on("removed",(e=>this.onKBucketRemoved(Xj(e.getPeerDescriptor())))),this.neighbors.on("added",(e=>this.onKBucketAdded(e))),this.neighbors.on("updated",(()=>{})),this.nearbyContacts=new rq({referenceId:this.options.localNodeId,maxSize:this.options.maxContactCount,allowToContainReferenceId:!1}),this.nearbyContacts.on("contactRemoved",(e=>{this.stopped||(this.emit("nearbyContactRemoved",e.getPeerDescriptor()),this.randomContacts.addContact(this.options.createDhtNodeRpcRemote(e.getPeerDescriptor())))})),this.nearbyContacts.on("contactAdded",(e=>this.emit("nearbyContactAdded",e.getPeerDescriptor()))),this.activeContacts=new Set,this.randomContacts=new cG(this.options.localNodeId,this.options.maxContactCount),this.randomContacts.on("contactRemoved",(e=>this.emit("randomContactRemoved",e.getPeerDescriptor()))),this.randomContacts.on("contactAdded",(e=>this.emit("randomContactAdded",e.getPeerDescriptor())))}onKBucketPing(e,t){if(this.stopped)return;const r=new rq({referenceId:this.options.localNodeId,allowToContainReferenceId:!1});r.addContacts(e);const n=r.getFurthestContacts(1)[0].getNodeId();this.options.connectionLocker?.weakUnlockConnection(n,this.options.lockId),this.neighbors.remove(Yj(n)),this.neighbors.add(t)}onKBucketRemoved(e){this.stopped||(this.options.connectionLocker?.weakUnlockConnection(e,this.options.lockId),yG.trace(`Removed contact ${e}`),0===this.neighbors.count()&&this.emit("kBucketEmpty"))}onKBucketAdded(e){if(!this.stopped&&e.getNodeId()!==this.options.localNodeId){const t=e.getPeerDescriptor(),r=Xj(t);this.options.connectionLocker?.weakLockConnection(r,this.options.lockId),this.options.hasConnection(e.getNodeId())||void 0!==this.options.neighborPingLimit&&this.neighbors.count()>this.options.neighborPingLimit?yG.trace(`Added new contact ${r}`):(yG.trace("starting ping "+r),e.ping().then((e=>{e?yG.trace(`Added new contact ${r}`):(yG.trace("ping failed "+r),this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors())})).catch((e=>{this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors()})))}}addNearbyContactToNeighbors(){if(this.stopped)return;const e=this.getNearbyActiveContactNotInNeighbors();e&&this.addContact(e.getPeerDescriptor())}getNearbyActiveContactNotInNeighbors(){for(const e of this.nearbyContacts.getContactIds())if(!this.neighbors.get(Yj(e))&&this.activeContacts.has(e))return this.nearbyContacts.getContact(e)}removeContact(e){this.stopped||(yG.trace(`Removing contact ${e}`),this.ringContacts.removeContact(this.nearbyContacts.getContact(e)),this.neighbors.remove(Yj(e)),this.nearbyContacts.removeContact(e),this.activeContacts.delete(e),this.randomContacts.removeContact(e))}removeNeighbor(e){this.neighbors.remove(Yj(e))}async pruneOfflineNodes(e){yG.trace("Pruning offline nodes",{nodes:e.length});const t=await(async(e,t)=>{const r=[];return await Promise.allSettled(e.map((async e=>{await e.ping()?t.add(e.getNodeId()):(t.delete(e.getNodeId()),r.push(e.getPeerDescriptor()))}))),r})(e,this.activeContacts);t.forEach((e=>{yG.trace("Removing offline node",{node:Xj(e)}),this.removeContact(Xj(e))}))}stop(){this.stopped=!0,this.neighbors.toArray().forEach((e=>{e.leaveNotice(),this.neighbors.remove(e.id)})),this.neighbors.removeAllListeners(),this.ringContacts.getAllContacts().forEach((e=>{e.leaveNotice(),this.ringContacts.removeContact(e)})),this.nearbyContacts.stop(),this.randomContacts.stop()}getNearbyContacts(){return this.nearbyContacts}getClosestRingContactsTo(e,t,r){const n=new mG(e,r);return this.ringContacts.getAllContacts().map((e=>n.addContact(e))),n.getClosestContacts(t??8)}getRandomContacts(){return this.randomContacts}getRingContacts(){return this.ringContacts}getNearbyContactCount(e){return this.nearbyContacts.getSize(e)}getNeighborCount(){return this.neighbors.count()}getNeighbors(){return this.neighbors.toArray()}setContactActive(e){this.activeContacts.add(e)}addContact(e){if(this.stopped)return;const t=Xj(e);if(t!==this.options.localNodeId){yG.trace(`Adding new contact ${t}`);const r=this.options.createDhtNodeRpcRemote(e),n=null!==this.neighbors.get(e.nodeId),i=void 0!==this.nearbyContacts.getContact(t),s=void 0!==this.ringContacts.getContact(e);(n||i)&&this.randomContacts.addContact(r),n||this.neighbors.add(r),i||this.nearbyContacts.addContact(r),s||this.ringContacts.addContact(r)}}}const wG=new Bv("DiscoverySession");class vG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;constructor(e){this.options=e}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestNeighborsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return[];const t=Xj(e);wG.trace(`Getting closest neighbors from remote: ${t}`),this.options.contactedPeers.add(t);const r=this.options.createDhtNodeRpcRemote(e),n=await r.getClosestPeers(this.options.targetId);return this.options.peerManager.setContactActive(t),n}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=Yj(this.options.targetId),n=this.getClosestNeighbor(),i=Qj(r,n.nodeId);this.addContacts(t);const s=this.getClosestNeighbor();Qj(r,s.nodeId)>=i&&this.noProgressCounter++}getClosestNeighbor(){return XK(this.options.targetId,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:1})[0]}onRequestFailed(e){this.ongoingRequests.has(e)&&(this.ongoingRequests.delete(e),this.options.peerManager.removeContact(e))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=XK(this.options.targetId,Array.from(this.options.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder(),(e=>e.getPeerDescriptor())),{maxCount:this.options.parallelism,excludedNodeIds:this.options.contactedPeers});if(0===e.length&&0===this.ongoingRequests.size||this.noProgressCounter>=this.options.noProgressLimit)this.doneGate.open();else for(const t of e){if(this.ongoingRequests.size>=this.options.parallelism)break;const e=Xj(t);this.ongoingRequests.add(e),this.fetchClosestNeighborsFromRemote(t).then((t=>this.onRequestSucceeded(e,t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const EG=new Bv("RingDiscoverySession");class AG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;numContactedPeers=0;targetIdAsRingId;constructor(e){this.options=e,this.targetIdAsRingId=hG(this.options.targetId)}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestContactsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return{left:[],right:[]};EG.trace(`Getting closest ring peers from contact: ${Xj(e.getPeerDescriptor())}`),this.numContactedPeers++,this.options.contactedPeers.add(e.getNodeId());const t=await e.getClosestRingPeers(this.options.targetId);return this.options.peerManager.setContactActive(e.getNodeId()),t}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),n=pG(this.targetIdAsRingId,fG(r.left[0].getPeerDescriptor())),i=pG(this.targetIdAsRingId,fG(r.right[0].getPeerDescriptor()));this.addContacts(t.left.concat(t.right));const s=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),o=pG(this.targetIdAsRingId,fG(s.left[0].getPeerDescriptor())),a=pG(this.targetIdAsRingId,fG(s.right[0].getPeerDescriptor()));o>=n&&a>=i&&this.noProgressCounter++}onRequestFailed(e){this.ongoingRequests.has(e.getNodeId())&&(this.ongoingRequests.delete(e.getNodeId()),this.options.peerManager.removeContact(e.getNodeId()))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,this.options.parallelism,this.options.contactedPeers);if(0===e.left.length&&0===e.right.length||this.noProgressCounter>=this.options.noProgressLimit)return void this.doneGate.open();const t=[],r=new Set,n=Math.max(e.left.length,e.right.length);for(let i=0;i<n;i++)i<e.left.length&&(r.has(e.left[i].getNodeId())||(t.push(e.left[i]),r.add(e.left[i].getNodeId()))),i<e.right.length&&(r.has(e.right[i].getNodeId())||(t.push(e.right[i]),r.add(e.right[i].getNodeId())));for(const e of t){if(this.ongoingRequests.size>=this.options.parallelism)break;this.ongoingRequests.add(e.getNodeId()),this.fetchClosestContactsFromRemote(e).then((t=>this.onRequestSucceeded(e.getNodeId(),t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const SG="layer0",kG=new Bv("PeerDiscovery");class RG{ongoingDiscoverySessions=new Map;ongoingRingDiscoverySessions=new Map;rejoinOngoing=!1;joinCalled=!1;recoveryIntervalStarted=!1;options;constructor(e){this.options=e}async joinDht(e,t=!0,r=!0){const n=new Set,i=t?{enabled:!0,contactedPeers:new Set}:{enabled:!1};await Promise.all(e.map((e=>this.joinThroughEntryPoint(e,n,i,r))))}async joinThroughEntryPoint(e,t,r,n=!0){if(this.isStopped())return;if(this.joinCalled=!0,kG.debug("Joining "+(this.options.serviceId===SG?"The Streamr Network":`Control Layer for ${this.options.serviceId}`)+` via entrypoint ${Xj(e)}`),eq(e,this.options.localPeerDescriptor))return;this.options.connectionLocker?.lockConnection(e,`${this.options.serviceId}::joinDht`),this.options.peerManager.addContact(e);const i=Xj(this.options.localPeerDescriptor),s=[this.createSession(i,t)];r.enabled&&s.push(this.createSession((e=>{const t=Yj(e).map((e=>~e));return Zj(t)})(i),r.contactedPeers)),await this.runSessions(s,e,n),this.options.connectionLocker?.unlockConnection(e,`${this.options.serviceId}::joinDht`)}async joinRing(){const e=new Set,t=[this.createRingSession(dG(this.options.localPeerDescriptor),e)];await this.runRingSessions(t)}createSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new vG(r)}createRingSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new AG(r)}async runSessions(e,t,r){try{for(const t of e)this.ongoingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`DHT join on ${this.options.serviceId} timed out`)}finally{this.isStopped()||(0===this.options.peerManager.getNeighborCount()?r&&Yy((()=>this.rejoinDht(t)),1e3,this.options.abortSignal):await this.ensureRecoveryIntervalIsRunning()),e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async runRingSessions(e){try{for(const t of e)this.ongoingRingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`Ring join on ${this.options.serviceId} timed out`)}finally{e.forEach((e=>this.ongoingRingDiscoverySessions.delete(e.id)))}}async rejoinDht(e,t=new Set,r=new Set){if(!this.isStopped()&&!this.rejoinOngoing){kG.debug(`Rejoining DHT ${this.options.serviceId}`),this.rejoinOngoing=!0;try{await this.joinThroughEntryPoint(e,t,{enabled:!0,contactedPeers:r}),kG.debug(`Rejoined DHT successfully ${this.options.serviceId}!`)}catch{kG.warn(`Rejoining DHT ${this.options.serviceId} failed`),this.isStopped()||Yy((()=>this.rejoinDht(e)),5e3,this.options.abortSignal)}finally{this.rejoinOngoing=!1}}}async ensureRecoveryIntervalIsRunning(){this.recoveryIntervalStarted||(this.recoveryIntervalStarted=!0,await Jv((()=>this.fetchClosestAndRandomNeighbors()),6e4,!0,this.options.abortSignal))}async fetchClosestAndRandomNeighbors(){if(this.isStopped())return;const e=Xj(this.options.localPeerDescriptor),t=this.getClosestNeighbors(e,this.options.parallelism),r=this.getClosestNeighbors(tq(),1);await Promise.allSettled([...t.map((async t=>{const r=this.options.createDhtNodeRpcRemote(t),n=await r.getClosestPeers(e);for(const e of n)this.options.peerManager.addContact(e)})),...r.map((async e=>{const t=this.options.createDhtNodeRpcRemote(e),r=await t.getClosestPeers(tq());for(const e of r)this.options.peerManager.addContact(e)}))])}getClosestNeighbors(e,t){return XK(e,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:t})}isJoinOngoing(){return!this.joinCalled||this.ongoingDiscoverySessions.size>0}isJoinCalled(){return this.joinCalled}isStopped(){return this.options.abortSignal.aborted}}const CG=e=>bj(e.routingPath),IG=new Bv("RouterRpcRemote");class PG extends jz{async routeMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const n=await this.getClient().routeMessage(t,r);if(n.error===vq.DUPLICATE&&yw(e.target,this.getPeerDescriptor().nodeId))return!0;if(void 0!==n.error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send routeMessage from ${n} to ${i}`,{err:t}),!1}return!0}async forwardMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{if(void 0!==(await this.getClient().forwardMessage(t,r)).error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send forwardMessage from ${n} to ${i}`,{err:t}),!1}return!0}}const TG=new Bv("RecursiveOperationRpcRemote");class _G extends jz{async routeRequest(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const e=await this.getClient().routeRequest(t,r);if(void 0!==e.error)return TG.trace("Next hop responded with error "+e.error),!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return TG.debug(`Failed to send routeRequest message from ${n} to ${i}`,{err:t}),!1}return!0}}const NG=new Bv("RoutingSession");class MG extends YK{routerRpcRemote;recursiveOperationRpcRemote;constructor(e,t,r){super(e),this.routerRpcRemote=new PG(t,e,r,yz,2e3),this.recursiveOperationRpcRemote=new _G(t,e,r,bz,2e3)}getRouterRpcRemote(){return this.routerRpcRemote}getRecursiveOperationRpcRemote(){return this.recursiveOperationRpcRemote}}var xG;!function(e){e[e.ROUTE=0]="ROUTE",e[e.FORWARD=1]="FORWARD",e[e.RECURSIVE=2]="RECURSIVE"}(xG||(xG={}));class OG extends Sl{sessionId=xF();ongoingRequests=new Set;contactedPeers=new Set;failedHopCounter=0;successfulHopCounter=0;stopped=!1;options;constructor(e){super(),this.options=e}onRequestFailed(e){if(NG.trace("onRequestFailed() sessionId: "+this.sessionId),this.stopped)return;if(this.ongoingRequests.has(e)&&this.ongoingRequests.delete(e),this.deleteParallelRootIfSource(e),this.failedHopCounter+=1,this.failedHopCounter>=2)return NG.trace(`Stopping routing after 2 failed attempts for sessionId: ${this.sessionId}`),void this.emitFailure();const t=this.updateAndGetRoutablePeers();0===t.length&&0===this.ongoingRequests.size?(NG.trace("routing failed, emitting routingFailed sessionId: "+this.sessionId),this.emitFailure()):(NG.trace("routing failed, retrying to route sessionId: "+this.sessionId+" failedHopCounter: "+this.failedHopCounter),this.sendMoreRequests(t))}emitFailure(){this.successfulHopCounter>=1?this.emit("partialSuccess"):this.emit("routingFailed")}onRequestSucceeded(){if(NG.trace("onRequestSucceeded() sessionId: "+this.sessionId),this.stopped)return;if(this.successfulHopCounter+=1,this.successfulHopCounter>=this.options.parallelism)return void this.emit("routingSucceeded");const e=this.updateAndGetRoutablePeers();0===e.length?this.emit("routingSucceeded"):e.length>0&&0===this.ongoingRequests.size&&this.sendMoreRequests(e)}async sendRouteMessageRequest(e){if(this.stopped)return!1;const t={...this.options.routedMessage,routingPath:this.options.routedMessage.routingPath.concat([this.options.localPeerDescriptor])};return this.options.mode===xG.FORWARD?e.getRouterRpcRemote().forwardMessage(t):this.options.mode===xG.RECURSIVE?e.getRecursiveOperationRpcRemote().routeRequest(t):e.getRouterRpcRemote().routeMessage(t)}updateAndGetRoutablePeers(){NG.trace("getRoutablePeers() sessionId: "+this.sessionId);const e=CG(this.options.routedMessage),t=e?Xj(e):void 0,r=Zj(this.options.routedMessage.target);let n;if(this.options.routingTablesCache.has(r,t)&&this.options.routingTablesCache.get(r,t).getSize()>0)n=this.options.routingTablesCache.get(r,t);else{n=new rq({referenceId:Zj(this.options.routedMessage.target),maxSize:5,allowToContainReferenceId:!0,nodeIdDistanceLimit:t});const e=this.options.getConnections().map((e=>new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator)));n.addContacts(e),this.options.routingTablesCache.set(r,n,t)}return n.getClosestContacts().filter((e=>!this.contactedPeers.has(e.getNodeId())&&!this.options.excludedNodeIds.has(e.getNodeId())))}sendMoreRequests(e){if(NG.trace("sendMoreRequests() sessionId: "+this.sessionId),!this.stopped)if(0!==e.length)for(;this.ongoingRequests.size<this.options.parallelism&&e.length>0&&!this.stopped;){const t=e.shift();NG.trace(`Sending routeMessage request to contact: ${Xj(t.getPeerDescriptor())} (sessionId=${this.sessionId})`),this.contactedPeers.add(t.getNodeId()),this.ongoingRequests.add(t.getNodeId()),this.addParallelRootIfSource(t.getNodeId()),setImmediate((async()=>{try{await this.sendRouteMessageRequest(t)?this.onRequestSucceeded():this.onRequestFailed(t.getNodeId())}catch(e){NG.debug("Unable to route message ",{err:e})}finally{NG.trace("sendRouteMessageRequest returned")}}))}else this.emitFailure()}addParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&this.options.routedMessage.parallelRootNodeIds.push(e)}deleteParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&Ej(this.options.routedMessage.parallelRootNodeIds,e)}stop(){this.stopped=!0,this.emit("stopped"),this.removeAllListeners()}}const DG=new Bv("RecursiveOperationSessionRpcRemote");class BG extends jz{sendResponse(e,t,r,n){const i={routingPath:e,closestConnectedNodes:t,dataEntries:r,noCloserNodesFound:n};this.getClient().sendResponse(i,this.formDhtRpcOptions()).catch((e=>{DG.trace("Failed to send RecursiveOperationResponse")}))}}const LG=new Bv("RecursiveOperationSessionRpcLocal");class FG{options;constructor(e){this.options=e}async sendResponse(e,t){const r=Xj(t.incomingSourceDescriptor);return LG.trace("RecursiveOperationResponse arrived: "+JSON.stringify(e)),this.options.onResponseReceived(r,e.routingPath,e.closestConnectedNodes,e.dataEntries,e.noCloserNodesFound),{}}}const UG=1e4;class jG extends Sl{id=xF();rpcCommunicator;results;foundData=new Map;allKnownHops=new Set;reportedHops=new Set;timeoutTask;completionEventEmitted=!1;noCloserNodesReceivedCounter=0;noCloserNodesReceivedFrom=new Set;options;constructor(e){super(),this.options=e,this.results=new rq({referenceId:e.targetId,maxSize:10,allowToContainReferenceId:!0}),this.rpcCommunicator=new lK(this.id,e.transport,{rpcRequestTimeout:UG}),this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new FG({onResponseReceived:(e,t,r,n,i)=>{this.onResponseReceived(e,t,r,n,i)}});this.rpcCommunicator.registerRpcNotification(Oq,"sendResponse",((t,r)=>e.sendResponse(t,r)))}start(e){const t=this.wrapRequest(e);this.options.doRouteRequest(t)}wrapRequest(e){const t={sessionId:this.getId(),operation:this.options.operation};return{message:{messageId:xF(),serviceId:e,body:{oneofKind:"recursiveOperationRequest",recursiveOperationRequest:t}},requestId:xF(),target:Yj(this.options.targetId),sourcePeer:this.options.localPeerDescriptor,reachableThrough:[],routingPath:[],parallelRootNodeIds:[]}}isCompleted(){const e=new Set(this.allKnownHops);return this.reportedHops.forEach((t=>{e.delete(t)})),this.noCloserNodesReceivedCounter>=1&&0===e.size&&(!(this.options.operation!==yq.FETCH_DATA||!(this.hasNonStaleData()||this.noCloserNodesReceivedCounter>=this.options.waitedRoutingPathCompletions))||this.options.operation!==yq.FETCH_DATA)}hasNonStaleData(){return Array.from(this.foundData.values()).some((e=>!1===e.stale))}onResponseReceived(e,t,r,n,i){this.addKnownHops(t),t.length>=1&&this.setHopAsReported(t[t.length-1]),r.forEach((e=>{this.results.addContact(new YK(e))})),this.processFoundData(n),(i||this.noCloserNodesReceivedFrom.has(e))&&this.onNoCloserPeersFound(e)}addKnownHops(e){const t=Xj(this.options.localPeerDescriptor);e.forEach((e=>{const r=Xj(e);t!==r&&this.allKnownHops.add(r)}))}setHopAsReported(e){const t=Xj(this.options.localPeerDescriptor),r=Xj(e);t!==r&&this.reportedHops.add(r),this.isCompleted()&&!this.completionEventEmitted&&this.isCompleted()&&(this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.emit("completed"),this.completionEventEmitted=!0)}processFoundData(e){e.forEach((e=>{const t=Zj(e.creator),r=this.foundData.get(t);(!r||r.createdAt<e.createdAt||r.createdAt<=e.createdAt&&e.deleted)&&this.foundData.set(t,e)}))}onNoCloserPeersFound(e){this.noCloserNodesReceivedCounter+=1,this.noCloserNodesReceivedFrom.add(e),this.isCompleted()?(this.emit("completed"),this.completionEventEmitted=!0,this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0)):this.timeoutTask||this.completionEventEmitted||(this.timeoutTask=setTimeout((()=>{this.completionEventEmitted||(this.emit("completed"),this.completionEventEmitted=!0)}),4e3))}getResults(){return{closestNodes:this.results.getClosestContacts().map((e=>e.getPeerDescriptor())),dataEntries:Array.from(this.foundData.values())}}getId(){return this.id}stop(){this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.rpcCommunicator.destroy(),this.emit("completed")}}const qG=new Bv("RouterRpcLocal"),zG=(e,t)=>({requestId:e.requestId,error:t});class KG{options;constructor(e){this.options=e}async routeMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?(qG.trace(`routing message targeted to self ${e.requestId}`),this.options.setForwardingEntries(e),this.options.handleMessage(e.message),zG(e)):this.options.doRouteMessage(e))}async forwardMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Forwarding message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received forward routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?this.forwardToDestination(e):this.options.doRouteMessage(e,xG.FORWARD))}forwardToDestination(e){qG.trace(`Forwarding found message targeted to self ${e.requestId}`);const t=e.message;return eq(this.options.localPeerDescriptor,t.targetDescriptor)?(this.options.handleMessage(t),zG(e)):this.options.doRouteMessage({...e,requestId:xF(),target:t.targetDescriptor.nodeId})}}const GG=new Bv("RecursiveOperationRpcLocal");class VG{options;constructor(e){this.options=e}async routeRequest(e){if(this.options.isMostLikelyDuplicate(e.requestId))return zG(e,vq.DUPLICATE);const t=Xj(CG(e)??e.sourcePeer);return GG.trace(`Received routeRequest call from ${t}`),this.options.addToDuplicateDetector(e.requestId),this.options.doRouteRequest(e)}}const HG=new Bv("RecursiveOperationManager");class $G{ongoingSessions=new Map;stopped=!1;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new VG({doRouteRequest:e=>this.doRouteRequest(e),addContact:e=>this.options.addContact(e),isMostLikelyDuplicate:e=>this.options.router.isMostLikelyDuplicate(e),addToDuplicateDetector:e=>this.options.router.addToDuplicateDetector(e)});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeRequest",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeRequest(t)))}async execute(e,t,r,n=!0){if(this.stopped)return{closestNodes:[]};const i=new jG({transport:this.options.sessionTransport,targetId:e,localPeerDescriptor:this.options.localPeerDescriptor,waitedRoutingPathCompletions:this.options.connectionsView.getConnectionCount()>1?2:1,operation:t,doRouteRequest:e=>this.doRouteRequest(e,r)});if(0===this.options.connectionsView.getConnectionCount()){const t=Array.from(this.options.localDataStore.values(e));return i.onResponseReceived(Xj(this.options.localPeerDescriptor),[this.options.localPeerDescriptor],[this.options.localPeerDescriptor],t,!0),i.getResults()}if(this.ongoingSessions.set(i.getId(),i),!0===n)try{const e=eE(i,"completed",UG);i.start(this.options.serviceId),await e}catch(e){HG.debug("start failed",{err:e})}else i.start(this.options.serviceId),await Qv(50);if(t===yq.FETCH_DATA){const t=Array.from(this.options.localDataStore.values(e));t.length>0&&this.sendResponse([this.options.localPeerDescriptor],this.options.localPeerDescriptor,i.getId(),[],t,!0)}else t===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(e,Xj(this.options.localPeerDescriptor));return this.ongoingSessions.delete(i.getId()),i.stop(),i.getResults()}sendResponse(e,t,r,n,i,s=!1){if(eq(this.options.localPeerDescriptor,t)&&this.ongoingSessions.has(r))this.ongoingSessions.get(r).onResponseReceived(Xj(this.options.localPeerDescriptor),e,n,i,s);else{const o=new lK(r,this.options.sessionTransport,{rpcRequestTimeout:UG});new BG(this.options.localPeerDescriptor,t,o,vz,1e4).sendResponse(e,n,i,s),o.destroy()}}doRouteRequest(e,t){if(this.stopped)return zG(e,vq.STOPPED);const r=Zj(e.target),n=e.message.body.recursiveOperationRequest,i=this.getClosestConnectedNodes(r,5),s=n.operation===yq.FETCH_DATA?Array.from(this.options.localDataStore.values(r)):[];if(n.operation===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(r,Xj(e.sourcePeer)),yw(this.options.localPeerDescriptor.nodeId,e.target))return this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,!0),zG(e);{const o=this.options.router.doRouteMessage(e,xG.RECURSIVE,t);if(void 0===o.error||o.error===vq.NO_TARGETS){const t=o.error===vq.NO_TARGETS||i.length>0&&CG(e)&&!this.isPeerCloserToIdThanSelf(i[0],r);this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,t)}return o}}getClosestConnectedNodes(e,t){const r=this.options.connectionsView.getConnections().map((e=>this.options.createDhtNodeRpcRemote(e))),n=new rq({referenceId:e,maxSize:t,allowToContainReferenceId:!0});return n.addContacts(r),n.getClosestContacts(t).map((e=>e.getPeerDescriptor()))}isPeerCloserToIdThanSelf(e,t){const r=Yj(t);return Qj(e.nodeId,r)<Qj(this.options.localPeerDescriptor.nodeId,r)}stop(){this.stopped=!0,this.ongoingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingSessions.clear()}}const WG=(e,t)=>e+(t??""),JG={max:1e3,maxAge:15e3};class QG{tables=new Mj(JG);get(e,t){return this.tables.get(WG(e,t))}set(e,t,r){this.tables.set(WG(e,r),t)}has(e,t){return this.tables.has(WG(e,t))}onNodeDisconnected(e){this.tables.forEach((t=>t.removeContact(e)))}onNodeConnected(e){this.tables.forEach((t=>t.addContact(e)))}reset(){this.tables.forEach((e=>e.stop())),this.tables.clear()}}const ZG=new Bv("Router");class YG{forwardingTable=new Map;routingTablesCache=new QG;ongoingRoutingSessions=new Map;duplicateRequestDetector=new nq(1e4);stopped=!1;options;messagesRouted=0;messagesSent=0;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new KG({doRouteMessage:(e,t)=>this.doRouteMessage(e,t),setForwardingEntries:e=>this.setForwardingEntries(e),duplicateRequestDetector:this.duplicateRequestDetector,localPeerDescriptor:this.options.localPeerDescriptor,handleMessage:this.options.handleMessage});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeMessage(t))),this.options.rpcCommunicator.registerRpcMethod(jq,qq,"forwardMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.forwardMessage(t)))}send(e,t){e.sourceDescriptor=this.options.localPeerDescriptor;const r=e.targetDescriptor,n=this.forwardingTable.get(Xj(r));if(n&&n.peerDescriptors.length>0){const r={message:e,requestId:xF(),target:n.peerDescriptors[0].nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(r,xG.FORWARD);if(void 0!==i.error){const e="Could not forward message with error "+i.error;throw ZG.debug(e),new Error(e)}}else{const n={message:e,requestId:xF(),target:r.nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(n,xG.ROUTE);if(void 0!==i.error){const e="Could not route message with error "+i.error;throw ZG.debug(e),new Error(e)}}this.messagesSent+=1}doRouteMessage(e,t=xG.ROUTE,r){if(this.stopped)return zG(e,vq.STOPPED);ZG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)}`);const n=this.createRoutingSession(e,t,r),i=n.updateAndGetRoutablePeers();if(i.length>0){this.addRoutingSession(n),ZG.trace("starting to raceForEvent from routingSession: "+n.sessionId);const t=tE(n,["routingSucceeded","partialSuccess","routingFailed","stopped"],1e4);return setImmediate((async()=>{try{await t,ZG.trace("raceForEvent ended from routingSession: "+n.sessionId)}catch{ZG.trace("raceForEvent timed out for routingSession "+n.sessionId)}n.stop(),this.removeRoutingSession(n.sessionId)})),n.sendMoreRequests(i),this.messagesRouted+=1,zG(e)}return ZG.trace("no targets",{sessionId:n.sessionId}),zG(e,vq.NO_TARGETS)}createRoutingSession(e,t,r){const n=new Set(e.routingPath.map((e=>Xj(e))));return r&&n.add(r),e.parallelRootNodeIds.forEach((e=>{n.add(e)})),new OG({rpcCommunicator:this.options.rpcCommunicator,localPeerDescriptor:this.options.localPeerDescriptor,routedMessage:e,parallelism:eq(this.options.localPeerDescriptor,e.sourcePeer)?2:1,mode:t,excludedNodeIds:n,routingTablesCache:this.routingTablesCache,getConnections:this.options.getConnections})}isMostLikelyDuplicate(e){return this.duplicateRequestDetector.isMostLikelyDuplicate(e)}addToDuplicateDetector(e){this.duplicateRequestDetector.add(e)}addRoutingSession(e){this.ongoingRoutingSessions.set(e.sessionId,e)}removeRoutingSession(e){this.ongoingRoutingSessions.delete(e)}onNodeConnected(e){const t=new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator);this.routingTablesCache.onNodeConnected(t)}onNodeDisconnected(e){this.routingTablesCache.onNodeDisconnected(Xj(e))}resetCache(){this.routingTablesCache.reset()}stop(){this.stopped=!0,this.ongoingRoutingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingRoutingSessions.clear(),this.forwardingTable.forEach((e=>{clearTimeout(e.timeout)})),this.forwardingTable.clear(),this.duplicateRequestDetector.clear(),this.routingTablesCache.reset()}getDiagnosticInfo(){return{messagesRouted:this.messagesRouted,messagesSent:this.messagesSent}}setForwardingEntries(e){const t=e.reachableThrough.filter((e=>!eq(e,this.options.localPeerDescriptor)));if(t.length>0){const r=Xj(e.sourcePeer);if(this.forwardingTable.has(r)){const e=this.forwardingTable.get(r);clearTimeout(e.timeout),this.forwardingTable.delete(r)}const n={peerDescriptors:t,timeout:setTimeout((()=>{this.forwardingTable.delete(r)}),1e4)};this.forwardingTable.set(r,n)}}}class XG{maxTtl;constructor(e){this.maxTtl=e}store=new Map;storeEntry(e){const t=Zj(e.key),r=Zj(e.creator);if(this.store.has(t)||this.store.set(t,new yE((e=>Math.min(e.ttl,this.maxTtl)))),this.store.get(t).has(r)){const n=1e3*e.createdAt.seconds+e.createdAt.nanos/1e6,i=this.store.get(t).get(r);if(1e3*i.createdAt.seconds+i.createdAt.nanos/1e6>=n)return!1}return this.store.get(t).set(r,e),!0}markAsDeleted(e,t){const r=this.store.get(e);if(!r?.has(t))return!1;return r.get(t).deleted=!0,!0}*values(e){if(void 0!==e){const t=this.store.get(e);void 0!==t&&(yield*t.values())}else for(const e of this.store.values())yield*e.values()}keys(){return this.store.keys()}setAllEntriesAsStale(e){this.store.get(e)?.forEach((e=>{e.stale=!0}))}deleteEntry(e,t){const r=this.store.get(e)?.get(t);r&&(this.store.get(e)?.delete(t),0===this.store.get(e)?.size()&&this.store.delete(e))}clear(){this.store.forEach((e=>e.clear())),this.store.clear()}}const eV=new Bv("StoreRpcLocal");class tV{options;constructor(e){this.options=e}async storeData(e){eV.trace("storeData()");const t=Zj(e.key),r=this.isLocalNodeStorer(t);return this.options.localDataStore.storeEntry({key:e.key,data:e.data,creator:e.creator,createdAt:e.createdAt,storedAt:mq.now(),ttl:e.ttl,stale:!r,deleted:!1}),r||this.options.localDataStore.setAllEntriesAsStale(t),{}}async replicateData(e,t){eV.trace("server-side replicateData()");const r=e.entry;this.options.localDataStore.storeEntry(r)&&this.replicateDataToNeighbors(t.incomingSourceDescriptor,e.entry);const n=Zj(r.key);return this.isLocalNodeStorer(n)||this.options.localDataStore.setAllEntriesAsStale(n),eV.trace("server-side replicateData() at end"),{}}isLocalNodeStorer(e){return this.options.getStorers(e).some((e=>eq(e,this.options.localPeerDescriptor)))}replicateDataToNeighbors(e,t){const r=Zj(t.key),n=this.options.getStorers(r);(eq(n[0],this.options.localPeerDescriptor)?n:[n[0]]).filter((t=>!eq(t,e)&&!eq(t,this.options.localPeerDescriptor))).forEach((e=>{setImmediate((()=>{pE((()=>this.options.replicateDataToContact(t,e)))}))}))}}const rV=new Bv("StoreManager");class nV{options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new tV({localPeerDescriptor:this.options.localPeerDescriptor,localDataStore:this.options.localDataStore,replicateDataToContact:(e,t)=>this.replicateDataToContact(e,t),getStorers:e=>this.getStorers(e)});this.options.rpcCommunicator.registerRpcMethod(Sq,kq,"storeData",(t=>e.storeData(t))),this.options.rpcCommunicator.registerRpcNotification(Iq,"replicateData",((t,r)=>e.replicateData(t,r)))}onContactAdded(e){for(const t of this.options.localDataStore.keys())this.replicateAndUpdateStaleState(t,e)}replicateAndUpdateStaleState(e,t){const r=this.getStorers(e),n=r.filter((e=>!eq(e,t)));eq(n[0],this.options.localPeerDescriptor)?r.some((e=>eq(e,t)))&&setImmediate((async()=>{const r=Array.from(this.options.localDataStore.values(e));await Promise.all(r.map((async e=>this.replicateDataToContact(e,t))))})):r.some((e=>eq(e,this.options.localPeerDescriptor)))||this.options.localDataStore.setAllEntriesAsStale(e)}async replicateDataToContact(e,t){const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!0)}catch(e){rV.trace("replicateData() threw an exception "+e)}}async storeDataToDht(e,t,r){rV.debug(`Storing data to DHT ${this.options.serviceId}`);const n=(await this.options.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes,i=[],s=this.options.highestTtl,o=mq.now();for(let a=0;a<n.length&&i.length<this.options.redundancyFactor;a++){const c=Yj(e),u=Yj(r);if(eq(this.options.localPeerDescriptor,n[a])){this.options.localDataStore.storeEntry({key:c,data:t,creator:u,createdAt:o,storedAt:mq.now(),ttl:s,stale:!1,deleted:!1}),i.push(n[a]);continue}const l=this.options.createRpcRemote(n[a]);try{await l.storeData({key:c,data:t,creator:u,createdAt:o,ttl:s}),i.push(n[a]),rV.trace("remote.storeData() success")}catch(e){rV.trace("remote.storeData() threw an exception "+e)}}return i}async replicateDataToClosestNodes(){const e=Array.from(this.options.localDataStore.values());await Promise.all(e.map((async e=>{const t=Zj(e.key),r=XK(t,this.options.getNeighbors(),{maxCount:this.options.redundancyFactor});await Promise.all(r.map((async t=>{const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!1)}catch(e){rV.trace("Failed to replicate data in replicateDataToClosestNodes",{err:e})}})))})))}getStorers(e,t){return XK(e,[...this.options.getNeighbors(),this.options.localPeerDescriptor],{maxCount:this.options.redundancyFactor,excludedNodeIds:void 0!==t?new Set([Xj(t)]):void 0})}async destroy(){await this.replicateDataToClosestNodes()}}class iV extends jz{async storeData(e){const t=this.formDhtRpcOptions();try{await this.getClient().storeData(e,t)}catch(e){const t=Xj(this.getPeerDescriptor()),r=Xj(this.getLocalPeerDescriptor());throw new Error(`Could not store data to ${t} from ${r} ${e}`)}}async replicateData(e,t){const r=this.formDhtRpcOptions({timeout:Fz,notification:!0,connect:t});return this.getClient().replicateData(e,r)}}const sV=new Bv("DhtNode");class oV extends Sl{options;rpcCommunicator;transport;localPeerDescriptor;router;storeManager;localDataStore;recursiveOperationManager;peerDiscovery;peerManager;connectionsView;connectionLocker;started=!1;abortController=new AbortController;constructor(e){super(),this.options=aE({serviceId:SG,joinParallelism:3,maxContactCount:200,numberOfNodesPerKBucket:8,joinNoProgressLimit:5,dhtJoinTimeout:6e4,peerDiscoveryQueryBatchSize:5,maxConnections:80,storeHighestTtl:6e4,storeMaxTtl:6e4,networkConnectivityTimeout:1e4,storageRedundancyFactor:5,metricsContext:new $v},e),this.validateOptions(),this.localDataStore=new XG(this.options.storeMaxTtl),this.send=this.send.bind(this)}validateOptions(){if(void 0!==this.options.nodeId){if(!/^[0-9a-fA-F]+$/.test(this.options.nodeId))throw new Error("Invalid nodeId, the nodeId should be a hex string");if(40!==this.options.nodeId.length)throw new Error("Invalid nodeId, the length of the nodeId should be 40")}if(void 0!==this.options.peerDescriptor&&20!==this.options.peerDescriptor.nodeId.length)throw new Error("Invalid peerDescriptor, the length of the nodeId should be 20 bytes");if(void 0!==this.options.transport&&void 0===this.options.connectionsView)throw new Error("connectionsView is required when transport is given")}async start(){if(this.started||this.abortController.signal.aborted)return;if(sV.trace(`Starting new Streamr Network DHT Node with serviceId ${this.options.serviceId}`),this.started=!0,this.options.websocketPortRange=void 0,this.options.peerDescriptor&&(this.options.peerDescriptor.websocket=void 0),this.options.transport)this.transport=this.options.transport,this.connectionsView=this.options.connectionsView,this.connectionLocker=this.options.connectionLocker,this.localPeerDescriptor=this.transport.getLocalPeerDescriptor();else{const e={transport:this,entryPoints:this.options.entryPoints,iceServers:this.options.iceServers,webrtcAllowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,webrtcDatachannelBufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,webrtcDatachannelBufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,webrtcPortRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize,websocketServerEnableTls:this.options.websocketServerEnableTls,tlsCertificate:this.options.tlsCertificate,externalIp:this.options.externalIp,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder,createLocalPeerDescriptor:e=>this.generatePeerDescriptorCallBack(e)};this.options.peerDescriptor?.websocket?(e.websocketHost=this.options.peerDescriptor.websocket.host,e.websocketPortRange={min:this.options.peerDescriptor.websocket.port,max:this.options.peerDescriptor.websocket.port}):this.options.websocketPortRange&&(e.websocketHost=this.options.websocketHost,e.websocketPortRange=this.options.websocketPortRange);const t=new Yz({createConnectorFacade:()=>new WK(e),maxConnections:this.options.maxConnections,metricsContext:this.options.metricsContext,allowIncomingPrivateConnections:this.options.allowIncomingPrivateConnections??!1});await t.start(),this.connectionsView=t,this.connectionLocker=t,this.transport=t}this.rpcCommunicator=new Iz(this.options.serviceId,((e,t)=>this.transport.send(e,t)),{rpcRequestTimeout:this.options.rpcRequestTimeout}),oE(this.transport,"message",(e=>this.handleMessageFromTransport(e)),this.abortController.signal),this.initPeerManager(),this.peerDiscovery=new RG({localPeerDescriptor:this.localPeerDescriptor,joinNoProgressLimit:this.options.joinNoProgressLimit,joinTimeout:this.options.dhtJoinTimeout,serviceId:this.options.serviceId,parallelism:this.options.joinParallelism,connectionLocker:this.connectionLocker,peerManager:this.peerManager,abortSignal:this.abortController.signal,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.router=new YG({rpcCommunicator:this.rpcCommunicator,localPeerDescriptor:this.localPeerDescriptor,handleMessage:e=>this.handleMessageFromRouter(e),getConnections:()=>this.connectionsView.getConnections()}),this.recursiveOperationManager=new $G({rpcCommunicator:this.rpcCommunicator,router:this.router,sessionTransport:this,connectionsView:this.connectionsView,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,localDataStore:this.localDataStore,addContact:e=>this.peerManager.addContact(e),createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.storeManager=new nV({rpcCommunicator:this.rpcCommunicator,recursiveOperationManager:this.recursiveOperationManager,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,highestTtl:this.options.storeHighestTtl,redundancyFactor:this.options.storageRedundancyFactor,localDataStore:this.localDataStore,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),createRpcRemote:e=>new iV(this.localPeerDescriptor,e,this.rpcCommunicator,wz,this.options.rpcRequestTimeout)}),this.on("nearbyContactAdded",(e=>{this.storeManager.onContactAdded(e)})),this.bindRpcLocalMethods();const e=[];!0===this.options.periodicallyPingNeighbors&&e.push((()=>this.peerManager.getNeighbors().map((e=>this.createDhtNodeRpcRemote(e.getPeerDescriptor()))))),!0===this.options.periodicallyPingRingContacts&&e.push((()=>this.peerManager.getRingContacts().getAllContacts()));for(const t of e)await Jv((async()=>{const e=t();await this.peerManager.pruneOfflineNodes(e)}),6e4,!1,this.abortController.signal)}initPeerManager(){this.peerManager=new bG({numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,maxContactCount:this.options.maxContactCount,localNodeId:this.getNodeId(),localPeerDescriptor:this.localPeerDescriptor,connectionLocker:this.connectionLocker,lockId:this.options.serviceId,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e),hasConnection:e=>this.connectionsView.hasConnection(e),neighborPingLimit:this.options.neighborPingLimit}),this.peerManager.on("nearbyContactRemoved",(e=>{this.emit("nearbyContactRemoved",e)})),this.peerManager.on("nearbyContactAdded",(e=>this.emit("nearbyContactAdded",e))),this.peerManager.on("randomContactRemoved",(e=>this.emit("randomContactRemoved",e))),this.peerManager.on("randomContactAdded",(e=>this.emit("randomContactAdded",e))),this.peerManager.on("ringContactRemoved",(e=>{this.emit("ringContactRemoved",e)})),this.peerManager.on("ringContactAdded",(e=>{this.emit("ringContactAdded",e)})),this.peerManager.on("kBucketEmpty",(()=>{this.peerDiscovery.isJoinOngoing()||(this.options.entryPoints&&this.options.entryPoints.length>0?setImmediate((async()=>{const e=new Set,t=new Set;await Promise.all(this.options.entryPoints.map((r=>this.peerDiscovery.rejoinDht(r,e,t))))})):this.emit("manualRejoinRequired"))})),oE(this.transport,"connected",(e=>{this.router.onNodeConnected(e),this.emit("connected",e)}),this.abortController.signal),oE(this.transport,"disconnected",((e,t)=>{if(void 0!==this.connectionLocker){const r=Xj(e);t?this.peerManager.removeContact(r):this.peerManager.removeNeighbor(r)}this.router.onNodeDisconnected(e),this.emit("disconnected",e,t)}),this.abortController.signal)}bindRpcLocalMethods(){if(!this.started||this.abortController.signal.aborted)return;const e=new tG({peerDiscoveryQueryBatchSize:this.options.peerDiscoveryQueryBatchSize,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),getClosestRingContactsTo:(e,t)=>this.getClosestRingContactsTo(e,t),addContact:e=>this.peerManager.addContact(e),removeContact:e=>this.removeContact(e)});this.rpcCommunicator.registerRpcMethod(Tq,_q,"getClosestPeers",((t,r)=>e.getClosestPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Nq,Mq,"getClosestRingPeers",((t,r)=>e.getClosestRingPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Dq,Bq,"ping",((t,r)=>e.ping(t,r))),this.rpcCommunicator.registerRpcNotification(Lq,"leaveNotice",((t,r)=>e.leaveNotice(r)));const t=new iG({executeRecursiveOperation:(e,t,r)=>this.recursiveOperationManager.execute(e,t,r),storeDataToDht:(e,t,r)=>this.storeDataToDht(e,t,r)});this.rpcCommunicator.registerRpcMethod(nz,iz,"externalFetchData",((e,r)=>t.externalFetchData(e,r)),{timeout:1e4}),this.rpcCommunicator.registerRpcMethod(Rq,Cq,"externalStoreData",((e,r)=>t.externalStoreData(e,r)),{timeout:1e4})}handleMessageFromTransport(e){e.serviceId===this.options.serviceId&&this.rpcCommunicator?.handleMessageFromPeer(e)}handleMessageFromRouter(e){e.serviceId===this.options.serviceId?this.rpcCommunicator?.handleMessageFromPeer(e):this.emit("message",e)}async generatePeerDescriptorCallBack(e){if(void 0!==this.options.peerDescriptor)this.localPeerDescriptor=this.options.peerDescriptor;else{let t;void 0!==this.options.region?(t=this.options.region,sV.debug(`Using region ${t} from options when generating local PeerDescriptor`)):void 0!==e.latitude&&void 0!==e.longitude?(t=((e,t)=>{const r=[];return Object.keys(Lj).forEach((n=>{const i=Lj[n],s=Bj({latitude:e,longitude:t},{latitude:i[1],longitude:i[2]});r.push([i[0],s])})),r.sort(((e,t)=>e[1]-t[1])),r[0][0]})(e.latitude,e.longitude),sV.debug(`Using region ${t} from GeoIP when generating local PeerDescriptor`)):(t=await(async(e=36e5)=>{if(void 0===zj||void 0===Kj||Date.now()-Kj>e){const e=await Gj();return zj=e,Kj=Date.now(),e}return zj})(),sV.debug(`Using region ${t} from CDN when generating local PeerDescriptor`)),this.localPeerDescriptor=await ZK(e,t,this.options.nodeId)}return this.localPeerDescriptor}getClosestContacts(e){return this.peerManager.getNearbyContacts().getClosestContacts(e).map((e=>e.getPeerDescriptor()))}getRandomContacts(e){return this.peerManager.getRandomContacts().getContacts(e).map((e=>e.getPeerDescriptor()))}getRingContacts(){const e=this.peerManager.getRingContacts().getClosestContacts();return{left:e.left.map((e=>e.getPeerDescriptor())),right:e.right.map((e=>e.getPeerDescriptor()))}}getClosestRingContactsTo(e,t){const r=this.peerManager.getClosestRingContactsTo(e,t);return{left:r.left.map((e=>e.getPeerDescriptor())),right:r.right.map((e=>e.getPeerDescriptor()))}}getNodeId(){return Xj(this.localPeerDescriptor)}getNeighborCount(){return this.peerManager.getNeighborCount()}removeContact(e){this.started&&this.peerManager.removeContact(e)}async send(e){if(!this.started||this.abortController.signal.aborted)return;const t=this.peerDiscovery.isJoinOngoing()?this.getConnectedEntryPoints():[];this.router.send(e,t)}getConnectedEntryPoints(){return void 0!==this.options.entryPoints?this.options.entryPoints.filter((e=>this.connectionsView.hasConnection(Xj(e)))):[]}async joinDht(e,t,r){if(!this.started)throw new Error("Cannot join DHT before calling start() on DhtNode");await this.peerDiscovery.joinDht(e,t,r)}async joinRing(){if(!this.started)throw new Error("Cannot join ring before calling start() on DhtNode");await this.peerDiscovery.joinRing()}async storeDataToDht(e,t,r){return this.executeRecursiveOperation((()=>this.storeManager.storeDataToDht(e,t,r??this.getNodeId())),(r=>this.storeDataToDhtViaPeer(e,t,r)))}async storeDataToDhtViaPeer(e,t,r){const n=new oG(this.localPeerDescriptor,r,this.rpcCommunicator,kz);return await n.storeData(e,t)}async fetchDataFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FETCH_DATA)).dataEntries??[]),(t=>this.fetchDataFromDhtViaPeer(e,t)))}async fetchDataFromDhtViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFetchData(e)}async executeRecursiveOperation(e,t){const r=this.getConnectedEntryPoints();return this.peerDiscovery.isJoinOngoing()&&r.length>0?t(oA(r)):e()}async deleteDataFromDht(e,t){this.abortController.signal.aborted||await this.recursiveOperationManager.execute(e,yq.DELETE_DATA,void 0,t)}async findClosestNodesFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes),(t=>this.findClosestNodesViaPeer(e,t)))}async findClosestNodesViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFindClosestNode(e)}getTransport(){return this.transport}getLocalPeerDescriptor(){return this.localPeerDescriptor}getNeighbors(){return this.started?this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())):[]}getConnectionsView(){return this.connectionsView}getLocalLockedConnectionCount(){return this.connectionLocker.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.connectionLocker.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.connectionLocker.getWeakLockedConnectionCount()}async waitForNetworkConnectivity(){await iE((()=>this.connectionsView.getConnectionCount()>0),this.options.networkConnectivityTimeout,100,this.abortController.signal)}hasJoined(){return this.peerDiscovery.isJoinCalled()}getDiagnosticInfo(){return{localPeerDescriptor:this.localPeerDescriptor,transport:this.transport.getDiagnosticInfo(),router:this.router.getDiagnosticInfo(),neighborCount:this.getNeighborCount(),nearbyContactCount:Array.from(this.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder()).length,randomContactCount:this.peerManager.getRandomContacts().getSize()}}async stop(){!this.abortController.signal.aborted&&this.started&&(sV.trace("stop()"),this.abortController.abort(),await this.storeManager.destroy(),this.localDataStore.clear(),this.peerManager?.stop(),this.rpcCommunicator.stop(),this.router.stop(),this.recursiveOperationManager.stop(),void 0===this.options.transport&&await this.transport.stop(),this.transport=void 0,this.connectionLocker=void 0,this.removeAllListeners())}createDhtNodeRpcRemote(e){return new nG(this.localPeerDescriptor,e,this.options.serviceId,this.rpcCommunicator,this.options.rpcRequestTimeout)}}var aV,cV,uV,lV,hV,dV,fV,pV,gV,mV;function yV(){if(lV)return uV;return lV=1,uV=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e},uV}!function(e){e[e.eu_central_1=0]="eu_central_1",e[e.eu_west_1=1]="eu_west_1",e[e.eu_west_2=2]="eu_west_2",e[e.eu_west_3=3]="eu_west_3",e[e.eu_north_1=4]="eu_north_1",e[e.us_east_1=5]="us_east_1",e[e.us_east_2=6]="us_east_2",e[e.us_west_1=7]="us_west_1",e[e.us_west_2=8]="us_west_2",e[e.ca_central_1=9]="ca_central_1",e[e.ap_south_1=10]="ap_south_1",e[e.ap_northeast_2=11]="ap_northeast_2",e[e.ap_southeast_1=12]="ap_southeast_1",e[e.ap_southeast_2=13]="ap_southeast_2",e[e.ap_northeast_1=14]="ap_northeast_1",e[e.sa_east_1=15]="sa_east_1"}(aV||(aV={})),new Bv("Simulator"),function(e){e.NONE="NONE",e.RANDOM="RANDOM",e.REAL="REAL",e.FIXED="FIXED"}(cV||(cV={}));var bV=function(){if(mV)return gV;mV=1;var e=function(){if(dV)return hV;dV=1;var e=yV(),t=Th(),r=$U();return hV=function(n,i){return r(t(n),e(i,0,n.length))},hV}(),t=function(){if(pV)return fV;pV=1;var e=yV(),t=$U(),r=nA();return fV=function(n,i){var s=r(n);return t(s,e(i,0,s.length))},fV}(),r=qu(),n=_d(),i=Ue();return gV=function(s,o,a){return o=(a?n(s,o,a):void 0===o)?1:i(o),(r(s)?e:t)(s,o)},gV}(),wV=n(bV);class vV{tail;head;length=0;static create(e=[]){return new vV(e)}constructor(e=[]){for(const t of e)this.push(t)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");const t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,t}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);const t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);const t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let t=0,r=e.length;t<r;t++)AV(this,e[t]);return this.length}unshift(...e){for(var t=0,r=e.length;t<r;t++)SV(this,e[t]);return this.length}pop(){if(!this.tail)return;const e=this.tail.value,t=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,t.list=void 0,this.length--,e}shift(){if(!this.head)return;const e=this.head.value,t=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,t.list=void 0,this.length--,e}forEach(e,t){t=t||this;for(let r=this.head,n=0;r;n++)e.call(t,r.value,n,this),r=r.next}forEachReverse(e,t){t=t||this;for(let r=this.tail,n=this.length-1;r;n--)e.call(t,r.value,n,this),r=r.prev}get(e){let t=0,r=this.head;for(;r&&t<e;t++)r=r.next;if(t===e&&r)return r.value}getReverse(e){let t=0,r=this.tail;for(;r&&t<e;t++)r=r.prev;if(t===e&&r)return r.value}map(e,t){t=t||this;const r=new vV;for(let n=this.head;n;)r.push(e.call(t,n.value,this)),n=n.next;return r}mapReverse(e,t){t=t||this;var r=new vV;for(let n=this.tail;n;)r.push(e.call(t,n.value,this)),n=n.prev;return r}reduce(e,t){let r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;n;i++)r=e(r,n.value,i),n=n.next;return r}reduceReverse(e,t){let r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(let t=this.length-1;n;t--)r=e(r,n.value,t),n=n.prev;return r}toArray(){const e=new Array(this.length);for(let t=0,r=this.head;r;t++)e[t]=r.value,r=r.next;return e}toArrayReverse(){const e=new Array(this.length);for(let t=0,r=this.tail;r;t++)e[t]=r.value,r=r.prev;return e}slice(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.head,i=0;for(i=0;n&&i<e;i++)n=n.next;for(;n&&i<t;i++,n=n.next)r.push(n.value);return r}sliceReverse(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.length,i=this.tail;for(;i&&n>t;n--)i=i.prev;for(;i&&n>e;n--,i=i.prev)r.push(i.value);return r}splice(e,t=0,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let n=this.head;for(let t=0;n&&t<e;t++)n=n.next;const i=[];for(let e=0;n&&e<t;e++)i.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(const e of r)n=EV(this,n,e);return i}reverse(){const e=this.head,t=this.tail;for(let t=e;t;t=t.prev){const e=t.prev;t.prev=t.next,t.next=e}return this.head=t,this.tail=e,this}}function EV(e,t,r){const n=t,i=t?t.next:e.head,s=new kV(r,n,i,e);return void 0===s.next&&(e.tail=s),void 0===s.prev&&(e.head=s),e.length++,s}function AV(e,t){e.tail=new kV(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function SV(e,t){e.head=new kV(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}class kV{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}}class RV{rpcCommunicator;constructor(e){this.rpcCommunicator=new lK("external-network-service",e)}registerRpcMethod(e,t,r,n){this.rpcCommunicator.registerRpcMethod(e,t,r,n)}createRpcClient(e){return iU(new e(this.rpcCommunicator.getRpcClientTransport()))}destroy(){this.rpcCommunicator.destroy()}}const CV=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},IV=new Bv("PeerDescriptorStoreManager");class PV{abortController;options;isLocalNodeStored_=!1;constructor(e){this.options=e,this.abortController=new AbortController}async fetchNodes(){IV.trace("Fetch data",{key:this.options.key});try{const e=await this.options.fetchDataFromDht(this.options.key);return e.filter((e=>!e.deleted)).map((e=>CV.unpack(e.data,Fq)))}catch{return[]}}async storeAndKeepLocalNode(){this.abortController.signal.aborted||(this.isLocalNodeStored_=!0,await this.storeLocalNode(),await this.keepLocalNode())}async storeLocalNode(){const e=this.options.localPeerDescriptor,t=CV.pack(e,Fq);try{await this.options.storeDataToDht(this.options.key,t)}catch{IV.warn("Failed to store local node",{key:this.options.key})}}async keepLocalNode(){await Jv((async()=>{IV.trace("Attempting to keep local node",{key:this.options.key});try{const e=await this.fetchNodes();(e.length<8||e.some((e=>eq(e,this.options.localPeerDescriptor))))&&await this.storeLocalNode()}catch{IV.debug("Failed to keep local node",{key:this.options.key})}}),this.options.storeInterval??6e4,!1,this.abortController.signal)}isLocalNodeStored(){return this.isLocalNodeStored_}async destroy(){this.abortController.abort(),await this.options.deleteDataFromDht(this.options.key,!1)}}const TV=new Bv("StreamPartNetworkSplitAvoidance");class _V{abortController;options;excludedNodes=new Set;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async avoidNetworkSplit(){this.running=!0,await(async(e,t,r,n=500,i=6)=>{for(let s=1;s<=i;s++){if(r.aborted)return;const i=n*2**s;try{await e()}catch{TV.trace(`${t} failed, retrying in ${i} ms`)}try{await Qv(i,r)}catch(e){TV.trace(`${e}`)}}})((async()=>{const e=(await this.options.discoverEntryPoints()).filter((e=>!this.excludedNodes.has(Xj(e))));if(await this.options.discoveryLayerNode.joinDht(e,!1,!1),this.options.discoveryLayerNode.getNeighborCount()<4){throw e.filter((e=>!this.options.discoveryLayerNode.getNeighbors().some((t=>eq(t,e))))).map((e=>Xj(e))).forEach((e=>this.excludedNodes.add(e))),new Error("Network split is still possible")}}),"avoid network split",this.abortController.signal,this.options.exponentialRunOfBaseDelay),this.running=!1,this.excludedNodes.clear(),TV.trace("Network split avoided")}isRunning(){return this.running}destroy(){this.abortController.abort()}}class NV{abortController;discoveryLayerNode;peerDescriptorStoreManager;constructor(e,t){this.discoveryLayerNode=e,this.peerDescriptorStoreManager=t}async reconnect(e=3e4){this.abortController=new AbortController,await Jv((async()=>{const e=await this.peerDescriptorStoreManager.fetchNodes();await this.discoveryLayerNode.joinDht(e),!this.peerDescriptorStoreManager.isLocalNodeStored()&&e.length<8&&await this.peerDescriptorStoreManager.storeAndKeepLocalNode(),this.discoveryLayerNode.getNeighborCount()>0&&this.abortController.abort()}),e,!0,this.abortController.signal)}isRunning(){return!!this.abortController&&!this.abortController.signal.aborted}destroy(){this.abortController?.abort()}}const MV=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var xV;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(xV||(xV={}));const OV=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>CV},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",xV]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>MV}])}};const DV=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var BV,LV,FV,UV,jV,qV;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(BV||(BV={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(LV||(LV={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(FV||(FV={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(UV||(UV={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(jV||(jV={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(qV||(qV={}));const zV=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"ttl",kind:"scalar",T:13}])}};const KV=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const GV=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV}])}};const VV=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>nH}])}};const HV=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>$V}])}};const $V=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"storedAt",kind:"message",T:()=>DV},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const WV=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const JV=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"requestId",kind:"scalar",T:9}])}};const QV=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const ZV=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>nH},{no:3,name:"requestId",kind:"scalar",T:9}])}};const YV=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",BV]}])}};const XV=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>nH},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>$V},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>nH}])}};const eH=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const tH=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const rH=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const nH=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",LV]},{no:3,name:"udp",kind:"message",T:()=>iH},{no:4,name:"tcp",kind:"message",T:()=>iH},{no:5,name:"websocket",kind:"message",T:()=>iH},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const iH=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const sH=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>nH},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>hH},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>nH},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>nH},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const oH=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",UV]}])}};const aH=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const cH=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>iH},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const uH=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>nH},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const lH=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",jV]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const hH=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>nH},{no:3,name:"targetDescriptor",kind:"message",T:()=>nH},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>OV},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>aH},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>cH},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>uH},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>lH},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>YV}])}};const dH=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const fH=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const pH=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const gH=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const mH=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const yH=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const bH=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const wH=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const vH=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",qV]}])}};const EH=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const AH=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const SH=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>$V}])}};const kH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const RH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>nH}])}};var CH,IH,PH,TH,_H;new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:WV,O:JV},{name:"getClosestRingPeers",options:{},I:QV,O:ZV},{name:"ping",options:{},I:eH,O:tH},{name:"leaveNotice",options:{},I:rH,O:MV}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:sH,O:oH},{name:"forwardMessage",options:{},I:sH,O:oH}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:sH,O:oH}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:zV,O:KV},{name:"replicateData",options:{},I:HV,O:MV}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:XV,O:MV}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:dH,O:MV}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:fH,O:MV},{name:"rtcOffer",options:{},I:pH,O:MV},{name:"rtcAnswer",options:{},I:gH,O:MV},{name:"iceCandidate",options:{},I:mH,O:MV}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:yH,O:wH},{name:"unlockRequest",options:{},I:bH,O:MV},{name:"gracefulDisconnect",options:{},I:vH,O:MV},{name:"setPrivate",options:{},I:EH,O:MV}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:AH,O:SH},{name:"externalStoreData",options:{},I:GV,O:VV},{name:"externalFindClosestNodes",options:{},I:kH,O:RH}]),e.ContentType=void 0,(CH=e.ContentType||(e.ContentType={}))[CH.JSON=0]="JSON",CH[CH.BINARY=1]="BINARY",e.EncryptionType=void 0,(IH=e.EncryptionType||(e.EncryptionType={}))[IH.NONE=0]="NONE",IH[IH.AES=1]="AES",function(e){e[e.RSA=0]="RSA",e[e.ML_KEM=1]="ML_KEM"}(PH||(PH={})),e.SignatureType=void 0,(TH=e.SignatureType||(e.SignatureType={}))[TH.ECDSA_SECP256K1_LEGACY=0]="ECDSA_SECP256K1_LEGACY",TH[TH.ECDSA_SECP256K1_EVM=1]="ECDSA_SECP256K1_EVM",TH[TH.ERC_1271=2]="ERC_1271",TH[TH.ML_DSA_87=3]="ML_DSA_87",TH[TH.ECDSA_SECP256R1=4]="ECDSA_SECP256R1",e.ProxyDirection=void 0,(_H=e.ProxyDirection||(e.ProxyDirection={}))[_H.PUBLISH=0]="PUBLISH",_H[_H.SUBSCRIBE=1]="SUBSCRIBE";const NH=new class extends wF{constructor(){super("MessageID",[{no:1,name:"streamId",kind:"scalar",T:9},{no:2,name:"streamPartition",kind:"scalar",T:5},{no:3,name:"timestamp",kind:"scalar",T:3,L:2},{no:4,name:"sequenceNumber",kind:"scalar",T:5},{no:5,name:"publisherId",kind:"scalar",T:12},{no:6,name:"messageChainId",kind:"scalar",T:9}])}};const MH=new class extends wF{constructor(){super("MessageRef",[{no:1,name:"timestamp",kind:"scalar",T:3,L:2},{no:2,name:"sequenceNumber",kind:"scalar",T:5}])}};const xH=new class extends wF{constructor(){super("StreamMessage",[{no:1,name:"messageId",kind:"message",T:()=>NH},{no:2,name:"previousMessageRef",kind:"message",T:()=>MH},{no:3,name:"signature",kind:"scalar",T:12},{no:4,name:"signatureType",kind:"enum",T:()=>["SignatureType",e.SignatureType]},{no:5,name:"contentMessage",kind:"message",oneof:"body",T:()=>OH},{no:6,name:"groupKeyRequest",kind:"message",oneof:"body",T:()=>DH},{no:7,name:"groupKeyResponse",kind:"message",oneof:"body",T:()=>BH}])}};const OH=new class extends wF{constructor(){super("ContentMessage",[{no:1,name:"content",kind:"scalar",T:12},{no:2,name:"contentType",kind:"enum",T:()=>["ContentType",e.ContentType]},{no:3,name:"encryptionType",kind:"enum",T:()=>["EncryptionType",e.EncryptionType]},{no:4,name:"groupKeyId",kind:"scalar",opt:!0,T:9},{no:5,name:"newGroupKey",kind:"message",T:()=>LH}])}};const DH=new class extends wF{constructor(){super("GroupKeyRequest",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"publicKey",kind:"scalar",T:12},{no:4,name:"groupKeyIds",kind:"scalar",repeat:2,T:9},{no:5,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const BH=new class extends wF{constructor(){super("GroupKeyResponse",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"groupKeys",kind:"message",repeat:2,T:()=>LH},{no:4,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const LH=new class extends wF{constructor(){super("EncryptedGroupKey",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12}])}};const FH=new class extends wF{constructor(){super("StreamPartHandshakeRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"concurrentHandshakeNodeId",kind:"scalar",opt:!0,T:12},{no:4,name:"neighborNodeIds",kind:"scalar",repeat:2,T:12},{no:5,name:"interleaveNodeId",kind:"scalar",opt:!0,T:12}])}};const UH=new class extends wF{constructor(){super("StreamPartHandshakeResponse",[{no:1,name:"accepted",kind:"scalar",T:8},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const jH=new class extends wF{constructor(){super("InterleaveRequest",[{no:1,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const qH=new class extends wF{constructor(){super("InterleaveResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const zH=new class extends wF{constructor(){super("LeaveStreamPartNotice",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"isEntryPoint",kind:"scalar",T:8}])}};const KH=new class extends wF{constructor(){super("NeighborUpdate",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"removeMe",kind:"scalar",T:8},{no:3,name:"neighborDescriptors",kind:"message",repeat:2,T:()=>nH}])}};const GH=new class extends wF{constructor(){super("ProxyConnectionRequest",[{no:1,name:"direction",kind:"enum",opt:!0,T:()=>["ProxyDirection",e.ProxyDirection]},{no:2,name:"userId",kind:"scalar",T:12}])}};const VH=new class extends wF{constructor(){super("ProxyConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const HH=new class extends wF{constructor(){super("TemporaryConnectionRequest",[])}};const $H=new class extends wF{constructor(){super("TemporaryConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const WH=new class extends wF{constructor(){super("CloseTemporaryConnection",[])}};const JH=new class extends wF{constructor(){super("StreamPartitionInfo",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"controlLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:3,name:"deprecatedContentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:4,name:"contentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>QH}])}};const QH=new class extends wF{constructor(){super("ContentDeliveryLayerNeighborInfo",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"rtt",kind:"scalar",opt:!0,T:5}])}};const ZH=new class extends wF{constructor(){super("ControlLayerInfo",[{no:1,name:"neighbors",kind:"message",repeat:2,T:()=>nH},{no:2,name:"connections",kind:"message",repeat:2,T:()=>nH}])}};const YH=new class extends wF{constructor(){super("NodeInfoRequest",[])}};const XH=new class extends wF{constructor(){super("NodeInfoResponse",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"streamPartitions",kind:"message",repeat:2,T:()=>JH},{no:3,name:"controlLayer",kind:"message",T:()=>ZH},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const e$=new class extends wF{constructor(){super("PauseNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9}])}};const t$=new class extends wF{constructor(){super("PauseNeighborResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const r$=new class extends wF{constructor(){super("ResumeNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9},{no:2,name:"fromTimestamp",kind:"scalar",T:3,L:2}])}},n$=new vF("ContentDeliveryRpc",[{name:"sendStreamMessage",options:{},I:xH,O:MV},{name:"leaveStreamPartNotice",options:{},I:zH,O:MV}]),i$=new vF("ProxyConnectionRpc",[{name:"requestConnection",options:{},I:GH,O:VH}]),s$=new vF("HandshakeRpc",[{name:"handshake",options:{},I:FH,O:UH},{name:"interleaveRequest",options:{},I:jH,O:qH}]),o$=new vF("NeighborUpdateRpc",[{name:"neighborUpdate",options:{},I:KH,O:KH}]),a$=new vF("TemporaryConnectionRpc",[{name:"openConnection",options:{},I:HH,O:$H},{name:"closeConnection",options:{},I:WH,O:MV}]),c$=new vF("NodeInfoRpc",[{name:"getInfo",options:{},I:YH,O:XH}]),u$=new vF("PlumtreeRpc",[{name:"pauseNeighbor",options:{},I:e$,O:t$},{name:"resumeNeighbor",options:{},I:r$,O:MV},{name:"sendMetadata",options:{},I:NH,O:MV}]);class l${_transport;typeName=n$.typeName;methods=n$.methods;options=n$.options;constructor(e){this._transport=e}sendStreamMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveStreamPartNotice(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class h${_transport;typeName=i$.typeName;methods=i$.methods;options=i$.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class d${_transport;typeName=s$.typeName;methods=s$.methods;options=s$.options;constructor(e){this._transport=e}handshake(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}interleaveRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class f${_transport;typeName=o$.typeName;methods=o$.methods;options=o$.options;constructor(e){this._transport=e}neighborUpdate(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class p${_transport;typeName=a$.typeName;methods=a$.methods;options=a$.options;constructor(e){this._transport=e}openConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}closeConnection(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class g${_transport;typeName=c$.typeName;methods=c$.methods;options=c$.options;constructor(e){this._transport=e}getInfo(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class m${_transport;typeName=u$.typeName;methods=u$.methods;options=u$.options;constructor(e){this._transport=e}pauseNeighbor(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}resumeNeighbor(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}sendMetadata(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const y$=new Bv("ContentDeliveryRpcRemote");class b$ extends jz{rtt;async sendStreamMessage(e,t){const r=this.formDhtRpcOptions({notification:!0,bufferWhileConnecting:t});this.getClient().sendStreamMessage(e,r).catch((()=>{y$.trace("Failed to sendStreamMessage")}))}leaveStreamPartNotice(e,t){const r={streamPartId:e,isEntryPoint:t},n=this.formDhtRpcOptions({notification:!0});this.getClient().leaveStreamPartNotice(r,n).catch((()=>{y$.debug("Failed to send leaveStreamPartNotice")}))}setRtt(e){this.rtt=e}getRtt(){return this.rtt}}const w$=new Bv("HandshakeRpcLocal");class v${options;constructor(e){this.options=e}async handshake(e,t){return this.handleRequest(e,t)}handleRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.ongoingInterleaves.has(n)?this.rejectHandshake(e):this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)||this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?this.acceptHandshake(e,r):this.options.neighbors.size(void 0!==e.interleaveNodeId?[Zj(e.interleaveNodeId)]:[])-this.options.ongoingInterleaves.size>=2&&this.options.neighbors.size()<=this.options.maxNeighborCount?this.acceptHandshakeWithInterleaving(e,r):this.rejectHandshake(e)}acceptHandshake(e,t){const r={requestId:e.requestId,accepted:!0};return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),r}rejectHandshake(e){return{requestId:e.requestId,accepted:!1}}acceptHandshakeWithInterleaving(e,t){const r=[];e.neighborNodeIds.forEach((e=>r.push(Zj(e)))),this.options.ongoingInterleaves.forEach((e=>r.push(e))),r.push(Xj(t)),void 0!==e.interleaveNodeId&&r.push(Zj(e.interleaveNodeId));const n=this.options.neighbors.getLast(r),i=n?n.getPeerDescriptor():void 0;if(n){const e=Xj(n.getPeerDescriptor()),r=this.options.createRpcRemote(n.getPeerDescriptor());this.options.ongoingInterleaves.add(e),r.interleaveRequest(t).then((e=>{e.accepted&&this.options.neighbors.remove(Xj(i))})).catch((()=>{})).finally((()=>{this.options.ongoingInterleaves.delete(e)}))}return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),{requestId:e.requestId,accepted:!0,interleaveTargetDescriptor:i}}async interleaveRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);try{return await this.options.handshakeWithInterleaving(e.interleaveTargetDescriptor,n),this.options.neighbors.remove(n),{accepted:!0}}catch(t){return w$.debug(`interleaveRequest to ${Xj(e.interleaveTargetDescriptor)} failed`,{err:t}),{accepted:!1}}}}const E$=new Bv("HandshakeRpcRemote");class A$ extends jz{async handshake(e,t,r,n){const i={streamPartId:e,requestId:xF(),neighborNodeIds:t.map((e=>Yj(e))),concurrentHandshakeNodeId:void 0!==r?Yj(r):void 0,interleaveNodeId:void 0!==n?Yj(n):void 0};try{const e=await this.getClient().handshake(i,this.formDhtRpcOptions());return{accepted:e.accepted,interleaveTargetDescriptor:e.interleaveTargetDescriptor}}catch(e){return E$.debug(`handshake to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}async interleaveRequest(e){const t={interleaveTargetDescriptor:e},r=this.formDhtRpcOptions({connect:!1,timeout:1e4});try{return{accepted:(await this.getClient().interleaveRequest(t,r)).accepted}}catch(e){return E$.debug(`interleaveRequest to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}}const S$=new Bv("Handshaker");class k${options;rpcLocal;constructor(e){this.options=e,this.rpcLocal=new v$({streamPartId:this.options.streamPartId,neighbors:this.options.neighbors,ongoingHandshakes:this.options.ongoingHandshakes,ongoingInterleaves:new Set,maxNeighborCount:this.options.maxNeighborCount,handshakeWithInterleaving:(e,t)=>this.handshakeWithInterleaving(e,t),createRpcRemote:e=>this.createRpcRemote(e),createContentDeliveryRpcRemote:e=>this.createContentDeliveryRpcRemote(e)}),this.options.rpcCommunicator.registerRpcMethod(jH,qH,"interleaveRequest",((e,t)=>this.rpcLocal.interleaveRequest(e,t)),{timeout:1e4}),this.options.rpcCommunicator.registerRpcMethod(FH,UH,"handshake",((e,t)=>this.rpcLocal.handshake(e,t)))}async attemptHandshakesOnContacts(e){return this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount-2?(S$.trace("Attempting parallel handshakes with 2 targets"),this.selectParallelTargetsAndHandshake(e)):this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?(S$.trace("Attempting handshake with new target"),this.selectNewTargetAndHandshake(e)):e}async selectParallelTargetsAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.selectParallelTargets(t);return r.forEach((e=>this.options.ongoingHandshakes.add(Xj(e.getPeerDescriptor())))),this.doParallelHandshakes(r,t)}selectParallelTargets(e){const t=new Map,r=()=>[...e,...Array.from(t.keys())];if(0===this.options.neighbors.size()){const e=this.options.nearbyNodeView.getFirst(r(),!0);if(e){const r=Xj(e.getPeerDescriptor());t.set(r,e)}}const n=this.options.leftNodeView.getFirst(r()),i=this.options.rightNodeView.getFirst(r());if(n&&t.set(Xj(n.getPeerDescriptor()),n),i&&t.set(Xj(i.getPeerDescriptor()),i),t.size<2){const e=this.options.nearbyNodeView.getFirst(r());e&&t.set(Xj(e.getPeerDescriptor()),e)}for(;t.size<2;){const e=this.options.randomNodeView.getRandom(r());if(!e)break;t.set(Xj(e.getPeerDescriptor()),e)}return Array.from(t.values()).map((e=>this.createRpcRemote(e.getPeerDescriptor())))}async doParallelHandshakes(e,t){return(await Promise.allSettled(Array.from(e.values()).map((async(t,r)=>{const n=0===r?e[1]:e[0],i=n?Xj(n.getPeerDescriptor()):void 0;return this.handshakeWithTarget(t,i)})))).forEach(((r,n)=>{"fulfilled"===r.status&&r.value||t.push(Xj(e[n].getPeerDescriptor()))})),t}async selectNewTargetAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.options.leftNodeView.getFirst(t)??this.options.rightNodeView.getFirst(t)??this.options.nearbyNodeView.getFirst(t)??this.options.randomNodeView.getRandom(t);if(r){await this.handshakeWithTarget(this.createRpcRemote(r.getPeerDescriptor()))||e.push(Xj(r.getPeerDescriptor()))}return e}async handshakeWithTarget(e,t){const r=Xj(e.getPeerDescriptor());this.options.ongoingHandshakes.add(r);const n=await e.handshake(this.options.streamPartId,this.options.neighbors.getIds(),t);return n.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(e.getPeerDescriptor())),n.interleaveTargetDescriptor&&await this.handshakeWithInterleaving(n.interleaveTargetDescriptor,r),this.options.ongoingHandshakes.delete(r),n.accepted}async handshakeWithInterleaving(e,t){const r=this.createRpcRemote(e),n=Xj(r.getPeerDescriptor());this.options.ongoingHandshakes.add(n);const i=await r.handshake(this.options.streamPartId,this.options.neighbors.getIds(),void 0,t);return i.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(r.getPeerDescriptor())),this.options.ongoingHandshakes.delete(n),i.accepted}createRpcRemote(e){return new A$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,d$,this.options.rpcRequestTimeout)}createContentDeliveryRpcRemote(e){return new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)}getOngoingHandshakes(){return this.options.ongoingHandshakes}}const R$=new Bv("NeighborFinder");class C${abortController;options;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async findNeighbors(e){if(!this.running)return;const t=await this.options.doFindNeighbors(e),r=new Set([...this.options.nearbyNodeView.getIds(),...this.options.leftNodeView.getIds(),...this.options.rightNodeView.getIds(),...this.options.randomNodeView.getIds()]).size;this.options.neighbors.size()<this.options.minCount&&t.length<r?Yy((()=>this.findNeighbors(t)),250,this.abortController.signal):0===this.options.neighbors.size()&&r>0?(R$.debug("No neighbors found yet contacts are available, restarting handshaking process"),Yy((()=>this.findNeighbors([])),250,this.abortController.signal)):this.running=!1}isRunning(){return this.running}start(e=[]){this.running||(this.running=!0,Yy((async()=>{await Promise.all([this.findNeighbors(e),this.findNeighbors(e)])}),100,this.abortController.signal))}stop(){this.running&&(this.running=!1,this.abortController.abort())}}class I${options;constructor(e){this.options=e}updateContacts(e){const t=Xj(this.options.localPeerDescriptor);e.filter((e=>{const r=Xj(e);return r!==t&&!this.options.neighbors.getIds().includes(r)})).forEach((e=>this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$))))}createResponse(e){return{streamPartId:this.options.streamPartId,neighborDescriptors:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),removeMe:e}}async neighborUpdate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);if(this.updateContacts(e.neighborDescriptors),this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)){const t=this.options.neighbors.size()>this.options.neighborTargetCount&&e.neighborDescriptors.length>this.options.neighborTargetCount;return t?this.options.neighbors.remove(n):this.options.neighborFinder.start(),this.createResponse(t)}return this.createResponse(!0)}}const P$=new Bv("NeighborUpdateRpcRemote");class T$ extends jz{async updateNeighbors(e,t){const r={streamPartId:e,neighborDescriptors:t,removeMe:!1};try{const e=await this.getClient().neighborUpdate(r,this.formDhtRpcOptions());return{peerDescriptors:e.neighborDescriptors,removeMe:e.removeMe}}catch(e){return P$.debug(`updateNeighbors to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{peerDescriptors:[],removeMe:!0}}}}const _$=new Bv("NeighborUpdateManager");class N${abortController;options;rpcLocal;constructor(e){this.abortController=new AbortController,this.rpcLocal=new I$(e),this.options=e,this.options.rpcCommunicator.registerRpcMethod(KH,KH,"neighborUpdate",((e,t)=>this.rpcLocal.neighborUpdate(e,t)))}async start(){await Jv((()=>this.updateNeighborInfo()),this.options.neighborUpdateInterval,!1,this.abortController.signal)}stop(){this.abortController.abort()}async updateNeighborInfo(){_$.trace("Updating neighbor info to nodes");const e=this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),t=Date.now();await Promise.allSettled(this.options.neighbors.getAll().map((async r=>{const n=await this.createRemote(r.getPeerDescriptor()).updateNeighbors(this.options.streamPartId,e),i=Xj(r.getPeerDescriptor());this.options.neighbors.get(i).setRtt(Date.now()-t),n.removeMe&&(this.options.neighbors.remove(i),this.options.neighborFinder.start([i]))})))}createRemote(e){return new T$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,f$)}}class M${options;constructor(e){this.options=e}async sendStreamMessage(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.markForInspection(n,e.messageId),void 0===this.options.plumtreeManager?this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)&&this.options.broadcast(e,n):this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)?this.options.plumtreeManager.broadcast(e,n):await this.options.plumtreeManager.pauseNeighbor(r,e.messageId.messageChainId),MV}async leaveStreamPartNotice(e,t){if(e.streamPartId===this.options.streamPartId){const r=t.incomingSourceDescriptor,n=Xj(r);this.options.onLeaveNotice(n,e.isEntryPoint)}return MV}}class x${a;b;constructor(e,t){this.a=e,this.b=t}greaterThanOrEqual(e){return this.greaterThan(e)||this.equalTo(e)}greaterThan(e){return 1===this.compareTo(e)}equalTo(e){return 0===this.compareTo(e)}compareTo(e){return this.a>e.a?1:this.a<e.a?-1:this.b>e.b?1:this.b<e.b?-1:0}toString(){return`${this.a}|${this.b}`}}class O$ extends Error{constructor(){super("pre-condition: previousNumber < number")}}class D$ extends Error{constructor(e,t,r){super(`pre-condition: gap overlap in given numbers: previousNumber=${t.toString()}, number=${r.toString()}, state=${e}`)}}class B${maxGapCount;gaps;constructor(e=1e4){this.maxGapCount=e,this.gaps=[]}markAndCheck(e,t){if(e?.greaterThanOrEqual(t))throw new O$;if(0===this.gaps.length)return this.gaps.push([t,new x$(1/0,1/0)]),!0;if(null===e)return!!t.greaterThan(this.gaps[this.gaps.length-1][0])&&(this.gaps[this.gaps.length-1][0]=t,!0);for(let r=this.gaps.length-1;r>=0;--r){const[n,i]=this.gaps[r];if(e.greaterThanOrEqual(i))return!1;if(e.greaterThanOrEqual(n)){if(t.greaterThan(i))throw new D$(this.toString(),e,t);return e.equalTo(n)?t.equalTo(i)?this.gaps.splice(r,1):this.gaps[r]=[t,i]:t.equalTo(i)?this.gaps[r]=[n,e]:this.gaps.splice(r,1,[n,e],[t,i]),this.dropLowestGapIfOverMaxGapCount(),!0}if(t.greaterThan(n))throw new D$(this.toString(),e,t)}return!1}dropLowestGapIfOverMaxGapCount(){this.gaps.length>this.maxGapCount&&this.gaps.shift()}toString(){return this.gaps.map((([e,t])=>`(${e.toString()}, ${t.toString()}]`)).join(", ")}}const L$=(e,t,r)=>{const n=`${kE(t.publisherId)}-${t.messageChainId}`,i=r?new x$(Number(r.timestamp),r.sequenceNumber):null,s=new x$(Number(t.timestamp),t.sequenceNumber);return e.has(n)||e.set(n,new B$),e.get(n).markAndCheck(i,s)},F$=new Bv("ContentDeliveryLayerNode");class U$ extends Sl{started=!1;duplicateDetectors;options;contentDeliveryRpcLocal;abortController=new AbortController;messagesPropagated=0;constructor(e){super(),this.options=e,this.duplicateDetectors=new Map,this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,rpcCommunicator:this.options.rpcCommunicator,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:(e,t)=>{if(this.abortController.signal.aborted)return;(this.options.nearbyNodeView.get(e)??this.options.randomNodeView.get(e)??this.options.neighbors.get(e)??this.options.proxyConnectionRpcLocal?.getConnection(e)?.remote)&&(this.options.discoveryLayerNode.removeContact(e),this.options.neighbors.remove(e),this.options.nearbyNodeView.remove(e),this.options.randomNodeView.remove(e),this.options.leftNodeView.remove(e),this.options.rightNodeView.remove(e),this.options.neighborFinder.start([e]),this.options.proxyConnectionRpcLocal?.removeConnection(e)),t&&this.emit("entryPointLeaveDetected")},markForInspection:(e,t)=>this.options.inspector.markMessage(e,t),plumtreeManager:this.options.plumtreeManager})}async start(){this.started=!0,this.registerDefaultServerMethods(),oE(this.options.discoveryLayerNode,"nearbyContactAdded",(()=>this.onNearbyContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"nearbyContactRemoved",(()=>this.onNearbyContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactAdded",(()=>this.onRandomContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactRemoved",(()=>this.onRandomContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactAdded",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactRemoved",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal),oE(this.options.neighbors,"nodeAdded",((e,t)=>{this.options.propagation.onNeighborJoined(e),this.options.connectionLocker.weakLockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId),this.emit("neighborConnected",e)}),this.abortController.signal),oE(this.options.neighbors,"nodeRemoved",((e,t)=>{this.options.connectionLocker.weakUnlockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId)}),this.abortController.signal),void 0!==this.options.proxyConnectionRpcLocal&&oE(this.options.proxyConnectionRpcLocal,"newConnection",(e=>this.options.propagation.onNeighborJoined(e)),this.abortController.signal),this.options.plumtreeManager&&oE(this.options.plumtreeManager,"message",(e=>this.emit("message",e)),this.abortController.signal),this.options.neighborFinder.start(),await this.options.neighborUpdateManager.start()}registerDefaultServerMethods(){this.options.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.options.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t))),this.options.rpcCommunicator.registerRpcMethod(HH,$H,"openConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.openConnection(e,t))),this.options.rpcCommunicator.registerRpcNotification(WH,"closeConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.closeConnection(e,t)))}onRingContactsUpdated(){if(F$.trace("onRingContactsUpdated"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRingContacts();this.options.leftNodeView.replaceAll(e.left.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.rightNodeView.replaceAll(e.right.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNearbyContactAdded(){if(F$.trace("New nearby contact found"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onNearbyContactRemoved(){if(F$.trace("Nearby contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e)}updateNearbyNodeView(e){this.options.nearbyNodeView.replaceAll(Array.from(e).map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))));for(const e of this.options.discoveryLayerNode.getNeighbors()){if(this.options.nearbyNodeView.size()>=this.options.nodeViewSize)break;this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))}}onRandomContactAdded(){if(this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onRandomContactRemoved(){if(F$.trace("New random contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNodeDisconnected(e){const t=Xj(e);this.options.neighbors.has(t)&&(this.options.neighbors.remove(t),this.options.neighborFinder.start([t]),this.options.temporaryConnectionRpcLocal.removeNode(t))}hasProxyConnection(e){return!!this.options.proxyConnectionRpcLocal&&this.options.proxyConnectionRpcLocal.hasConnection(e)}stop(){this.started&&(this.abortController.abort(),this.options.proxyConnectionRpcLocal?.stop(),this.options.neighbors.getAll().map((e=>{e.leaveStreamPartNotice(this.options.streamPartId,this.options.isLocalNodeEntryPoint()),this.options.connectionLocker.weakUnlockConnection(Xj(e.getPeerDescriptor()),this.options.streamPartId)})),this.options.rpcCommunicator.destroy(),this.removeAllListeners(),this.options.plumtreeManager?.stop(),this.options.nearbyNodeView.stop(),this.options.neighbors.stop(),this.options.randomNodeView.stop(),this.options.neighborFinder.stop(),this.options.neighborUpdateManager.stop(),this.options.inspector.stop(),this.duplicateDetectors.clear())}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e);const r=void 0!==t&&!this.options.temporaryConnectionRpcLocal.hasNode(t);this.options.propagation.feedUnseenMessage(e,this.getPropagationTargets(e),r?t:null),this.messagesPropagated+=1}inspect(e){return this.options.inspector.inspect(e)}getPropagationTargets(e){let t=this.options.neighbors.getIds();return this.options.proxyConnectionRpcLocal&&(t=t.concat(this.options.proxyConnectionRpcLocal.getPropagationTargets(e))),t=t.concat(this.options.temporaryConnectionRpcLocal.getNodes().getIds()),t}getOwnNodeId(){return Xj(this.options.localPeerDescriptor)}getOutgoingHandshakeCount(){return this.options.handshaker.getOngoingHandshakes().size}getNeighbors(){return!this.started&&this.isStopped()?[]:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor()))}getInfos(){return this.options.neighbors.getAll().map((e=>({peerDescriptor:e.getPeerDescriptor(),rtt:e.getRtt()})))}getNearbyNodeView(){return this.options.nearbyNodeView}getDiagnosticInfo(){return{neighborCount:this.options.neighbors.size(),nearbyNodeViewCount:this.options.nearbyNodeView.size(),randomNodeViewCount:this.options.randomNodeView.size(),leftNodeViewCount:this.options.leftNodeView.size(),rightNodeViewCount:this.options.rightNodeView.size(),messagesPropagated:this.messagesPropagated}}isStopped(){return this.abortController.signal.aborted}}const j$=(e,t,r=!1)=>{const n=r?Array.from(e.entries()).filter((([e,t])=>void 0!==t.getPeerDescriptor().websocket)):Array.from(e.entries());return n.filter((([e])=>!t.includes(e))).map((([e,t])=>t))};class q$ extends Sl{nodes;limit;ownId;constructor(e,t){super(),this.nodes=new Map,this.limit=t,this.ownId=e}add(e){const t=Xj(e.getPeerDescriptor());if(this.ownId!==t&&this.nodes.size<this.limit){const r=this.nodes.has(t);this.nodes.set(t,e),r||this.emit("nodeAdded",t,e)}}remove(e){if(this.nodes.has(e)){const t=this.nodes.get(e);this.nodes.delete(e),this.emit("nodeRemoved",e,t)}}has(e){return this.nodes.has(e)}replaceAll(e){this.nodes.clear();e.splice(0,this.limit).forEach((e=>{this.add(e)}))}getIds(){return Array.from(this.nodes.keys())}get(e){return this.nodes.get(e)}size(e=[]){return Array.from(this.nodes.keys()).filter((t=>!e.includes(t))).length}getRandom(e){return oA(j$(this.nodes,e))}getFirst(e,t=!1){return j$(this.nodes,e,t)[0]}getFirstAndLast(e){const t=j$(this.nodes,e);return 0===t.length?[]:t.length>1?[this.getFirst(e),this.getLast(e)]:[this.getFirst(e)]}getLast(e){const t=j$(this.nodes,e);return t[t.length-1]}getAll(){return Array.from(this.nodes.values())}stop(){this.nodes.forEach((e=>this.remove(Xj(e.getPeerDescriptor())))),this.removeAllListeners()}}class z${items=new Map;dropQueue=vV.create();ttlInMs;maxSize;onItemDropped;timeProvider;constructor({ttlInMs:e,maxSize:t,onItemDropped:r=()=>{},timeProvider:n=Date.now}){if(e<0)throw new Error(`ttlInMs (${e}) cannot be < 0`);if(t<0)throw new Error(`maxSize (${t}) cannot be < 0`);this.ttlInMs=e,this.maxSize=t,this.onItemDropped=r,this.timeProvider=n}set(e,t){if(0===this.maxSize)return;if(this.items.size>this.maxSize)throw new Error("assertion error: maximum size exceeded");if(this.delete(e),this.items.size===this.maxSize){const e=this.dropQueue.shift();if(void 0===e)throw new Error("assertion error: queue empty but still have items");this.items.delete(e),this.onItemDropped(e)}const r=new kV(e);this.dropQueue.pushNode(r),this.items.set(e,{value:t,dropQueueNode:r,expiresAt:this.timeProvider()+this.ttlInMs})}delete(e){const t=this.items.get(e);void 0!==t&&(this.items.delete(e),this.dropQueue.removeNode(t.dropQueueNode),this.onItemDropped(e))}get(e){const t=this.items.get(e);if(void 0!==t){if(!(t.expiresAt<=this.timeProvider()))return t.value;this.delete(e)}}values(){const e=[...this.items.keys()],t=[];for(const r of e){const e=this.get(r);void 0!==e&&t.push(e)}return t}}class K${tasks;constructor(e,t){this.tasks=new z$({ttlInMs:e,maxSize:t})}get(){return this.tasks.values()}add(e){const t=e.message.messageId;this.tasks.set(t,e)}delete(e){this.tasks.delete(e)}}class G${sendToNeighbor;minPropagationTargets;activeTaskStore;constructor({sendToNeighbor:e,minPropagationTargets:t,maxMessages:r,ttl:n}){this.sendToNeighbor=e,this.minPropagationTargets=t,this.activeTaskStore=new K$(n,r)}feedUnseenMessage(e,t,r){const n={message:e,source:r,handledNeighbors:new Set};this.activeTaskStore.add(n);for(const e of t)this.sendAndAwaitThenMark(n,e)}onNeighborJoined(e){const t=this.activeTaskStore.get();for(const r of t)this.sendAndAwaitThenMark(r,e)}sendAndAwaitThenMark({message:e,source:t,handledNeighbors:r},n){r.has(n)||n===t||(async()=>{try{await this.sendToNeighbor(n,e)}catch{return}r.add(n),r.size>=this.minPropagationTargets&&this.activeTaskStore.delete(e.messageId)})()}}const V$=new Bv("ProxyConnectionRpcLocal");class H$ extends Sl{options;connections=new Map;constructor(e){super(),this.options=e,this.options.rpcCommunicator.registerRpcMethod(GH,VH,"requestConnection",((e,t)=>this.requestConnection(e,t)))}getConnection(e){return this.connections.get(e)}hasConnection(e){return this.connections.has(e)}removeConnection(e){this.connections.delete(e)}stop(){this.connections.forEach((e=>e.remote.leaveStreamPartNotice(this.options.streamPartId,!1))),this.connections.clear(),this.removeAllListeners()}getPropagationTargets(e){if("groupKeyRequest"!==e.body.oneofKind)return this.getSubscribers();try{const t=e.body.groupKeyRequest.recipientId;return this.getNodeIdsForUserId(kE(t))}catch(e){return V$.trace("Could not parse GroupKeyRequest",{err:e}),[]}}getNodeIdsForUserId(e){return Array.from(this.connections.keys()).filter((t=>this.connections.get(t).userId===e))}getSubscribers(){return Array.from(this.connections.keys()).filter((t=>{const r=this.connections.get(t).direction;return void 0===r||r===e.ProxyDirection.SUBSCRIBE}))}async requestConnection(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);this.connections.set(n,{direction:e.direction,userId:kE(e.userId),remote:new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$)});return V$.trace(`Accepted connection request from ${n} to ${this.options.streamPartId}`),this.emit("newConnection",n),{accepted:!0}}}const $$=new Bv("TemporaryConnectionRpcRemote");class W$ extends jz{async openConnection(){try{return(await this.getClient().openConnection({},this.formDhtRpcOptions())).accepted}catch(e){return $$.debug(`temporaryConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),!1}}async closeConnection(){try{await this.getClient().closeConnection({},this.formDhtRpcOptions({connect:!1,notification:!0}))}catch(e){$$.trace(`closeConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e})}}}class J$ extends Sl{inspectionMessages=new Map;inspectedNode;constructor(e){super(),this.inspectedNode=e.inspectedNode}markMessage(e,t){const r=(e=>`${kE(e.publisherId)}:${e.messageChainId}:${e.timestamp}:${e.sequenceNumber}`)(t);this.inspectionMessages.has(r)?(this.inspectionMessages.has(r)&&!1===this.inspectionMessages.get(r)&&e===this.inspectedNode||this.inspectionMessages.has(r)&&!0===this.inspectionMessages.get(r))&&this.emit("done"):this.inspectionMessages.set(r,e===this.inspectedNode)}getInspectedMessageCount(){return this.inspectionMessages.size}onlyMarkedByInspectedNode(){return Array.from(this.inspectionMessages.values()).every((e=>!0===e))}stop(){this.emit("done")}}const Q$=new Bv("Inspector");class Z${sessions=new Map;streamPartId;localPeerDescriptor;rpcCommunicator;connectionLocker;inspectionTimeout;openInspectConnection;closeInspectConnection;constructor(e){this.streamPartId=e.streamPartId,this.localPeerDescriptor=e.localPeerDescriptor,this.rpcCommunicator=e.rpcCommunicator,this.connectionLocker=e.connectionLocker,this.inspectionTimeout=e.inspectionTimeout??6e4,this.openInspectConnection=e.openInspectConnection??this.defaultOpenInspectConnection,this.closeInspectConnection=e.closeInspectConnection??this.defaultCloseInspectConnection}async defaultOpenInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.openConnection(),this.connectionLocker.weakLockConnection(Xj(e),t)}async defaultCloseInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.closeConnection(),this.connectionLocker.weakUnlockConnection(Xj(e),t)}async inspect(e){const t=Xj(e),r=new J$({inspectedNode:t}),n=`inspector-${this.streamPartId}`;this.sessions.set(t,r),await this.openInspectConnection(e,n);let i=!1;try{await eE(r,"done",this.inspectionTimeout),i=!0}catch{Q$.trace("Inspect session timed out, removing")}finally{await this.closeInspectConnection(e,n),this.sessions.delete(t)}return i||r.getInspectedMessageCount()<1||r.onlyMarkedByInspectedNode()}markMessage(e,t){this.sessions.forEach((r=>r.markMessage(e,t)))}isInspected(e){return this.sessions.has(e)}stop(){this.sessions.forEach((e=>{e.stop()})),this.sessions.clear()}}class Y${options;temporaryNodes;lockId;constructor(e){this.options=e,this.temporaryNodes=new q$(Xj(e.localPeerDescriptor),10),this.lockId="system/content-delivery/temporary-connection/"+e.streamPartId}getNodes(){return this.temporaryNodes}hasNode(e){return this.temporaryNodes.has(e)}removeNode(e){this.temporaryNodes.remove(e),this.options.connectionLocker.weakUnlockConnection(e,this.lockId)}async openConnection(e,t){const r=t.incomingSourceDescriptor,n=new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$);return this.temporaryNodes.add(n),this.options.connectionLocker.weakLockConnection(Xj(r),this.lockId),{accepted:!0}}async closeConnection(e,t){const r=Xj(t.incomingSourceDescriptor);return this.removeNode(r),{}}}const X$=e=>`stream-part-delivery-${e}`;class eW{neighbors;pausedNodes;onMetadataCb;sendBuffer;constructor(e,t,r,n){this.neighbors=e,this.pausedNodes=t,this.onMetadataCb=r,this.sendBuffer=n}async sendMetadata(e,t){const r=t.incomingSourceDescriptor;return await this.onMetadataCb(e,r),MV}async pauseNeighbor(e,t){const r=Xj(t.incomingSourceDescriptor);if(this.neighbors.has(r)){return{accepted:this.pausedNodes.add(r,e.messageChainId)}}return{accepted:!1}}async resumeNeighbor(e,t){const r=t.incomingSourceDescriptor;return this.neighbors.has(Xj(r))&&(this.pausedNodes.delete(Xj(r),e.messageChainId),await this.sendBuffer(e.fromTimestamp,e.messageChainId,r)),MV}}class tW extends jz{async sendMetadata(e){const t=this.formDhtRpcOptions({notification:!0});await this.getClient().sendMetadata(e,t)}async pauseNeighbor(e){const t=this.formDhtRpcOptions();return(await this.getClient().pauseNeighbor({messageChainId:e},t)).accepted}async resumeNeighbor(e,t){const r=this.formDhtRpcOptions({notification:!0});await this.getClient().resumeNeighbor({fromTimestamp:e,messageChainId:t},r)}}class rW{pausedNeighbors;limit;constructor(e){this.pausedNeighbors=new Map,this.limit=e}add(e,t){return this.pausedNeighbors.has(t)||this.pausedNeighbors.set(t,new Set),!(this.pausedNeighbors.get(t).size>=this.limit)&&(this.pausedNeighbors.get(t).add(e),!0)}delete(e,t){this.pausedNeighbors.get(t)?.delete(e),0===this.pausedNeighbors.get(t)?.size&&this.pausedNeighbors.delete(t)}deleteAll(e){this.pausedNeighbors.forEach(((t,r)=>{t.delete(e),0===t.size&&this.pausedNeighbors.delete(r)}))}isPaused(e,t){return!!this.pausedNeighbors.has(t)&&this.pausedNeighbors.get(t).has(e)}forEach(e){this.pausedNeighbors.forEach(((t,r)=>{e(t,r)}))}size(e){return this.pausedNeighbors.get(e)?.size??0}}const nW=new Bv("PlumtreeManager");class iW extends Sl{neighbors;localPeerDescriptor;localPausedNeighbors;remotePausedNeighbors;rpcLocal;latestMessages=new Map;rpcCommunicator;maxPausedNeighbors;recoveryState=new Map;recoveryCooldownUntil=new Map;recoveryTimeout;recoveryCooldown;abortController=new AbortController;constructor(e){super(),this.neighbors=e.neighbors,this.maxPausedNeighbors=e.maxPausedNeighbors??3,this.localPeerDescriptor=e.localPeerDescriptor,this.localPausedNeighbors=new rW(e.maxPausedNeighbors??3),this.remotePausedNeighbors=new rW(e.maxPausedNeighbors??3),this.recoveryTimeout=e.recoveryTimeout??500,this.recoveryCooldown=e.recoveryCooldown??2500,this.rpcLocal=new eW(this.neighbors,this.localPausedNeighbors,((e,t)=>this.onMetadata(e,t)),((e,t,r)=>this.sendBuffer(e,t,r))),this.neighbors.on("nodeRemoved",this.onNeighborRemoved),this.rpcCommunicator=e.rpcCommunicator,this.rpcCommunicator.registerRpcNotification(NH,"sendMetadata",((e,t)=>this.rpcLocal.sendMetadata(e,t))),this.rpcCommunicator.registerRpcMethod(e$,t$,"pauseNeighbor",((e,t)=>this.rpcLocal.pauseNeighbor(e,t))),this.rpcCommunicator.registerRpcNotification(r$,"resumeNeighbor",((e,t)=>this.rpcLocal.resumeNeighbor(e,t))),((e,t,r)=>{if(r.aborted)return;r.addEventListener("abort",(()=>{clearInterval(n)}),{once:!0});const n=setInterval((()=>{e()}),t)})((()=>{const e=performance.now();for(const[t,r]of this.recoveryState)e-r.metadataAheadSince>=this.recoveryTimeout&&!r.resumeInProgress&&this.attemptRecovery(t,r,this.getLatestMessageTimestamp(t))}),e.recoveryCheckInterval??200,this.abortController.signal)}async pauseNeighbor(e,t){if(this.neighbors.has(Xj(e))&&!this.remotePausedNeighbors.isPaused(Xj(e),t)&&this.remotePausedNeighbors.size(t)<this.maxPausedNeighbors){nW.debug(`Pausing neighbor ${Xj(e)}`),this.remotePausedNeighbors.add(Xj(e),t);try{const r=this.createRemote(e);await r.pauseNeighbor(t)||this.remotePausedNeighbors.delete(Xj(e),t)}catch(r){this.remotePausedNeighbors.delete(Xj(e),t)}}}async resumeNeighbor(e,t,r){if(this.remotePausedNeighbors.isPaused(Xj(e),t)){nW.debug(`Resuming neighbor ${Xj(e)}`),this.remotePausedNeighbors.delete(Xj(e),t);const n=this.createRemote(e);await n.resumeNeighbor(r,t)}}onNeighborRemoved=e=>{this.localPausedNeighbors.deleteAll(e),this.remotePausedNeighbors.deleteAll(e);for(const[t,r]of this.recoveryState)r.candidates=r.candidates.filter((t=>Xj(t)!==e)),null!==r.lastAttemptedNode&&Xj(r.lastAttemptedNode)===e&&(r.lastAttemptedNode=null);this.neighbors.size()>0&&this.remotePausedNeighbors.forEach(((e,t)=>{if(e.size>=this.neighbors.size()){nW.debug("All neighbors are paused, resuming first neighbor");const e=this.neighbors.getFirst([]).getPeerDescriptor();setImmediate((()=>this.resumeNeighbor(e,t,this.getLatestMessageTimestamp(t))))}}))};getLatestMessageTimestamp(e){return this.latestMessages.has(e)&&0!==this.latestMessages.get(e).length?this.latestMessages.get(e)[this.latestMessages.get(e).length-1].messageId.timestamp:0}async sendBuffer(e,t,r){const n=new b$(this.localPeerDescriptor,r,this.rpcCommunicator,l$),i=this.latestMessages.get(t)?.filter((t=>t.messageId.timestamp>e))??[];for(const e of i)await n.sendStreamMessage(e)}async onMetadata(e,t){const r=this.getLatestMessageTimestamp(e.messageChainId);if(r>=e.timestamp)return;const n=e.messageChainId,i=this.recoveryCooldownUntil.get(n);if(void 0!==i&&performance.now()<i)return;let s=this.recoveryState.get(n);s||(s={timestampsAhead:new Set,metadataAheadSince:performance.now(),candidates:[],lastAttemptedNode:null,resumeInProgress:!1},this.recoveryState.set(n,s)),s.timestampsAhead.add(e.timestamp);const o=Xj(t);null!==s.lastAttemptedNode&&Xj(s.lastAttemptedNode)===o||s.candidates.some((e=>Xj(e)===o))||s.candidates.push(t),s.timestampsAhead.size>1&&!s.resumeInProgress&&await this.attemptRecovery(n,s,r)}async attemptRecovery(e,t,r){const n=t.candidates.shift();if(n){t.resumeInProgress=!0,t.lastAttemptedNode=n,t.candidates=[],t.timestampsAhead.clear(),t.metadataAheadSince=performance.now();try{const t=this.createRemote(n);await t.resumeNeighbor(r,e)}catch(e){nW.debug("Recovery resume failed, will retry with next candidate")}finally{t.resumeInProgress=!1}}else t.metadataAheadSince=performance.now()}createRemote(e){return new tW(this.localPeerDescriptor,e,this.rpcCommunicator,m$)}broadcast(e,t){const r=e.messageId.messageChainId;this.latestMessages.has(r)||this.latestMessages.set(r,[]),this.latestMessages.get(r).length<20||this.latestMessages.get(r).shift(),this.latestMessages.get(r).push(e);const n=this.recoveryState.get(r);n&&(n.lastAttemptedNode&&this.remotePausedNeighbors.delete(Xj(n.lastAttemptedNode),r),this.recoveryState.delete(r),this.recoveryCooldownUntil.set(r,performance.now()+this.recoveryCooldown)),this.emit("message",e);const i=this.neighbors.getAll().filter((e=>Xj(e.getPeerDescriptor())!==t));for(const t of i)if(this.localPausedNeighbors.isPaused(Xj(t.getPeerDescriptor()),e.messageId.messageChainId)){const r=this.createRemote(t.getPeerDescriptor());setImmediate((()=>r.sendMetadata(e.messageId)))}else setImmediate((()=>t.sendStreamMessage(e)))}isNeighborPaused(e,t){return this.localPausedNeighbors.isPaused(Xj(e),t)||this.remotePausedNeighbors.isPaused(Xj(e),t)}getLocalPausedNeighbors(){return this.localPausedNeighbors}getRemotePausedNeighbors(){return this.remotePausedNeighbors}stop(){this.abortController.abort(),this.neighbors.off("nodeRemoved",this.onNeighborRemoved),this.latestMessages.clear(),this.recoveryState.clear(),this.recoveryCooldownUntil.clear()}}const sW=e=>new U$((e=>{const t=Xj(e.localPeerDescriptor),r=e.rpcCommunicator??new lK(X$(e.streamPartId),e.transport),n=e.neighborTargetCount??4,i=e.maxContactCount??20,s=e.acceptProxyConnections??!1,o=e.neighborUpdateInterval??1e4,a=e.minPropagationTargets??2,c=e.maxPropagationBufferSize??150,u=e.neighbors??new q$(t,i),l=e.leftNodeView??new q$(t,i),h=e.rightNodeView??new q$(t,i),d=e.nearbyNodeView??new q$(t,i),f=e.randomNodeView??new q$(t,i),p=new Set,g=new Y$({rpcCommunicator:r,localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker}),m=s?new H$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r}):void 0,y=e.plumtreeOptimization?new iW({neighbors:u,localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,maxPausedNeighbors:e.plumtreeMaxPausedNeighbors}):void 0,b=e.propagation??new G$({minPropagationTargets:a,maxMessages:c,ttl:1e4,sendToNeighbor:async(t,r)=>{const n=u.get(t)??g.getNodes().get(t),i=m?.getConnection(t);if(n)await n.sendStreamMessage(r,e.bufferWhileConnecting);else{if(!i)throw new Error("Propagation target not found");await i.remote.sendStreamMessage(r)}}}),w=e.handshaker??new k$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,maxNeighborCount:n,rpcRequestTimeout:e.rpcRequestTimeout,ongoingHandshakes:p}),v=e.neighborFinder??new C$({neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,doFindNeighbors:e=>w.attemptHandshakesOnContacts(e),minCount:n}),E=e.neighborUpdateManager??new N$({neighbors:u,nearbyNodeView:d,localPeerDescriptor:e.localPeerDescriptor,neighborFinder:v,streamPartId:e.streamPartId,rpcCommunicator:r,neighborUpdateInterval:o,neighborTargetCount:n,ongoingHandshakes:p}),A=e.inspector??new Z$({localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker});return{...e,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,rpcCommunicator:r,handshaker:w,neighborFinder:v,neighborUpdateManager:E,propagation:b,neighborTargetCount:n,nodeViewSize:i,proxyConnectionRpcLocal:m,inspector:A,temporaryConnectionRpcLocal:g,plumtreeManager:y}})(e)),oW=new Bv("ProxyConnectionRpcRemote");class aW extends jz{async requestConnection(e,t){const r={direction:t,userId:RE(e)},n=this.formDhtRpcOptions({timeout:Fz});try{return(await this.getClient().requestConnection(r,n)).accepted}catch(e){return oW.debug("ProxyConnectionRequest failed with error",{err:e}),!1}}}const cW=new Bv("ProxyClient"),uW="system/proxy-client";class lW extends Sl{rpcCommunicator;contentDeliveryRpcLocal;options;duplicateDetectors=new Map;definition;connections=new Map;propagation;neighbors;abortController;constructor(e){super(),this.options=e,this.rpcCommunicator=new lK(X$(e.streamPartId),e.transport),this.neighbors=new q$(Xj(this.options.localPeerDescriptor),1e3),this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:e=>{const t=this.neighbors.get(e);t&&setImmediate((()=>this.onNodeDisconnected(t.getPeerDescriptor())))},rpcCommunicator:this.rpcCommunicator,markForInspection:()=>{}}),this.propagation=new G$({minPropagationTargets:e.minPropagationTargets,maxMessages:e.maxPropagationBufferSize,ttl:e.propagationBufferTtl,sendToNeighbor:async(e,t)=>{const r=this.neighbors.get(e);if(!r)throw new Error("Propagation target not found");await r.sendStreamMessage(t)}}),this.abortController=new AbortController}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t)))}async setProxies(e,t,r,n){if(cW.trace("Setting proxies",{streamPartId:this.options.streamPartId,peerDescriptors:e,direction:r,userId:t,connectionCount:n}),void 0!==n&&n>e.length)throw new Error("Cannot set connectionCount above the size of the configured array of nodes");const i=new Map;e.forEach((e=>{i.set(Xj(e),e)})),this.definition={nodes:i,userId:t,direction:r,connectionCount:n??e.length},await this.updateConnections()}async updateConnections(){await Promise.all(this.getInvalidConnections().map((async e=>{await this.closeConnection(e)})));const e=this.definition.connectionCount-this.connections.size;e>0?await this.openRandomConnections(e):e<0&&await this.closeRandomConnections(-e)}getInvalidConnections(){return Array.from(this.connections.keys()).filter((e=>!this.definition.nodes.has(e)||this.definition.direction!==this.connections.get(e).direction))}async openRandomConnections(e){const t=wV(Array.from(this.definition.nodes.keys()).filter((e=>!this.connections.has(e))),e);await Promise.all(t.map((e=>this.attemptConnection(e,this.definition.userId,this.definition.direction))))}async attemptConnection(e,t,r){const n=this.definition.nodes.get(e),i=new aW(this.options.localPeerDescriptor,n,this.rpcCommunicator,h$);if(await i.requestConnection(t,r)){this.options.connectionLocker.lockConnection(n,uW),this.connections.set(e,{peerDescriptor:n,direction:r});const t=new b$(this.options.localPeerDescriptor,n,this.rpcCommunicator,l$);this.neighbors.add(t),this.propagation.onNeighborJoined(e),cW.info("Open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}else cW.warn("Unable to open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}async closeRandomConnections(e){const t=wV(Array.from(this.connections.keys()),e);await Promise.allSettled(t.map((e=>this.closeConnection(e))))}async closeConnection(e){if(this.connections.has(e)){cW.info("Close proxy connection",{nodeId:e});const t=this.neighbors.get(e);t?.leaveStreamPartNotice(this.options.streamPartId,!1),this.removeConnection(this.connections.get(e).peerDescriptor)}}removeConnection(e){const t=Xj(e);this.connections.delete(t),this.neighbors.remove(t),this.options.connectionLocker.unlockConnection(e,uW)}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e),this.propagation.feedUnseenMessage(e,this.neighbors.getIds(),t??null)}hasConnection(e,t){return this.connections.has(e)&&this.connections.get(e).direction===t}getDirection(){return this.definition.direction}async onNodeDisconnected(e){const t=Xj(e);this.connections.has(t)&&(this.options.connectionLocker.unlockConnection(e,uW),this.removeConnection(e),await(async(e,t,r,n=1e4)=>{for(;;){try{return await e()}catch{cW.warn(`Failed ${t} (retrying after delay)`,{delayInMs:n})}await Qv(n,r)}})((()=>this.updateConnections()),"updating proxy connections",this.abortController.signal))}async start(){this.registerDefaultServerMethods(),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal)}getDiagnosticInfo(){return{neighbors:this.neighbors.getAll().map((e=>e.getPeerDescriptor()))}}stop(){this.neighbors.getAll().forEach((e=>{this.options.connectionLocker.unlockConnection(e.getPeerDescriptor(),uW),e.leaveStreamPartNotice(this.options.streamPartId,!1)})),this.neighbors.stop(),this.rpcCommunicator.destroy(),this.connections.clear(),this.abortController.abort()}}const hW=new Bv("ContentDeliveryManager"),dW=e=>{return Zj((t=e,Buffer.from(Zr(pw(t)))));var t};class fW extends Sl{transport;connectionLocker;controlLayerNode;metricsContext;metrics;options;streamParts;knownStreamPartEntryPoints=new Map;started=!1;destroyed=!1;constructor(e){super(),this.options=e,this.streamParts=new Map,this.metricsContext=e.metricsContext??new $v,this.metrics={broadcastMessagesPerSecond:new Hv,broadcastBytesPerSecond:new Hv},this.metricsContext.addMetrics("node",this.metrics)}async start(e,t,r){this.started||this.destroyed||(this.started=!0,this.controlLayerNode=e,this.transport=t,this.connectionLocker=r)}async destroy(){this.started&&!this.destroyed&&(hW.trace("Destroying ContentDeliveryManager"),this.destroyed=!0,await Promise.all(Array.from(this.streamParts.values()).map((e=>e.stop()))),this.streamParts.clear(),this.removeAllListeners(),this.controlLayerNode=void 0,this.transport=void 0,this.connectionLocker=void 0)}broadcast(e,t){const r=EE(e.messageId.streamId,e.messageId.streamPartition);hW.debug(`Broadcasting to stream part ${r}`),this.joinStreamPart(r,t),this.streamParts.get(r).broadcast(e),"contentMessage"===e.body.oneofKind&&(this.metrics.broadcastMessagesPerSecond.record(1),this.metrics.broadcastBytesPerSecond.record(e.body.contentMessage.content.length))}async leaveStreamPart(e){const t=this.streamParts.get(e);t&&(await t.stop(),this.streamParts.delete(e))}joinStreamPart(e,t){let r=this.streamParts.get(e);if(void 0!==r)return;hW.debug(`Join stream part ${e}`);const n=this.createDiscoveryLayerNode(e,this.knownStreamPartEntryPoints.get(e)??[]),i=new PV({key:dW(e),localPeerDescriptor:this.getPeerDescriptor(),fetchDataFromDht:e=>this.controlLayerNode.fetchDataFromDht(e),storeDataToDht:(e,t)=>this.controlLayerNode.storeDataToDht(e,t),deleteDataFromDht:async(e,t)=>this.controlLayerNode.deleteDataFromDht(e,t)}),s=new _V({discoveryLayerNode:n,discoverEntryPoints:async()=>i.fetchNodes()}),o=this.createContentDeliveryLayerNode(e,n,(()=>i.isLocalNodeStored()),t),a=new NV(n,i);r={proxied:!1,discoveryLayerNode:n,node:o,networkSplitAvoidance:s,broadcast:e=>o.broadcast(e),stop:async()=>{a.destroy(),s.destroy(),await i.destroy(),o.stop(),await n.stop()},getDiagnosticInfo:()=>o.getDiagnosticInfo()},this.streamParts.set(e,r),o.on("message",(e=>{this.emit("newMessage",e)}));const c=async()=>{if(this.destroyed||i.isLocalNodeStored()||this.knownStreamPartEntryPoints.has(e))return;(await i.fetchNodes()).length<8&&await i.storeAndKeepLocalNode()};n.on("manualRejoinRequired",(async()=>{a.isRunning()||s.isRunning()||(hW.debug("Manual rejoin required for stream part",{streamPartId:e}),await a.reconnect())})),o.on("entryPointLeaveDetected",(()=>c())),setImmediate((async()=>{try{await this.startLayersAndJoinDht(e,i)}catch(t){hW.warn(`Failed to join to stream part ${e}`,{err:t})}}))}async startLayersAndJoinDht(e,t){hW.debug(`Start layers and join DHT for stream part ${e}`);const r=this.streamParts.get(e);if(void 0===r||r.proxied)return;this.transport.isPrivateClientMode()&&await this.transport.disablePrivateClientMode(),await r.discoveryLayerNode.start(),await r.node.start();const n=this.knownStreamPartEntryPoints.get(e);if(void 0!==n)await Promise.all([r.discoveryLayerNode.joinDht(n),r.discoveryLayerNode.joinRing()]);else{const e=await t.fetchNodes();await Promise.all([r.discoveryLayerNode.joinDht(wV(e,4)),r.discoveryLayerNode.joinRing()]),e.length<8&&(await t.storeAndKeepLocalNode(),r.discoveryLayerNode.getNeighborCount()<4&&setImmediate((()=>r.networkSplitAvoidance.avoidNetworkSplit())))}}createDiscoveryLayerNode(e,t){return new oV({transport:this.controlLayerNode,connectionsView:this.controlLayerNode.getConnectionsView(),serviceId:"layer1::"+e,peerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),entryPoints:t,numberOfNodesPerKBucket:4,rpcRequestTimeout:Fz,dhtJoinTimeout:2e4,periodicallyPingNeighbors:!0,periodicallyPingRingContacts:!0,neighborPingLimit:16})}createContentDeliveryLayerNode(e,t,r,n){return sW({streamPartId:e,transport:this.transport,discoveryLayerNode:t,connectionLocker:this.connectionLocker,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),minPropagationTargets:this.options.streamPartitionMinPropagationTargets,neighborTargetCount:this.options.streamPartitionNeighborTargetCount,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize,acceptProxyConnections:this.options.acceptProxyConnections,rpcRequestTimeout:this.options.rpcRequestTimeout,neighborUpdateInterval:this.options.neighborUpdateInterval,isLocalNodeEntryPoint:r,bufferWhileConnecting:this.options.bufferWhileConnecting,plumtreeOptimization:n?.plumtreeOptimization?.enabled,plumtreeMaxPausedNeighbors:!0===n?.plumtreeOptimization?.enabled?n?.plumtreeOptimization?.maxPausedNeighbors:void 0})}async setProxies(e,t,r,n,i){if(this.options.acceptProxyConnections)throw new Error("cannot set proxies when acceptProxyConnections=true");if(t.length>0&&(void 0===i||i>0)){let s;this.isProxiedStreamPart(e)?s=this.streamParts.get(e).client:(s=this.createProxyClient(e),this.streamParts.set(e,{proxied:!0,client:s,broadcast:e=>s.broadcast(e),stop:async()=>s.stop(),getDiagnosticInfo:()=>s.getDiagnosticInfo()}),s.on("message",(e=>{this.emit("newMessage",e)})),Array.from(this.streamParts.values()).every((e=>e.proxied))&&await this.transport.enablePrivateClientMode(),await s.start()),await s.setProxies(t,r,n,i)}else await(this.streamParts.get(e)?.stop()),this.streamParts.delete(e)}createProxyClient(e){return new lW({transport:this.transport,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),streamPartId:e,connectionLocker:this.connectionLocker,minPropagationTargets:this.options.streamPartitionMinPropagationTargets??2,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize??150,propagationBufferTtl:1e4})}async inspect(e,t){const r=this.streamParts.get(t);return void 0!==r&&!r.proxied&&r.node.inspect(e)}getNodeInfo(){const e=Array.from(this.streamParts.entries()).filter((([e,t])=>!1===t.proxied));return e.map((([e])=>{const t=this.streamParts.get(e);return{id:e,controlLayerNeighbors:t.discoveryLayerNode.getNeighbors(),deprecatedContentDeliveryLayerNeighbors:[],contentDeliveryLayerNeighbors:t.node.getInfos()}}))}setStreamPartEntryPoints(e,t){this.knownStreamPartEntryPoints.set(e,t)}isProxiedStreamPart(e,t){const r=this.streamParts.get(e);return void 0!==r&&r.proxied&&(void 0===t||r.client.getDirection()===t)}getStreamPartDelivery(e){return this.streamParts.get(e)}hasStreamPart(e){return this.streamParts.has(e)}getPeerDescriptor(){return this.controlLayerNode.getLocalPeerDescriptor()}getNodeId(){return Xj(this.controlLayerNode.getLocalPeerDescriptor())}getNeighbors(e){const t=this.streamParts.get(e);return!1===t?.proxied?t.node.getNeighbors().map((e=>Xj(e))):[]}getStreamParts(){return Array.from(this.streamParts.keys()).map((e=>AE.parse(e)))}getDiagnosticInfo(){return{streamParts:this.getStreamParts().map((e=>({id:e,info:this.getStreamPartDelivery(e).getDiagnosticInfo()})))}}}class pW extends jz{async getInfo(){return this.getClient().getInfo({},this.formDhtRpcOptions())}}class gW{ownPeerDescriptor;rpcCommunicator;constructor(e,t){this.ownPeerDescriptor=e,this.rpcCommunicator=t}async getInfo(e){return new pW(this.ownPeerDescriptor,e,this.rpcCommunicator,g$).getInfo()}}class mW{stack;rpcCommunicator;constructor(e,t){this.stack=e,this.rpcCommunicator=t,this.registerDefaultServerMethods()}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcMethod(YH,XH,"getInfo",(()=>this.getInfo()))}async getInfo(){return this.stack.createNodeInfo()}}const yW=new Bv("NetworkStack"),bW=[],wW=async()=>{const e=[...bW];await Promise.all(e.map((e=>e.stop())))};if("object"==typeof process&&"function"==typeof process?.on){["exit","SIGINT","SIGUSR1","SIGUSR2","uncaughtException","unhandledRejection","SIGTERM"].forEach((e=>{process.on(e,(async t=>{const r="uncaughtException"===e||"unhandledRejection"===e;r&&yW.error(`exit event: ${e}`,t),await wW(),process.exit(r?1:0)}))}))}"object"==typeof window&&window.addEventListener("unload",(async()=>{await wW()}));class vW{controlLayerNode;contentDeliveryManager;stopped=!1;metricsContext;options;nodeInfoRpcLocal;nodeInfoClient;constructor(e){this.options=e,this.metricsContext=e.metricsContext??new $v,this.controlLayerNode=new oV({...e.layer0,metricsContext:this.metricsContext,allowIncomingPrivateConnections:e.networkNode?.acceptProxyConnections}),this.contentDeliveryManager=new fW({...e.networkNode,metricsContext:this.metricsContext}),bW.push(this)}async joinStreamPart(e,t,r){if(this.getContentDeliveryManager().isProxiedStreamPart(e))throw new Error(`Cannot join to ${e} as proxy connections have been set`);await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().joinStreamPart(e,r),void 0!==t&&await iE((()=>this.getContentDeliveryManager().getNeighbors(e).length>=t.minCount),t.timeout)}async broadcast(t,r){const n=EE(t.messageId.streamId,t.messageId.streamPartition);if(this.getContentDeliveryManager().isProxiedStreamPart(n,e.ProxyDirection.SUBSCRIBE)&&"contentMessage"===t.body.oneofKind)throw new Error(`Cannot broadcast to ${n} as proxy subscribe connections have been set`);this.contentDeliveryManager.isProxiedStreamPart(n)||await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().broadcast(t,r)}async start(e=!0){yW.info("Starting a Streamr Network Node"),await this.controlLayerNode.start(),yW.info(`Node id is ${Xj(this.controlLayerNode.getLocalPeerDescriptor())}`);const t=this.controlLayerNode.getTransport();if(this.options.layer0?.entryPoints?.some((e=>eq(e,this.controlLayerNode.getLocalPeerDescriptor())))?await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints)):e&&await this.ensureConnectedToControlLayer(),await(this.contentDeliveryManager?.start(this.controlLayerNode,t,t)),this.contentDeliveryManager){const e=new lK("system/node-info-rpc",this.getConnectionManager());this.nodeInfoRpcLocal=new mW(this,e),this.nodeInfoClient=new gW(this.controlLayerNode.getLocalPeerDescriptor(),e)}}async ensureConnectedToControlLayer(){this.controlLayerNode.hasJoined()||(setImmediate((async()=>{void 0!==this.options.layer0?.entryPoints&&await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints))})),await this.controlLayerNode.waitForNetworkConnectivity())}getContentDeliveryManager(){return this.contentDeliveryManager}getControlLayerNode(){return this.controlLayerNode}getMetricsContext(){return this.metricsContext}async fetchNodeInfo(e){return eq(e,this.getControlLayerNode().getLocalPeerDescriptor())?this.createNodeInfo():this.nodeInfoClient.getInfo(e)}createNodeInfo(){return{peerDescriptor:this.getControlLayerNode().getLocalPeerDescriptor(),controlLayer:{connections:this.getControlLayerNode().getConnectionsView().getConnections(),neighbors:this.getControlLayerNode().getNeighbors()},streamPartitions:this.getContentDeliveryManager().getNodeInfo(),applicationVersion:"103.7.0-rc.2"}}getOptions(){return this.options}getConnectionManager(){return this.controlLayerNode.getTransport()}async stop(){this.stopped||(this.stopped=!0,Ej(bW,this),await this.contentDeliveryManager.destroy(),await this.controlLayerNode.stop(),this.contentDeliveryManager=void 0,this.controlLayerNode=void 0)}}class EW{stack;stopped=!1;externalNetworkRpc;constructor(e){this.stack=e}async start(e){await this.stack.start(e),this.externalNetworkRpc=new RV(this.stack.getControlLayerNode().getTransport())}async inspect(e,t){return this.stack.getContentDeliveryManager().inspect(e,t)}async broadcast(e,t){await this.stack.broadcast(e,t)}async join(e,t,r){await this.stack.joinStreamPart(e,t,r)}async setProxies(e,t,r,n,i){await this.stack.getContentDeliveryManager().setProxies(e,t,r,n,i)}isProxiedStreamPart(e){return this.stack.getContentDeliveryManager().isProxiedStreamPart(e)}addMessageListener(e){this.stack.getContentDeliveryManager().on("newMessage",e)}setStreamPartEntryPoints(e,t){this.stack.getContentDeliveryManager().setStreamPartEntryPoints(e,t)}removeMessageListener(e){this.stack.getContentDeliveryManager().off("newMessage",e)}async leave(e){this.stopped||await this.stack.getContentDeliveryManager().leaveStreamPart(e)}getNeighbors(e){return this.stack.getContentDeliveryManager().getNeighbors(e)}hasStreamPart(e){return this.stack.getContentDeliveryManager().hasStreamPart(e)}async stop(){this.stopped=!0,this.externalNetworkRpc.destroy(),await this.stack.stop()}getPeerDescriptor(){return this.stack.getControlLayerNode().getLocalPeerDescriptor()}getMetricsContext(){return this.stack.getMetricsContext()}getNodeId(){return this.stack.getContentDeliveryManager().getNodeId()}getOptions(){return this.stack.getOptions()}getStreamParts(){return this.stack.getContentDeliveryManager().getStreamParts()}async fetchNodeInfo(e){return this.stack.fetchNodeInfo(e)}getDiagnosticInfo(){return{controlLayer:this.stack.getControlLayerNode().getDiagnosticInfo(),contentLayer:this.stack.getContentDeliveryManager().getDiagnosticInfo()}}registerExternalNetworkRpcMethod(e,t,r,n){this.externalNetworkRpc.registerRpcMethod(e,t,r,n)}createExternalRpcClient(e){return this.externalNetworkRpc.createRpcClient(e)}}class AW extends Error{code;constructor(e,t){super(e),this.code=t}}function SW(e,t){if(void 0===t)throw new AW(`Expected ${e} to not be undefined.`)}function kW(e,t,r=!1){if(!r||void 0!==t){if(SW(e,t),!Number.isInteger(t))throw new AW(`Expected ${e} to be an integer but was a ${typeof t} (${t}).`);if(t<0)throw new AW(`Expected ${e} to not be negative (${t}).`)}}class RW{timestamp;sequenceNumber;constructor(e,t){kW("timestamp",e),kW("sequenceNumber",t,!0),this.timestamp=e,this.sequenceNumber=t}compareTo(e){return this.timestamp<e.timestamp?-1:this.timestamp>e.timestamp?1:this.sequenceNumber<e.sequenceNumber?-1:this.sequenceNumber>e.sequenceNumber?1:0}}class CW{streamId;streamPartition;timestamp;sequenceNumber;publisherId;msgChainId;constructor(e,t,r,n,i,s){kW("streamPartition",t),kW("timestamp",r),kW("sequenceNumber",n),this.streamId=e,this.streamPartition=t,this.timestamp=r,this.sequenceNumber=n,this.publisherId=i,this.msgChainId=s}getStreamPartID(){return EE(this.streamId,this.streamPartition)}toMessageRef(){return new RW(this.timestamp,this.sequenceNumber)}}var IW;e.StreamMessageType=void 0,(IW=e.StreamMessageType||(e.StreamMessageType={}))[IW.MESSAGE=0]="MESSAGE",IW[IW.GROUP_KEY_REQUEST=1]="GROUP_KEY_REQUEST",IW[IW.GROUP_KEY_RESPONSE=2]="GROUP_KEY_RESPONSE";class PW{messageId;prevMsgRef;messageType;content;contentType;signature;signatureType;encryptionType;groupKeyId;newGroupKey;constructor({messageId:t,prevMsgRef:r,messageType:n=e.StreamMessageType.MESSAGE,content:i,contentType:s,signature:o,signatureType:a,encryptionType:c,groupKeyId:u,newGroupKey:l}){!function(e,t){if(void 0===t)return;const r=e.toMessageRef().compareTo(t);if(0===r)throw new AW(`prevMessageRef cannot be identical to current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`);if(r<0)throw new AW(`prevMessageRef must come before current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`)}(t,r),c===e.EncryptionType.AES&&SW("groupKeyId",u),this.messageId=t,this.prevMsgRef=r,this.messageType=n,this.contentType=s,this.encryptionType=c,this.groupKeyId=u,this.newGroupKey=l,this.signature=o,this.signatureType=a,this.content=i}getStreamId(){return this.messageId.streamId}getStreamPartition(){return this.messageId.streamPartition}getStreamPartID(){return this.messageId.getStreamPartID()}getTimestamp(){return this.messageId.timestamp}getSequenceNumber(){return this.messageId.sequenceNumber}getPublisherId(){return this.messageId.publisherId}getMsgChainId(){return this.messageId.msgChainId}getMessageRef(){return new RW(this.getTimestamp(),this.getSequenceNumber())}getParsedContent(){if(this.encryptionType!==e.EncryptionType.NONE||this.contentType===e.ContentType.BINARY)return this.content;if(this.contentType!==e.ContentType.JSON)throw new uA(`Unknown content type: ${this.contentType}`,"ASSERTION_FAILED",this);try{return JSON.parse(fw(this.content))}catch(e){throw new uA(`Unable to parse JSON: ${e}`,"INVALID_MESSAGE_CONTENT",this)}}static isAESEncrypted(t){return t.encryptionType===e.EncryptionType.AES}}class TW{static toProtobuf(t){const r={timestamp:t.getTimestamp(),sequenceNumber:t.getSequenceNumber(),streamId:t.getStreamId(),streamPartition:t.getStreamPartition(),publisherId:RE(t.getPublisherId()),messageChainId:t.getMsgChainId()};let n,i;if(t.prevMsgRef&&(n={timestamp:t.prevMsgRef.timestamp,sequenceNumber:t.prevMsgRef.sequenceNumber}),t.messageType===e.StreamMessageType.MESSAGE){let e;t.newGroupKey&&(e={id:t.newGroupKey.id,data:t.newGroupKey.data}),i={oneofKind:"contentMessage",contentMessage:{content:t.content,contentType:t.contentType,encryptionType:t.encryptionType,groupKeyId:t.groupKeyId??void 0,newGroupKey:e}}}else if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)i={oneofKind:"groupKeyRequest",groupKeyRequest:DH.fromBinary(t.content)};else{if(t.messageType!==e.StreamMessageType.GROUP_KEY_RESPONSE)throw new Error("invalid message type");i={oneofKind:"groupKeyResponse",groupKeyResponse:BH.fromBinary(t.content)}}return{messageId:r,previousMessageRef:n,signature:t.signature,signatureType:t.signatureType,body:i}}static toClientProtocol(t){let r,n,i,s,o=e.ContentType.BINARY,a=e.EncryptionType.NONE;if("contentMessage"===t.body.oneofKind)r=e.StreamMessageType.MESSAGE,n=t.body.contentMessage.content,o=t.body.contentMessage.contentType,a=t.body.contentMessage.encryptionType,i=t.body.contentMessage.newGroupKey,s=t.body.contentMessage.groupKeyId;else if("groupKeyRequest"===t.body.oneofKind){r=e.StreamMessageType.GROUP_KEY_REQUEST;try{n=DH.toBinary(t.body.groupKeyRequest)}catch(e){throw new Error(`invalid group key request: ${e}`)}}else{if("groupKeyResponse"!==t.body.oneofKind)throw new Error("invalid message type");r=e.StreamMessageType.GROUP_KEY_RESPONSE;try{n=BH.toBinary(t.body.groupKeyResponse)}catch(e){throw new Error(`invalid group key response: ${e}`)}}const c=new CW(t.messageId.streamId,t.messageId.streamPartition,Number(t.messageId.timestamp),t.messageId.sequenceNumber,kE(t.messageId.publisherId),t.messageId.messageChainId);let u;t.previousMessageRef&&(u=new RW(Number(t.previousMessageRef.timestamp),t.previousMessageRef.sequenceNumber));return new PW({messageId:c,prevMsgRef:u,messageType:r,content:n,contentType:o,signature:t.signature,signatureType:t.signatureType,encryptionType:a,groupKeyId:s,newGroupKey:i})}}function _W(e){return TW.toClientProtocol(xH.fromBinary(e))}async function*NW(e,t,r){let n=0;for await(const r of e){try{await t(r,n,e)}catch(e){throw e}finally{n+=1}yield r}}async function*MW(e,t,r){let n=0;for await(const r of e)try{yield await t(r,n,e)}catch(e){throw e}finally{n+=1}}async function*xW(e,t,r){let n=0;for await(const i of e){let s;try{s=await t(i,n,e)}catch(e){if(r){await r(e,i);continue}throw e}finally{n+=1}s&&(yield i)}}class OW{isLocked=!1;pending;open(){this.isLocked||this.clearPending()}lock(){this.isLocked||(this.isLocked=!0,this.clearPending())}error(e){this.isLocked||this.clearPending(e)}close(){this.isLocked||(this.pending??=new eb)}setOpenState(e){e?this.open():this.close()}isOpen(){return!this.isLocked&&!this.pending}clearPending(e){const{pending:t}=this;t&&(this.pending=void 0,e?t.reject(e):t.resolve(void 0))}async check(){return this.pending&&await this.pending,!this.isLocked}}class DW{buffer=[];bufferSize;writeGate;readGate;error;iterator;isIterating=!1;constructor(e=256){if(!(e>0&&Number.isSafeInteger(e)))throw new uA(`bufferSize must be a safe positive integer, got: ${e}`,"INVALID_ARGUMENT");this.bufferSize=e,this.writeGate=new OW,this.readGate=new OW,this.writeGate.close(),this.readGate.close(),this.iterator=this.iterate()}async push(e){return!!this.isWritable()&&(this.buffer.push(e),this.updateWriteGate(),this.readGate.open(),this.writeGate.check())}updateWriteGate(){this.writeGate.setOpenState(!this.isFull())}end(e){e&&(this.error=e),this.lock()}lock(){this.writeGate.lock(),this.readGate.lock()}endWrite(e){e&&!this.error&&(this.error=e),this.readGate.open(),this.writeGate.lock()}isFull(){return this.buffer.length>=this.bufferSize}isDone(){return this.writeGate.isLocked&&this.readGate.isLocked}isWritable(){return!this.writeGate.isLocked&&!this.readGate.isLocked}async*iterate(){this.isIterating=!0;try{for(;!this.readGate.isLocked;){for(;this.buffer.length&&!this.readGate.isLocked;){const t=this.buffer.shift();if(this.updateWriteGate(),(e=t)&&(e instanceof Error||e?.stack&&e.message&&"string"==typeof e.stack&&"string"==typeof e.message))throw t;yield t}if(0===this.buffer.length&&this.writeGate.isLocked)break;if(this.isDone())break;this.readGate.close();if(!await this.readGate.check())break}const{error:t}=this;if(t)throw this.error=void 0,t}finally{this.buffer=[],this.lock()}var e}get length(){return this.buffer.length}clear(){this.buffer=[]}async throw(e){return this.endWrite(e),this.iterator.throw(e)}async return(e){return this.end(),this.iterator.return(e)}next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new this.constructor.Error(this,"already iterating");return this}async[Symbol.asyncDispose](){this.end()}}var BW,LW,FW=pt();function UW(e,t){if("pipe"in e)return e;const r=new Tr.PassThrough(t);return async function(e,t){const r=e.getReader(),n=new AbortController;try{for(;;){const{value:e,done:i}=await r.read();if(i)break;if(!t.writable)break;if(!t.write(e))try{await FW.once(t,"drain",n)}catch(e){if("AbortError"===e.name)break;throw e}}}catch(e){t.destroy(e),n.abort()}finally{t.end();try{await r.cancel()}catch(e){}r.releaseLock()}}(e,r),r}var jW=function(){if(LW)return BW;LW=1;var e=Ju(),t=0;return BW=function(r){var n=++t;return e(r)+n},BW}(),qW=n(jW);let zW;function KW(e=""){return void 0===zW&&(zW=xF()),qW(`${zW}${e?`-${e}`:""}`)}const GW=new Bv("sdk-utils"),VW=((e,{maxPrefixes:t=256}={})=>{let r={},n=!1;const i=(i="ID",s="-")=>{if(r[i]=(r[i]+1||0)%Number.MAX_SAFE_INTEGER,!n){const e=Object.keys(r).length;e>t&&(n=!0,console.warn(`counterId should not be used for a large number of unique prefixes: ${e} > ${t}`))}return[e,i,r[i]].filter((e=>null!=e)).join(s)};return i.clear=(...e)=>{if(e.length){const[t]=e;delete r[t]}else r={}},i})();function HW(e){return bE("/assignments",nb(e))}class $W{delegate;constructor(e){this.delegate=new Mj({maxSize:e,sizeCalculation:()=>1})}add(e){this.delegate.set(e,!0)}has(e){return this.delegate.has(e)}delete(e){this.delegate.delete(e)}}function WW(t){const r=t.type===e.NetworkNodeType.BROWSER?bq.BROWSER:bq.NODEJS,n={...t,nodeId:Yj(t.nodeId??t.id),type:r,websocket:t.websocket};return void 0!==n.id&&delete n.id,n}function JW(t){return{nodeId:Zj(t.nodeId),type:t.type===bq.NODEJS?e.NetworkNodeType.NODEJS:e.NetworkNodeType.BROWSER,websocket:t.websocket,region:t.region}}const QW=e=>Array.isArray(e)?e.map((e=>e.toString())).join("|"):e.toString();class ZW extends Error{response;constructor(e){super(`Fetch error, url=${e.url}`),this.response=e}}var YW,XW={exports:{}};var eJ=function(){if(YW)return XW.exports;YW=1;class e extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}}return XW.exports=({limit:t,interval:r,strict:n})=>{if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(r))throw new TypeError("Expected `interval` to be a finite number");const i=new Map;let s=0,o=0;const a=[];const c=n?function(){const e=Date.now();if(a.length<t)return a.push(e),0;const n=a.shift()+r;return e>=n?(a.push(e),0):(a.push(n),n-e)}:function(){const e=Date.now();return e-s>r?(o=1,s=e,0):(o<t?o++:(s+=r,o=1),s-e)};return t=>{const r=function(...e){if(!r.isEnabled)return(async()=>t.apply(this,e))();let n;return new Promise(((r,s)=>{n=setTimeout((()=>{r(t.apply(this,e)),i.delete(n)}),c()),i.set(n,s)}))};return r.abort=()=>{for(const t of i.keys())clearTimeout(t),i.get(t)(new e);i.clear(),a.splice(0,a.length)},r.isEnabled=!0,r}},XW.exports.AbortError=e,XW.exports}(),tJ=n(eJ);function rJ(e,t=1){const r=gD(t);return Object.assign(((...t)=>r((()=>e(...t)))),{clear(){r.clearQueue()}})}function nJ(e){let t={status:"init"};return Object.assign((async function(...r){const n=t;if("pending"===n.status)return n.promise;if("fulfilled"===n.status)return n.value;if("rejected"===n.status)throw n.reason;t=n;const i=(async()=>{try{const t=await e(...r);return Object.assign(n,{promise:void 0,status:"fulfilled",value:t}),t}catch(e){throw Object.assign(n,{promise:void 0,status:"rejected",reason:e}),e}})();return i.catch((()=>{})),Object.assign(n,{status:"pending",promise:i}),i}),{isStarted:()=>"init"!==t.status,reset(){t={status:"init"}}})}var iJ;!function(e){e.ONCE="ONCE",e.ONE="ONE",e.QUEUE="QUEUE",e.PARALLEL="PARALLEL"}(iJ||(iJ={}));class sJ{static TRIGGER_TYPE=iJ;static create(e=iJ.PARALLEL){return new this(e)}static once(){return this.create(iJ.ONCE)}static one(){return this.create(iJ.ONE)}static queue(){return this.create(iJ.QUEUE)}static parallel(){return this.create(iJ.PARALLEL)}listeners=[];isEnded=!1;triggerCountValue=0;triggerType;constructor(e=iJ.PARALLEL){switch(this.triggerType=e,this.trigger=Function.prototype.bind.call(this.trigger,this),e){case iJ.ONCE:this.trigger=nJ(this.trigger);break;case iJ.QUEUE:this.trigger=rJ(this.trigger);break;case iJ.ONE:this.trigger=function(e){const t=nJ(e);return async(...e)=>{try{return await t(...e)}finally{t.reset()}}}(this.trigger);break;case iJ.PARALLEL:break;default:throw new Error(`unknown trigger type: ${e}`)}}triggerCount(){return this.triggerCountValue}lastValue;end=(...e)=>{this.lastValue=e,this.isEnded=!0};wait(){return new Promise((e=>{this.once(((...t)=>e(t[0])))}))}async getLastValue(){if(this.currentTask&&await this.currentTask,!this.lastValue)throw new Error("Signal ended with no value");return this.lastValue}listen(e){return e?this.isEnded?(this.getLastValue().then((t=>e(...t))).catch((()=>{})),this):(this.listeners.push(e),this):new Promise((e=>{this.once(((...t)=>{e(t[0])}))}))}once(e){if(!e)return this.listen();const t=Object.assign(((...t)=>(this.unlisten(e),e(...t))),{listener:e});return this.listen(t)}countListeners(){return this.listeners.length}unlisten(e){const t=this.listeners.findIndex((t=>t===e||"listener"in t&&t.listener===e));return this.listeners.splice(t,1),this}async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{await t,await r(...e)}),Promise.resolve())}currentTask;async trigger(...e){const t=this.execTrigger(...e);this.currentTask=t;try{await this.currentTask}finally{this.currentTask===t&&(this.currentTask=void 0)}}async*[Symbol.asyncIterator](){for(;!this.isEnded;)yield await this.listen()}}class oJ extends sJ{seenErrors=new WeakSet;ignoredErrors=new WeakSet;minListeners=1;async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{try{await t}catch(e){return void await r(e)}await r(...e)}),Promise.resolve())}async trigger(...e){const t=e[0];if(this.ignoredErrors.has(t))return;if(this.seenErrors.has(t))throw t;this.seenErrors.add(t);const r=!!(this.countListeners()>=this.minListeners);try{if(await super.trigger(...e),!r)throw t;this.ignoredErrors.add(t)}catch(e){throw this.seenErrors.add(e),e}}}class aJ{source;transforms;constructor(e,t=[]){this.source=this.setSource(e),this.transforms=t}pipe(e){return this.transforms.push(e),this}clearTransforms(){this.transforms=[]}setSource(e){const t="id"in e?e.id:function(e,t=""){return VW(e.constructor.name)+t}(e,"Source");return this.source=Object.assign(e,{id:t}),this.source}getTransforms(){return this.transforms}}class cJ{source;iterator;isIterating=!1;isCleaningUp=!1;definition;constructor(e,t){this.source=e,this.definition=t??new aJ(e),this.cleanup=nJ(this.cleanup.bind(this)),this.iterator=function(e,t){if(!t)return async function*(){yield*e}();let r,n,i=!1,s=!1,o=e=>(n??=Promise.resolve(t(e)).finally((()=>{o=()=>{}})),n);function a(e){return async(...t)=>{if(s=!0,i)return e(...t);try{return await e(...t)}catch(e){throw r??=e,e}finally{await o(r)}}}const c=async function*(){i=!0;try{yield*e}catch(e){throw r??=e,e}finally{await o(r)}}(),u=c[Symbol.asyncIterator].bind(c);let l;return l="cancel"in e?Object.assign(c,{cancel:t=>e.cancel(t),isCancelled:()=>e.isCancelled()}):c,Object.assign(l,{return:a(l.return.bind(l)),throw:a(l.throw.bind(l)),[Symbol.asyncIterator]:()=>s&&!i?async function*(){try{"return"in e&&await e.return(void 0)}finally{await o()}}():u()})}(this.iterate(),this.cleanup),this.handleError=this.handleError.bind(this)}pipe(e){if(this.isIterating)throw new uA(`cannot pipe after already iterating: ${this.isIterating}`,"PIPELINE_ERROR");return this.definition.pipe(e),this}onFinally=sJ.once();onBeforeFinally=sJ.once();onMessage=sJ.create();onError=oJ.create();filter(e){return this.pipe((t=>xW(t,e,this.onError.trigger)))}flow(){return setImmediate((()=>{this.isIterating||async function(e,t=e=>e){(async e=>{for await(const t of e);})(NW(e,t))}(this)})),this}async cleanup(e){this.isCleaningUp=!0;try{try{e&&await this.onError.trigger(e)}finally{await this.definition.source.return(void 0)}}finally{await this.onBeforeFinally.trigger(),await this.onFinally.trigger(e),this.definition.clearTransforms()}}async handleError(e){await this.onError.trigger(e)}async*iterate(){if(this.isIterating=!0,!this.definition.source)throw new uA("no source","PIPELINE_ERROR");const e=this.definition.getTransforms().reduce(((e,t)=>t(e)),this.definition.source);try{for await(const t of e)await this.onMessage.trigger(t),yield t;this.isCleaningUp=!0}catch(e){this.isCleaningUp=!0,await this.handleError(e)}finally{this.isCleaningUp=!0,this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger()}}async throw(e){if(this.isCleaningUp)throw e;return this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.throw(e).catch((()=>{})),this.iterator.throw(e)}async return(e){return this.isCleaningUp?Promise.resolve({done:!0,value:e}):(this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.return(void 0),this.iterator.return(e))}async next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new uA("already iterating","PIPELINE_ERROR");return this}[Symbol.asyncDispose](){return this.cleanup()}}class uJ extends cJ{source;constructor(e=256){const t=new DW(e);super(t),this.source=t}pipe(e){return super.pipe(e),this}filter(e){return super.filter(e)}async push(e){return this.source.push(e)}async handleError(e){try{await this.onError.trigger(e)}catch(e){if(this.isCleaningUp)throw e;await this.push(e)}}end(e){this.source.end(e)}endWrite(e){this.source.endWrite(e)}isDone(){return this.source.isDone()}get length(){return this.source.length||0}clear(){this.source.clear()}}var lJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},hJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let dJ=class{onDestroy=sJ.once();trigger=this.destroy;abortSignal;constructor(){const e=new AbortController;this.abortSignal=e.signal,this.onDestroy.listen((()=>{e.abort()}))}destroy(){return this.onDestroy.trigger()}assertNotDestroyed(){if(this.isDestroyed())throw new uA("Client is destroyed. Create a new instance","CLIENT_DESTROYED")}isDestroyed(){return this.onDestroy.triggerCount()>0}};var fJ,pJ,gJ,mJ,yJ,bJ;dJ=lJ([q(d.ContainerScoped),hJ("design:paramtypes",[])],dJ);var wJ=function(){if(bJ)return yJ;bJ=1;var e=Jc(),t=function(){if(pJ)return fJ;pJ=1;var e=Vc(),t=$c(),r=Wc(),n=Jc(),i=Qc(),s=Zc(),o=Math.min;return fJ=function(a,c,u){for(var l=u?r:t,h=a[0].length,d=a.length,f=d,p=Array(d),g=1/0,m=[];f--;){var y=a[f];f&&c&&(y=n(y,i(c))),g=o(y.length,g),p[f]=!u&&(c||h>=120&&y.length>=120)?new e(f&&y):void 0}y=a[0];var b=-1,w=p[0];e:for(;++b<h&&m.length<g;){var v=y[b],E=c?c(v):v;if(v=u||0!==v?v:0,!(w?s(w,E):l(m,E,u))){for(f=d;--f;){var A=p[f];if(!(A?s(A,E):l(a[f],E,u)))continue e}w&&w.push(E),m.push(v)}}return m},fJ}(),r=nu(),n=function(){if(mJ)return gJ;mJ=1;var e=ou();return gJ=function(t){return e(t)?t:[]}}(),i=r((function(r){var i=e(r,n);return i.length&&i[0]===r[0]?t(i):[]}));return yJ=i}(),vJ=n(wJ),EJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},AJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},SJ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function kJ(e){const t=e;if(void 0!==t.id)return t.id;if(void 0!==t.stream)return t.stream;if(void 0!==t.streamId)return t.streamId;throw new Error('streamDefinition: object must have property: "id", "stream", or "streamId"')}let RJ=class{identity;constructor(e){this.identity=e}async toStreamID(e){let t;return wE.isPathOnlyFormat(e)&&(t=nb(await this.identity.getUserId())),bE(e,t)}async toStreamPartID(e){const[t,r]=await this.toStreamPartElements(e);return EE(t,r??0)}async toStreamPartElements(e){const[t,r]=function(e){if("string"==typeof e)return AE.parseRawElements(e);if("object"==typeof e)return[kJ(e),e.partition];throw new Error("streamDefinition: must be of type string or object")}(e);return[await this.toStreamID(t),r]}async getMatcher(e){const[t,r]=await this.toStreamPartElements(e);return e=>t===AE.getStreamID(e)&&(void 0===r||r===AE.getStreamPartition(e))}};RJ=EJ([q(d.ContainerScoped),SJ(0,U(kA)),AJ("design:paramtypes",[RA])],RJ);const CJ=e=>{try{return JSON.parse(e)}catch(e){return{}}},IJ=e=>{const t=e.partitions;if(void 0!==t)try{!function(e){if(!Number.isSafeInteger(e)||e<0||e>100)throw new Error(`invalid streamPartition value: ${e}`)}(t)}catch{throw new uA(`Invalid partition count: ${t}`,"INVALID_STREAM_METADATA")}return t??1};var PJ;e.StreamPermission=void 0,(PJ=e.StreamPermission||(e.StreamPermission={})).EDIT="edit",PJ.DELETE="delete",PJ.PUBLISH="publish",PJ.SUBSCRIBE="subscribe",PJ.GRANT="grant";const TJ="0x0000000000000000000000000000000000000000",_J=e=>!0===e.public,NJ=e=>"userId"in e?{...e,userId:kE(e.userId)}:e,MJ=t=>{switch(t){case e.StreamPermission.EDIT:return 0n;case e.StreamPermission.DELETE:return 1n;case e.StreamPermission.PUBLISH:return 2n;case e.StreamPermission.SUBSCRIBE:return 3n;case e.StreamPermission.GRANT:return 4n}return 0n},xJ=t=>{const r=Math.round(Date.now()/1e3),n=[];return t.canEdit&&n.push(e.StreamPermission.EDIT),t.canDelete&&n.push(e.StreamPermission.DELETE),t.publishExpiration>r&&n.push(e.StreamPermission.PUBLISH),t.subscribeExpiration>r&&n.push(e.StreamPermission.SUBSCRIBE),t.canGrant&&n.push(e.StreamPermission.GRANT),n};class OJ{delegate;pendingPromises=new Map;opts;constructor(e){this.delegate="maxSize"in e?new Mj({maxSize:e.maxSize,sizeCalculation:()=>1,ttl:e.maxAge}):new Map,this.opts={isCacheableValue:()=>!0,...e}}async get(e){const t=QW(e),r=this.pendingPromises.get(t);if(void 0!==r)return await r;{let r=this.delegate.get(t);if(void 0===r){const n=this.opts.valueFactory(e);let i;this.pendingPromises.set(t,n);try{i=await n}finally{this.pendingPromises.delete(t)}r={key:e,value:i},this.opts.isCacheableValue(i)&&this.delegate.set(t,r)}return r.value}}set(e,t){this.delegate.set(QW(e),{key:e,value:t})}invalidate(e){for(const[t,r]of this.delegate.entries())e(r.key)&&this.delegate.delete(t)}*values(){for(const e of this.delegate.values())yield e.value}}const DJ=e=>new OJ(e),BJ=e=>new OJ(e);var LJ,FJ,UJ,jJ,qJ,zJ,KJ,GJ;function VJ(){if(jJ)return UJ;jJ=1;var e=Pl(),t=uj(),r=function(){if(FJ)return LJ;FJ=1;var e=sL(),t=Ku();return LJ=function(r,n){return n.length<2?r:e(r,t(n,0,-1))},LJ}(),n=_l();return UJ=function(i,s){return s=e(s,i),null==(i=r(i,s))||delete i[n(t(s))]},UJ}var HJ,$J,WJ,JJ,QJ,ZJ,YJ,XJ,eQ=function(){if(GJ)return KJ;GJ=1;var e=uL(),t=function(){if(zJ)return qJ;zJ=1;var e=VJ(),t=Tl(),r=Array.prototype.splice;return qJ=function(n,i){for(var s=n?i.length:0,o=s-1;s--;){var a=i[s];if(s==o||a!==c){var c=a;t(a)?r.call(n,a,1):e(n,a)}}return n},qJ}();return KJ=function(r,n){var i=[];if(!r||!r.length)return i;var s=-1,o=[],a=r.length;for(n=e(n,3);++s<a;){var c=r[s];n(c,s,r)&&(i.push(c),o.push(s))}return t(r,o),i},KJ}(),tQ=n(eQ);function rQ(){if(JJ)return WJ;JJ=1;var e=YB(),t=$J?HJ:($J=1,HJ=function(){}),r=VB(),n=e&&1/r(new e([,-0]))[1]==1/0?function(t){return new e(t)}:t;return WJ=n}var nQ=function(){if(XJ)return YJ;XJ=1;var e=function(){if(ZJ)return QJ;ZJ=1;var e=Vc(),t=$c(),r=Wc(),n=Zc(),i=rQ(),s=VB();return QJ=function(o,a,c){var u=-1,l=t,h=o.length,d=!0,f=[],p=f;if(c)d=!1,l=r;else if(h>=200){var g=a?null:i(o);if(g)return s(g);d=!1,l=n,p=new e}else p=a?[]:f;e:for(;++u<h;){var m=o[u],y=a?a(m):m;if(m=c||0!==m?m:0,d&&y==y){for(var b=p.length;b--;)if(p[b]===y)continue e;a&&p.push(y),f.push(m)}else l(p,y,c)||(p!==f&&p.push(y),f.push(m))}return f},QJ}();return YJ=function(t){return t&&t.length?e(t):[]},YJ}(),iQ=n(nQ),sQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},oQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},aQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let cQ=class{listeners=[];providers;pollInterval;abortController;constructor(e,t){this.providers=e.getSubProviders(),this.pollInterval=t.contracts.pollInterval}on(e){const t=this.listeners.length>0;this.listeners.push(e),t||this.start()}off(e){const t=this.listeners.length>0;tQ(this.listeners,(t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.topicHash===e.contractInterfaceFragment.topicHash&&t.onEvent==e.onEvent)),t&&0===this.listeners.length&&this.abortController.abort()}start(){const e=new AbortController;this.abortController=e,setImmediate((async()=>{const t=new Bv("ChainEventPoller",{sessionId:Wv(6)});let r;t.debug("Start polling",{pollInterval:this.pollInterval});do{try{r=await oA(this.providers).getBlockNumber()}catch(e){t.debug("Failed to query block number",{err:e}),await Qv(1e3)}}while(void 0===r);let n=0;await Jv((async()=>{const i=oA(this.providers),s=this.listeners.map((e=>e.contractInterfaceFragment.name));let o,a=0;try{if(n>=30&&(a=await i.getBlockNumber()+1,t.debug("Fetch next block number explicitly",{newFromBlock:a}),e.signal.aborted))return;t.debug("Polling",{fromBlock:r,eventNames:s});const c={address:iQ(this.listeners.map((e=>e.contractAddress))),topics:[iQ(this.listeners.map((e=>e.contractInterfaceFragment.topicHash)))],fromBlock:r},u=await i.getLogs(c);o=[];for(const e of u){const t=this.listeners.find((t=>t.contractAddress===nb(e.address)&&t.contractInterfaceFragment.topicHash===e.topics[0]));if(void 0!==t){const r=new uN([t.contractInterfaceFragment.format("minimal")]).decodeEventLog(t.contractInterfaceFragment.name,e.data,e.topics);o.push({contractAddress:t.contractAddress,name:t.contractInterfaceFragment.name,args:r,blockNumber:e.blockNumber})}}t.debug("Polled",{fromBlock:r,events:o.length})}catch(e){t.debug("Failed to poll",{reason:e?.reason,eventNames:s,fromBlock:r})}if(!e.signal.aborted){if(void 0!==o&&o.length>0){for(const e of o){const t=this.listeners.filter((t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.name===e.name));for(const r of t)r.onEvent(e.args,e.blockNumber)}a=Math.max(...o.map((e=>e.blockNumber)))+1}void 0!==o&&a>r?(t.debug("Forward fromBlock",{before:r,after:a}),r=a,n=0):n+=1}}),this.pollInterval,!0,e.signal)}))}};cQ=sQ([q(d.ContainerScoped),aQ(1,U(cA)),oQ("design:paramtypes",[e.RpcProviderSource,Object])],cQ);const uQ=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),lQ=e=>`"${e}"`,hQ=e=>`{ ${e} }`,dQ=(t,r,n)=>{const i=[];return t.includes(e.StreamPermission.EDIT)&&i.push("canEdit: true"),t.includes(e.StreamPermission.DELETE)&&i.push("canDelete: true"),t.includes(e.StreamPermission.PUBLISH)&&i.push(`publishExpiration_gt: "${n}"`),t.includes(e.StreamPermission.SUBSCRIBE)&&i.push(`subscribeExpiration_gt: "${n}"`),t.includes(e.StreamPermission.GRANT)&&i.push("canGrant: true"),`${r}: [${i.map(hQ).join(", ")}]`},fQ=(t,r,n,i)=>{const s=[];if(s.push(`id_gt: "${uQ(n)}"`),void 0!==t&&s.push(`idAsString_contains: "${uQ(t)}"`),void 0!==r){const t=[],n=[r.userId];r.allowPublic&&n.push(TJ),t.push(`userId_in: [${n.map(lQ).join(",")}]`);const i=Math.round(Date.now()/1e3);void 0!==r.allOf&&t.push(dQ(r.allOf,"and",i));const o=r.anyOf??(void 0===r.allOf||0===r.allOf.length?Object.values(e.StreamPermission):void 0);void 0!==o&&t.push(dQ(o,"or",i)),s.push(`permissions_: { and: [${t.map(hQ).join(", ")}] }`)}return{query:`\n query {\n streams (\n first: ${i}\n orderBy: "id"\n where: {\n ${s.join(", ")}\n }\n ) {\n id\n metadata\n }\n }`}};var pQ,gQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},mQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},yQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const bQ=t=>{for(const r of t){const t=[e.StreamPermission.EDIT,e.StreamPermission.DELETE,e.StreamPermission.GRANT],n=vJ(r.permissions,t);if(n.length>0){const e=e=>new uA(`${e} is not supported for permission types: ${n.map((e=>e.toUpperCase())).join(", ")}`,"UNSUPPORTED_OPERATION");if(_J(r))throw e("Public permission");if(42!==r.userId.length)throw e("Non-Ethereum user id")}}},wQ=(e,t,r)=>{throw"CALL_EXCEPTION"===e.reason?.code?new uA("Stream not found: id="+t,"STREAM_NOT_FOUND"):new Error(`Could not reach the ${r} Smart Contract: ${e.message}`)},vQ=(e,t)=>{e.invalidate((e=>(Array.isArray(e)?e[0]:e)===t))};let EQ=pQ=class{streamRegistryContract;streamRegistryContractReadonly;contractFactory;rpcProviderSource;theGraphClient;streamIdBuilder;config;identity;logger;metadataCache;publisherCache;subscriberCache;publicSubscribePermissionCache;constructor(t,r,n,i,s,o,a,c,u){this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.streamIdBuilder=s,this.config=o,this.identity=a,this.logger=u.createLogger("StreamRegistry"),this.streamRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,this.rpcProviderSource.getProvider(),"streamRegistry"),wD({sourceDefinition:{contractInterfaceFragment:new uN(SA.StreamRegistryABI).getEvent("StreamCreated"),contractAddress:nb(this.config.contracts.streamRegistryChainAddress)},sourceEmitter:n,targetName:"streamCreated",targetEmitter:c,transformation:([e,t],r)=>({streamId:bE(e),metadata:CJ(t),blockNumber:r}),loggerFactory:u}),this.metadataCache=DJ({valueFactory:e=>this.getStreamMetadata_nonCached(e),...o.cache}),this.publisherCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.PUBLISH),...o.cache}),this.subscriberCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.SUBSCRIBE),...o.cache}),this.publicSubscribePermissionCache=DJ({valueFactory:t=>this.hasPermission({streamId:t,public:!0,permission:e.StreamPermission.SUBSCRIBE}),...o.cache})}async connectToContract(){if(void 0===this.streamRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,e,"streamRegistry")}}async createStream(e,t){const r=await nD(this.rpcProviderSource,this.config),n=wE.getDomainAndPath(e);if(void 0===n)throw new Error(`stream id "${e}" not valid`);const[i,s]=n;if(await this.connectToContract(),function(e){return tb(e)}(i)){await mD(this.streamRegistryContract.createStreamWithENS(i,s,JSON.stringify(t),r));try{await iE((async()=>this.streamExistsOnChain(e)),this.config._timeouts.ensStreamCreation.timeout,this.config._timeouts.ensStreamCreation.retryInterval)}catch{throw new Error(`unable to create stream "${e}"`)}}else await this.ensureStreamIdInNamespaceOfAuthenticatedUser(i,e),await mD(this.streamRegistryContract.createStream(s,JSON.stringify(t),r));this.populateMetadataCache(e,t)}async ensureStreamIdInNamespaceOfAuthenticatedUser(e,t){const r=nb(await this.identity.getUserId());if(e!==r)throw new Error(`stream id "${t}" not in namespace of authenticated user "${r}"`)}async setStreamMetadata(e,t){await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.updateStreamMetadata(e,JSON.stringify(t),r)),this.populateMetadataCache(e,t)}async deleteStream(e){const t=await this.streamIdBuilder.toStreamID(e);await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.deleteStream(t,r)),vQ(this.metadataCache,t),this.invalidatePermissionCaches(t)}async streamExistsOnChain(e){const t=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream exists on chain",{streamId:t}),this.streamRegistryContractReadonly.exists(t)}async getStreamMetadata_nonCached(e){let t;try{t=await this.streamRegistryContractReadonly.getStreamMetadata(e)}catch(t){return wQ(t,e,"StreamRegistry")}return CJ(t)}async*searchStreams(e,t){const r=async function*(e,t,r){yield*r.queryEntities(((r,n)=>fQ(e,t,r,n)))}(e,t,this.theGraphClient);for await(const e of r){const t=bE(e.id);this.populateMetadataCache(t,CJ(e.metadata)),yield t}}getStreamPublishers(e){return this.getStreamPublishersOrSubscribersList(e,"publishExpiration")}getStreamSubscribers(e){return this.getStreamPublishersOrSubscribersList(e,"subscribeExpiration")}async*getStreamPublishersOrSubscribersList(e,t){const r=await this.streamIdBuilder.toStreamID(e),n=xW(this.theGraphClient.queryEntities(((e,n)=>pQ.buildStreamPublishersOrSubscribersQuery(r,t,e,n))),(e=>null!==e.stream));yield*MW(n,(e=>kE(e.userId)))}static buildStreamPublishersOrSubscribersQuery(e,t,r,n){return{query:`\n {\n streamPermissions (\n first: ${n}\n orderBy: "id"\n where: {\n id_gt: "${r}"\n stream: "${e}"\n ${t}_gt: "${Math.round(Date.now()/1e3)}"\n }\n ) {\n id\n userId\n stream {\n id\n }\n }\n }`}}async hasPermission(e){if((e=>!0===e.public)(e)){const t=MJ(e.permission);return this.streamRegistryContractReadonly.hasPublicPermission(e.streamId,t)}{const t=e.allowPublic?await this.streamRegistryContractReadonly.getPermissionsForUserId(e.streamId,e.userId):await this.streamRegistryContractReadonly.getDirectPermissionsForUserId(e.streamId,e.userId);return xJ(t).includes(e.permission)}}async getPermissions(e){const t=await this.streamIdBuilder.toStreamID(e),r=await cE(this.theGraphClient.queryEntities(((e,r)=>({query:`{\n stream (id: "${t}") {\n id\n metadata\n permissions(first: ${r} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n userId\n canEdit\n canDelete\n publishExpiration\n subscribeExpiration\n canGrant\n }\n }\n }`})),(e=>{if(null!==e.stream)return e.stream.permissions;throw new uA("Stream not found: id="+t,"STREAM_NOT_FOUND")}))),n=[];return r.forEach((e=>{const t=xJ(e);t.length>0&&(e.userId===TJ?n.push({public:!0,permissions:t}):n.push({userId:kE(e.userId),permissions:t}))})),n}async grantPermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.grantPublicPermission(e,n,r):this.streamRegistryContract.grantPermissionForUserId(e,t,n,r)),...t)}async revokePermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.revokePublicPermission(e,n,r):this.streamRegistryContract.revokePermissionForUserId(e,t,n,r)),...t)}async updatePermissions(e,t,...r){const n=await this.streamIdBuilder.toStreamID(e);this.invalidatePermissionCaches(n),await this.connectToContract();for(const e of r)for(const r of e.permissions){const i=MJ(r),s=t(n,_J(e)?void 0:e.userId,i);await mD(s)}}async setPermissions(...t){const r=[],n=[],i=[];for(const s of t){bQ(s.assignments);const t=await this.streamIdBuilder.toStreamID(s.streamId);this.invalidatePermissionCaches(t),r.push(t),n.push(s.assignments.map((e=>_J(e)?TJ:e.userId))),i.push(s.assignments.map((t=>{return{canEdit:(r=t.permissions).includes(e.StreamPermission.EDIT),canDelete:r.includes(e.StreamPermission.DELETE),publishExpiration:r.includes(e.StreamPermission.PUBLISH)?PI:0n,subscribeExpiration:r.includes(e.StreamPermission.SUBSCRIBE)?PI:0n,canGrant:r.includes(e.StreamPermission.GRANT)};var r})))}await this.connectToContract();const s=await nD(this.rpcProviderSource,this.config),o=this.streamRegistryContract.setMultipleStreamPermissionsForUserIds(r,n,i,s);await mD(o)}async isStreamPublisherOrSubscriber_nonCached(e,t,r){try{return await this.hasPermission({streamId:e,userId:t,permission:r,allowPublic:!0})}catch(t){return wQ(t,e,"StreamPermission")}}getStreamMetadata(e){return this.metadataCache.get(e)}isStreamPublisher(e,t){return this.publisherCache.get([e,t])}isStreamSubscriber(e,t){return this.subscriberCache.get([e,t])}hasPublicSubscribePermission(e){return this.publicSubscribePermissionCache.get(e)}populateMetadataCache(e,t){this.metadataCache.set(e,t)}invalidatePermissionCaches(e){this.logger.trace("Clear permission caches for stream",{streamId:e}),vQ(this.publisherCache,e),vQ(this.subscriberCache,e)}};var AQ,SQ,kQ,RQ,CQ,IQ;EQ=pQ=gQ([q(d.ContainerScoped),yQ(5,U(cA)),yQ(6,U(kA)),mQ("design:paramtypes",[SD,e.RpcProviderSource,cQ,lE,RJ,Object,RA,sD,uD])],EQ);var PQ=function(){if(IQ)return CQ;IQ=1;var e=function(){if(SQ)return AQ;SQ=1;var e=Le();return AQ=function(t,r,n){for(var i=-1,s=t.length;++i<s;){var o=t[i],a=r(o);if(null!=a&&(void 0===c?a==a&&!e(a):n(a,c)))var c=a,u=o}return u},AQ}(),t=RQ?kQ:(RQ=1,kQ=function(e,t){return e<t}),r=Yc();return CQ=function(n){return n&&n.length?e(n,r,t):void 0},CQ}(),TQ=n(PQ),_Q=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},NQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},MQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const xQ=Symbol("GET_ALL_STORAGE_NODES");let OQ=class{streamStorageRegistryContract;streamStorageRegistryContractReadonly;streamIdBuilder;contractFactory;rpcProviderSource;theGraphClient;config;identity;logger;storageNodesCache;constructor(e,t,r,n,i,s,o,a,c){this.streamIdBuilder=e,this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.config=s,this.identity=o,this.logger=c.createLogger("StreamStorageRegistry"),this.streamStorageRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,r.getProvider(),"streamStorageRegistry"),this.initStreamAssignmentEventListeners(a,n,c),this.storageNodesCache=DJ({valueFactory:e=>this.getStorageNodes_nonCached(e),...s.cache})}initStreamAssignmentEventListeners(e,t,r){const n=([e,t],r)=>({streamId:bE(e),nodeAddress:nb(t),blockNumber:r}),i=nb(this.config.contracts.streamStorageRegistryChainAddress),s=new uN(SA.StreamStorageRegistryABI);wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Added"),contractAddress:i},sourceEmitter:t,targetName:"streamAddedToStorageNode",targetEmitter:e,transformation:n,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Removed"),contractAddress:i},sourceEmitter:t,targetName:"streamRemovedFromStorageNode",targetEmitter:e,transformation:n,loggerFactory:r})}async connectToContract(){if(!this.streamStorageRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamStorageRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,e,"streamStorageRegistry")}}async addStreamToStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Add stream to storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.addStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async removeStreamFromStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Remove stream from storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.removeStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async isStoredStream(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream is stored in storage node",{streamId:r,nodeAddress:t}),await this.streamStorageRegistryContractReadonly.isStorageNodeOf(r,t)}async getStoredStreams(e){this.logger.debug("Get stored streams of storage node",{nodeAddress:e});const t=[],r=(await cE(this.theGraphClient.queryEntities(((t,r)=>({query:`{\n node (id: "${e}") {\n id\n metadata\n lastSeen\n storedStreams (first: ${r} orderBy: "id" where: { id_gt: "${t}"}) {\n id,\n metadata\n }\n }\n _meta {\n block {\n number\n }\n }\n }`})),(e=>(t.push(e._meta.block.number),null!==e.node?e.node.storedStreams:[]))))).map((e=>({id:bE(e.id),metadata:CJ(e.metadata)})));return{streams:r,blockNumber:TQ(t)}}async getStorageNodes(e){const t=void 0!==e?await this.streamIdBuilder.toStreamID(e):xQ;return this.storageNodesCache.get(t)}async getStorageNodes_nonCached(e){let t;if(e!==xQ){const r=e;this.logger.debug("Get storage nodes of stream",{streamId:r}),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n stream (id: "${r}") {\n id\n metadata\n storageNodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }\n }`})),(e=>null!==e.stream?e.stream.storageNodes:[])))}else this.logger.debug("Get all storage nodes"),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n nodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }`}))));return t.map((e=>nb(e.id)))}};OQ=_Q([q(d.ContainerScoped),MQ(5,U(cA)),MQ(6,U(kA)),NQ("design:paramtypes",[RJ,SD,e.RpcProviderSource,cQ,lE,Object,RA,sD,uD])],OQ);
69
69
  /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
70
70
  const DQ=256,BQ=3329,{mod:LQ,nttZetas:FQ,NTT:UQ,bitsCoder:jQ}=Gp({N:DQ,Q:BQ,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),qQ=e=>jQ(e,(e=>{if(e>=12)return{encode:e=>e,decode:e=>e};const t=2**(e-1);return{encode:t=>((t<<e)+BQ/2)/BQ,decode:r=>r*BQ+t>>>e}})(e));function zQ(e,t){for(let r=0;r<DQ;r++)e[r]=LQ(e[r]+t[r])}function KQ(e,t){for(let o=0;o<128;o++){let a=FQ[64+(o>>1)];1&o&&(a=-a);const{c0:c,c1:u}=(r=e[2*o+0],n=e[2*o+1],i=t[2*o+0],s=t[2*o+1],{c0:LQ(n*s*a+r*i),c1:LQ(r*s+n*i)});e[2*o+0]=c,e[2*o+1]=u}var r,n,i,s;return e}function GQ(e){const t=new Uint16Array(DQ);for(let r=0;r<DQ;){const n=e();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let e=0;r<DQ&&e+3<=n.length;e+=3){const i=4095&(n[e+0]|n[e+1]<<8),s=4095&(n[e+1]>>4|n[e+2]<<4);i<BQ&&(t[r++]=i),r<DQ&&s<BQ&&(t[r++]=s)}}return t}function VQ(e,t,r,n){const i=e(n*DQ/4,t,r),s=new Uint16Array(DQ),o=Ci(i);let a=0;for(let e=0,t=0,r=0,i=0;e<o.length;e++){let c=o[e];for(let e=0;e<32;e++)r+=1&c,c>>=1,a+=1,a===n?(i=r,r=0):a===2*n&&(s[t++]=LQ(i-r),r=0,a=0)}if(a)throw new Error(`sampleCBD: leftover bits: ${a}`);return s}const HQ=e=>{const{K:t,PRF:r,XOF:n,HASH512:i,ETA1:s,ETA2:o,du:a,dv:c}=e,u=qQ(1),l=qQ(c),h=qQ(a),d=ao(co(qQ(12),t),32),f=co(qQ(12),t),p=ao(co(h,t),l),g=ao(32,32);return{secretCoder:f,secretKeyLen:f.bytesLen,publicKeyLen:d.bytesLen,cipherTextLen:p.bytesLen,keygen:e=>{io(e,32);const o=new Uint8Array(33);o.set(e),o[32]=t;const a=i(o),[c,u]=g.decode(a),l=[],h=[];for(let e=0;e<t;e++)l.push(UQ.encode(VQ(r,u,e,s)));const p=n(c);for(let e=0;e<t;e++){const n=UQ.encode(VQ(r,u,t+e,s));for(let r=0;r<t;r++){zQ(n,KQ(GQ(p.get(r,e)),l[r]))}h.push(n)}p.clean();const m={publicKey:d.encode([h,c]),secretKey:f.encode(l)};return uo(c,u,l,h,o,a),m},encrypt:(e,i,a)=>{const[c,l]=d.decode(e),h=[];for(let e=0;e<t;e++)h.push(UQ.encode(VQ(r,a,e,s)));const f=n(l),g=new Uint16Array(DQ),m=[];for(let e=0;e<t;e++){const n=VQ(r,a,t+e,o),i=new Uint16Array(DQ);for(let r=0;r<t;r++){zQ(i,KQ(GQ(f.get(e,r)),h[r]))}zQ(n,UQ.decode(i)),m.push(n),zQ(g,KQ(c[e],h[e])),i.fill(0)}f.clean();const y=VQ(r,a,2*t,o);zQ(y,UQ.decode(g));const b=u.decode(i);return zQ(b,y),uo(c,h,g,y),p.encode([m,b])},decrypt:(e,r)=>{const[n,i]=p.decode(e),s=f.decode(r),o=new Uint16Array(DQ);for(let e=0;e<t;e++)zQ(o,KQ(s[e],UQ.encode(n[e])));return function(e,t){for(let r=0;r<DQ;r++)e[r]=LQ(e[r]-t[r])}(i,UQ.decode(o)),uo(o,s,n),u.encode(i)}}};function $Q(e){const t=HQ(e),{HASH256:r,HASH512:n,KDF:i}=e,{secretCoder:s,cipherTextLen:o}=t,a=t.publicKeyLen,c=ao(t.secretKeyLen,t.publicKeyLen,32,32),u=c.bytesLen;return{publicKeyLen:a,msgLen:32,keygen:(e=so(64))=>{io(e,64);const{publicKey:n,secretKey:i}=t.keygen(e.subarray(0,32)),s=r(n),o=c.encode([i,n,s,e.subarray(32)]);return uo(i,s),{publicKey:n,secretKey:o}},encapsulate:(i,o=so(32))=>{io(i,a),io(o,32);const c=i.subarray(0,384*e.K),u=s.encode(s.decode(c.slice()));if(!oo(u,c))throw uo(u),new Error("ML-KEM.encapsulate: wrong publicKey modulus");uo(u);const l=n.create().update(o).update(r(i)).digest(),h=t.encrypt(i,o,l.subarray(32,64));return l.subarray(32).fill(0),{cipherText:h,sharedSecret:l.subarray(0,32)}},decapsulate:(e,r)=>{io(r,u),io(e,o);const[s,a,l,h]=c.decode(r),d=t.decrypt(e,s),f=n.create().update(d).update(l).digest(),p=f.subarray(0,32),g=t.encrypt(a,d,f.subarray(32,64)),m=oo(e,g),y=i.create({dkLen:32}).update(h).update(e).digest();return uo(d,g,m?y:p),m?p:y}}}const WQ={HASH256:Ys,HASH512:eo,KDF:no,XOF:Hp,PRF:function(e,t,r){return no.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}},JQ=$Q({...WQ,...{N:DQ,Q:BQ,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}}),QQ=Buffer.from("streamr-key-exchange"),ZQ=1568;class YQ{static async encryptForPublicKey(e,t,r){if(r===PH.ML_KEM)return this.encryptWithMLKEMPublicKey(e,t);if(r===PH.RSA)return this.encryptWithRSAPublicKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static async decryptWithPrivateKey(e,t,r){if(r===PH.ML_KEM)return this.decryptWithMLKEMPrivateKey(e,t);if(r===PH.RSA)return this.decryptWithRSAPrivateKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static toRSAPublicKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PUBLIC KEY-----")||!t.endsWith("-----END PUBLIC KEY-----\n"))throw new Error('"publicKey" must be an RSA public key (SPKI) in PEM format, encoded in UTF-8');return t}static toRSAPrivateKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PRIVATE KEY-----")||!t.endsWith("-----END PRIVATE KEY-----\n"))throw new Error('"privateKey" must be a PKCS#8 RSA private key in PEM format, encoded in UTF-8');return t}static encryptWithRSAPublicKey(e,t){const r=function(e,t){return Pv.publicEncrypt(e,t)}(this.toRSAPublicKeyString(t),e);return r}static decryptWithRSAPrivateKey(e,t){return function(e,t){return Pv.privateDecrypt(e,t)}(this.toRSAPrivateKeyString(t),e)}static async deriveAESWrapperKey(e,t){const r=Tv(),n=await r.importKey("raw",e,{name:"HKDF"},!1,["deriveKey"]),i=await r.deriveKey({name:"HKDF",hash:"SHA-512",salt:t,info:QQ},n,{name:"AES-CTR",length:256},!0,["encrypt","decrypt"]),s=await r.exportKey("raw",i);return new Uint8Array(s)}static async encryptWithMLKEMPublicKey(e,t){const{cipherText:r,sharedSecret:n}=JQ.encapsulate(t);if(r.length!==ZQ)throw new Error(`Expected KEM cipher to be 1568, but it was ${r.length} bytes`);const i=so(64),s=await this.deriveAESWrapperKey(n,i),o=this.encryptWithAES(e,Buffer.from(s));return Buffer.concat([r,i,o])}static async decryptWithMLKEMPrivateKey(e,t){let r=0;const n=e.slice(0,ZQ);r+=ZQ;const i=e.slice(r,r+64);r+=64;const s=e.slice(r),o=JQ.decapsulate(n,t),a=await this.deriveAESWrapperKey(o,i);return this.decryptWithAES(s,Buffer.from(a))}static encryptWithAES(e,t){const r=so(16),n=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createCipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,r);return Buffer.concat([r,n.update(e),n.final()])}static decryptWithAES(e,t){const r=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createDecipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,e.slice(0,16));return Buffer.concat([r.update(e.slice(16)),r.final()])}static decryptStreamMessage(e,t){let r,n;try{r=this.decryptWithAES(e.content,t.data)}catch{throw new uA("AES decryption failed","DECRYPT_ERROR",e)}if(e.newGroupKey)try{n=t.decryptNextGroupKey(e.newGroupKey)}catch{throw new uA("Could not decrypt new encryption key","DECRYPT_ERROR",e)}return[r,n]}}class XQ extends Error{groupKey;constructor(e,t){super(e),this.groupKey=t}}class eZ{id;data;constructor(e,t){if(this.id=e,!e)throw new XQ(`groupKeyId must not be falsey ${e}`);if(!t)throw new XQ(`groupKeyBufferOrHexString must not be falsey ${t}`);this.data=t,eZ.validate(this)}static validate(e){if(!e)throw new XQ(`value must be a ${this.name}: ${e}`,e);if(!(e instanceof this))throw new XQ(`value must be a ${this.name}: ${e}`,e);if(!e.id||"string"!=typeof e.id)throw new XQ(`${this.name} id must be a string: ${e}`,e);if(e.id.includes("---BEGIN"))throw new XQ(`${this.name} public/private key is not a valid group key id: ${e}`,e);if(!e.data||!Buffer.isBuffer(e.data))throw new XQ(`${this.name} data must be a Buffer: ${e}`,e);if(32!==e.data.length)throw new XQ("Group key must have a size of 256 bits, not "+8*e.data.length,e)}static generate(e=KW("GroupKey")){const t=so(32);return new eZ(e,Buffer.from(t))}encryptNextGroupKey(e){return{id:e.id,data:YQ.encryptWithAES(e.data,this.data)}}decryptNextGroupKey(e){return new eZ(e.id,YQ.decryptWithAES(e.data,this.data))}}const tZ=(e,t)=>t.some((t=>e instanceof t));let rZ,nZ;const iZ=new WeakMap,sZ=new WeakMap,oZ=new WeakMap;let aZ={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return iZ.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return hZ(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function cZ(e){aZ=e(aZ)}function uZ(e){return(nZ||(nZ=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(dZ(this),t),hZ(this.request)}:function(...t){return hZ(e.apply(dZ(this),t))}}function lZ(e){return"function"==typeof e?uZ(e):(e instanceof IDBTransaction&&function(e){if(iZ.has(e))return;const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),n()},s=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));iZ.set(e,t)}(e),tZ(e,rZ||(rZ=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,aZ):e)}function hZ(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(hZ(e.result)),n()},s=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",s)}));return oZ.set(t,e),t}(e);if(sZ.has(e))return sZ.get(e);const t=lZ(e);return t!==e&&(sZ.set(e,t),oZ.set(t,e)),t}const dZ=e=>oZ.get(e);const fZ=["get","getKey","getAll","getAllKeys","count"],pZ=["put","add","delete","clear"],gZ=new Map;function mZ(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(gZ.get(t))return gZ.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=pZ.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!fZ.includes(r))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return n&&(o=o.index(t.shift())),(await Promise.all([o[r](...t),i&&s.done]))[0]};return gZ.set(t,s),s}cZ((e=>({...e,get:(t,r,n)=>mZ(t,r)||e.get(t,r,n),has:(t,r)=>!!mZ(t,r)||e.has(t,r)})));const yZ=["continue","continuePrimaryKey","advance"],bZ={},wZ=new WeakMap,vZ=new WeakMap,EZ={get(e,t){if(!yZ.includes(t))return e[t];let r=bZ[t];return r||(r=bZ[t]=function(...e){wZ.set(this,vZ.get(this)[t](...e))}),r}};async function*AZ(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,EZ);for(vZ.set(r,t),oZ.set(r,dZ(t));t;)yield r,t=await(wZ.get(r)||t.continue()),wZ.delete(r)}function SZ(e,t){return t===Symbol.asyncIterator&&tZ(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&tZ(e,[IDBIndex,IDBObjectStore])}cZ((e=>({...e,get:(t,r,n)=>SZ(t,r)?AZ:e.get(t,r,n),has:(t,r)=>SZ(t,r)||e.has(t,r)})));class kZ{db;static async createInstance(e){const t=await function(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=hZ(o);return n&&o.addEventListener("upgradeneeded",(e=>{n(hZ(o.result),e.oldVersion,e.newVersion,hZ(o.transaction),e)})),r&&o.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(`streamr-sdk::${e.ownerId}`,1,{upgrade(t){e.namespaces.forEach((e=>t.createObjectStore(e)))}});return new kZ(t)}constructor(e){this.db=e}async exists(){throw new Error("Method not implemented in browser Persistence.")}async get(e,t){return this.db.get(t,e)}async set(e,t,r){await this.db.put(r,t,e)}async close(){}}var RZ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},CZ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},IZ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const PZ={ENCRYPTION_KEYS:"EncryptionKeys",LATEST_ENCRYPTION_KEY_IDS:"LatestEncryptionKeyIds"};let TZ=class{persistence;identity;loggerFactory;constructor(e,t,r){this.identity=e,this.loggerFactory=r,t.onDestroy.listen((()=>{if(void 0!==this.persistence)return this.persistence.close()}))}async ensureInitialized(){this.persistence??=await kZ.createInstance({loggerFactory:this.loggerFactory,ownerId:await this.identity.getUserId(),namespaces:Object.values(PZ),migrationsUrl:new URL("./encryption/migrations","undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("exports-umd.min.js",document.baseURI).href)})}async getPersistence(e){return await this.ensureInitialized(),{get:t=>this.persistence.get(t,e),set:(t,r)=>this.persistence.set(t,r,e)}}};TZ=RZ([q(d.ContainerScoped),IZ(0,U(kA)),CZ("design:paramtypes",[RA,dJ,uD])],TZ);var _Z=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},NZ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function MZ(e,t){return`${t}::${e}`}function xZ(e,t){return`${e}::${t}`}let OZ=class{persistenceManager;eventEmitter;logger;constructor(e,t,r){this.persistenceManager=e,this.eventEmitter=t,this.logger=r.createLogger("LocalGroupKeyStore")}async get(e,t){const r=await this.persistenceManager.getPersistence(PZ.ENCRYPTION_KEYS),n=await r.get(MZ(e,t));return void 0!==n?new eZ(e,Buffer.from(n,"hex")):void 0}async set(e,t,r){const n=await this.persistenceManager.getPersistence(PZ.ENCRYPTION_KEYS);await n.set(MZ(e,t),Buffer.from(r).toString("hex")),this.logger.debug("Set key",{keyId:e,publisherId:t}),this.eventEmitter.emit("encryptionKeyStoredToLocalStore",e)}async setLatestEncryptionKeyId(e,t,r){const n=await this.persistenceManager.getPersistence(PZ.LATEST_ENCRYPTION_KEY_IDS);this.logger.debug("Set latest encryptionKeyId",{keyId:e,publisherId:t,streamId:r}),await n.set(xZ(t,r),e)}async getLatestEncryptionKeyId(e,t){const r=await this.persistenceManager.getPersistence(PZ.LATEST_ENCRYPTION_KEY_IDS);return await r.get(xZ(e,t))}};var DZ,BZ,LZ,FZ,UZ,jZ,qZ,zZ,KZ,GZ,VZ,HZ,$Z,WZ,JZ,QZ,ZZ,YZ,XZ,eY,tY,rY,nY,iY,sY,oY,aY,cY,uY,lY,hY,dY,fY,pY,gY,mY,yY,bY,wY,vY,EY,AY,SY,kY,RY,CY;function IY(){if(GZ)return KZ;GZ=1;var e=$B(),t=Nh(),r=QB(),n=JB(),i=Object.getOwnPropertySymbols?function(n){for(var i=[];n;)e(i,r(n)),n=t(n);return i}:n;return KZ=i}function PY(){if(WZ)return $Z;WZ=1;var e=WB(),t=IY(),r=Id();return $Z=function(n){return e(n,r,t)},$Z}function TY(){if(iY)return nY;iY=1;var e=Ih(),t=function(){if(YZ)return ZZ;YZ=1;var e=Ih();return ZZ=function(t,r){var n=r?e(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)},ZZ}(),r=function(){if(eY)return XZ;eY=1;var e=/\w*$/;return XZ=function(t){var r=new t.constructor(t.source,e.exec(t));return r.lastIndex=t.lastIndex,r}}(),n=function(){if(rY)return tY;rY=1;var e=Oe(),t=e?e.prototype:void 0,r=t?t.valueOf:void 0;return tY=function(e){return r?Object(r.call(e)):{}}}(),i=Ph();return nY=function(s,o,a){var c=s.constructor;switch(o){case"[object ArrayBuffer]":return e(s);case"[object Boolean]":case"[object Date]":return new c(+s);case"[object DataView]":return t(s,a);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return i(s,a);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(s);case"[object RegExp]":return r(s);case"[object Symbol]":return n(s)}},nY}function _Y(){if(cY)return aY;cY=1;var e=function(){if(oY)return sY;oY=1;var e=XB(),t=Be();return sY=function(r){return t(r)&&"[object Map]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isMap,i=n?t(n):e;return aY=i}function NY(){if(dY)return hY;dY=1;var e=function(){if(lY)return uY;lY=1;var e=XB(),t=Be();return uY=function(r){return t(r)&&"[object Set]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isSet,i=n?t(n):e;return hY=i}function MY(){if(pY)return fY;pY=1;var e=Yl(),t=(BZ||(BZ=1,DZ=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}),DZ),r=Rl(),n=function(){if(FZ)return LZ;FZ=1;var e=kd(),t=rA();return LZ=function(r,n){return r&&e(n,t(n),r)},LZ}(),i=function(){if(jZ)return UZ;jZ=1;var e=kd(),t=Id();return UZ=function(r,n){return r&&e(n,t(n),r)},UZ}(),s=Rh(),o=Th(),a=function(){if(zZ)return qZ;zZ=1;var e=kd(),t=QB();return qZ=function(r,n){return e(r,t(r),n)},qZ}(),c=function(){if(HZ)return VZ;HZ=1;var e=kd(),t=IY();return VZ=function(r,n){return e(r,t(r),n)},VZ}(),u=ZB(),l=PY(),h=XB(),d=function(){if(QZ)return JZ;QZ=1;var e=Object.prototype.hasOwnProperty;return JZ=function(t){var r=t.length,n=new t.constructor(r);return r&&"string"==typeof t[0]&&e.call(t,"index")&&(n.index=t.index,n.input=t.input),n},JZ}(),f=TY(),p=xh(),g=qu(),m=Kh(),y=_Y(),b=Ne(),w=NY(),v=rA(),E=Id(),A="[object Arguments]",S="[object Function]",k="[object Object]",R={};return R[A]=R["[object Array]"]=R["[object ArrayBuffer]"]=R["[object DataView]"]=R["[object Boolean]"]=R["[object Date]"]=R["[object Float32Array]"]=R["[object Float64Array]"]=R["[object Int8Array]"]=R["[object Int16Array]"]=R["[object Int32Array]"]=R["[object Map]"]=R["[object Number]"]=R[k]=R["[object RegExp]"]=R["[object Set]"]=R["[object String]"]=R["[object Symbol]"]=R["[object Uint8Array]"]=R["[object Uint8ClampedArray]"]=R["[object Uint16Array]"]=R["[object Uint32Array]"]=!0,R["[object Error]"]=R[S]=R["[object WeakMap]"]=!1,fY=function C(I,P,T,_,N,M){var x,O=1&P,D=2&P,B=4&P;if(T&&(x=N?T(I,_,N,M):T(I)),void 0!==x)return x;if(!b(I))return I;var L=g(I);if(L){if(x=d(I),!O)return o(I,x)}else{var F=h(I),U=F==S||"[object GeneratorFunction]"==F;if(m(I))return s(I,O);if(F==k||F==A||U&&!N){if(x=D||U?{}:p(I),!O)return D?c(I,i(x,I)):a(I,n(x,I))}else{if(!R[F])return N?I:{};x=f(I,F,O)}}M||(M=new e);var j=M.get(I);if(j)return j;M.set(I,x),w(I)?I.forEach((function(e){x.add(C(e,P,T,e,I,M))})):y(I)&&I.forEach((function(e,t){x.set(t,C(e,P,T,t,I,M))}));var q=L?void 0:(B?D?l:u:D?E:v)(I);return t(q||I,(function(e,t){q&&(e=I[t=e]),r(x,t,C(e,P,T,t,I,M))})),x},fY}function xY(){if(vY)return wY;vY=1;var e=$B(),t=function(){if(bY)return yY;bY=1;var e=Oe(),t=Oh(),r=qu(),n=e?e.isConcatSpreadable:void 0;return yY=function(e){return r(e)||t(e)||!!(n&&e&&e[n])}}();return wY=function r(n,i,s,o,a){var c=-1,u=n.length;for(s||(s=t),a||(a=[]);++c<u;){var l=n[c];i>0&&s(l)?i>1?r(l,i-1,s,o,a):e(a,l):o||(a[a.length]=l)}return a},wY}function OY(){if(kY)return SY;kY=1;var e=function(){if(AY)return EY;AY=1;var e=xY();return EY=function(t){return null!=t&&t.length?e(t,1):[]},EY}(),t=Xc(),r=ru();return SY=function(n){return r(t(n,void 0,e),n+"")}}OZ=_Z([q(d.ContainerScoped),NZ("design:paramtypes",[TZ,sD,uD])],OZ);var DY=function(){if(CY)return RY;CY=1;var e=Jc(),t=MY(),r=VJ(),n=Pl(),i=kd(),s=function(){if(mY)return gY;mY=1;var e=Gh();return gY=function(t){return e(t)?void 0:t}}(),o=OY(),a=PY(),c=o((function(o,c){var u={};if(null==o)return u;var l=!1;c=e(c,(function(e){return e=n(e,o),l||(l=e.length>1),e})),i(o,a(o),u),l&&(u=t(u,7,s));for(var h=c.length;h--;)r(u,c[h]);return u}));return RY=c}(),BY=n(DY),LY=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},FY=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let UY=class{theGraphClient;logger;constructor(e,t){this.theGraphClient=e,this.logger=t.createLogger("OperatorRegistry")}async findRandomNetworkEntrypoints(e,t,r){const n=this.theGraphClient.queryEntities((()=>({query:`{\n operators(\n orderBy: latestHeartbeatTimestamp\n orderDirection: desc\n first: ${t}\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }`}))),i=[];for await(const e of n)i.push(JSON.parse(e.latestHeartbeatMetadata));const s=JU(i).slice(0,e);return this.logger.debug(`Found ${i.length} network entrypoints, picked ${s.length}`,{picked:s}),s}async findOperatorsOnStream(e,t,r){const n={query:`{\n stream(id: "${e}") {\n sponsorships(where: { isRunning: true }) {\n stakes(first: ${t}, orderBy: updateTimestamp, orderDirection: desc) {\n operator (\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }\n }\n }\n }`},i=(await this.theGraphClient.queryEntity(n)).stream.sponsorships.flatMap((e=>e.stakes.map((e=>({operatorId:nb(e.operator.id),peerDescriptor:JSON.parse(e.operator.latestHeartbeatMetadata)})))));return i}};UY=LY([q(d.ContainerScoped),FY("design:paramtypes",[lE,uD])],UY);const jY=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const qY=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var zY;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(zY||(zY={}));const KY=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>qY},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",zY]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>jY}])}};const GY=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var VY,HY,$Y,WY,JY,QY;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(VY||(VY={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(HY||(HY={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}($Y||($Y={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(WY||(WY={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(JY||(JY={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(QY||(QY={}));const ZY=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>GY},{no:5,name:"ttl",kind:"scalar",T:13}])}};const YY=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const XY=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY}])}};const eX=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>dX}])}};const tX=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>rX}])}};const rX=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>GY},{no:5,name:"storedAt",kind:"message",T:()=>GY},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const nX=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const iX=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>dX},{no:2,name:"requestId",kind:"scalar",T:9}])}};const sX=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const oX=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>dX},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>dX},{no:3,name:"requestId",kind:"scalar",T:9}])}};const aX=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",VY]}])}};const cX=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>dX},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>rX},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>dX}])}};const uX=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const lX=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const hX=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const dX=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",HY]},{no:3,name:"udp",kind:"message",T:()=>fX},{no:4,name:"tcp",kind:"message",T:()=>fX},{no:5,name:"websocket",kind:"message",T:()=>fX},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const fX=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const pX=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>dX},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>vX},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>dX},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>dX},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const gX=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",WY]}])}};const mX=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const yX=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>fX},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const bX=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>dX},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>dX},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const wX=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>dX},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",JY]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const vX=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>dX},{no:3,name:"targetDescriptor",kind:"message",T:()=>dX},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>KY},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>mX},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>yX},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>bX},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>wX},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>aX}])}};const EX=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const AX=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const SX=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const kX=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const RX=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const CX=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const IX=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const PX=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const TX=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",QY]}])}};const _X=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const NX=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const MX=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>rX}])}};const xX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const OX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>dX}])}};new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:nX,O:iX},{name:"getClosestRingPeers",options:{},I:sX,O:oX},{name:"ping",options:{},I:uX,O:lX},{name:"leaveNotice",options:{},I:hX,O:jY}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:pX,O:gX},{name:"forwardMessage",options:{},I:pX,O:gX}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:pX,O:gX}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:ZY,O:YY},{name:"replicateData",options:{},I:tX,O:jY}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:cX,O:jY}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:EX,O:jY}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:AX,O:jY},{name:"rtcOffer",options:{},I:SX,O:jY},{name:"rtcAnswer",options:{},I:kX,O:jY},{name:"iceCandidate",options:{},I:RX,O:jY}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:CX,O:PX},{name:"unlockRequest",options:{},I:IX,O:jY},{name:"gracefulDisconnect",options:{},I:TX,O:jY},{name:"setPrivate",options:{},I:_X,O:jY}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:NX,O:MX},{name:"externalStoreData",options:{},I:XY,O:eX},{name:"externalFindClosestNodes",options:{},I:xX,O:OX}]);const DX=new class extends wF{constructor(){super("OperatorDiscoveryRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9}])}};const BX=new class extends wF{constructor(){super("OperatorDiscoveryResponse",[{no:1,name:"operators",kind:"message",repeat:2,T:()=>dX}])}},LX=new vF("OperatorDiscovery",[{name:"discoverOperators",options:{},I:DX,O:BX}]);class FX{_transport;typeName=LX.typeName;methods=LX.methods;options=LX.options;constructor(e){this._transport=e}discoverOperators(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}var UX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},jX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},qX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let zX=class{createNetworkNode(e){return(e=>new EW(new vW(e)))(e)}};zX=UX([q(d.ContainerScoped)],zX);const KX=new Bv("NetworkNodeFacade");let GX=class{cachedNode;startNodeCalled=!1;startNodeComplete=!1;messageListeners=[];networkNodeFactory;operatorRegistry;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.networkNodeFactory=e,this.operatorRegistry=t,this.config=r,this.identity=n,this.eventEmitter=new Sl,this.destroySignal=i,i.onDestroy.listen(this.destroy)}async getNetworkOptions(){const e=await this.getEntryPoints(),t=this.config.network.controlLayer.peerDescriptor?WW(this.config.network.controlLayer.peerDescriptor):void 0;return{layer0:{...this.config.network.controlLayer,entryPoints:e.map(WW),peerDescriptor:t,websocketPortRange:null!==this.config.network.controlLayer.websocketPortRange?this.config.network.controlLayer.websocketPortRange:void 0},networkNode:{...BY(this.config.network.node,"contentDeliveryBufferWhileConnecting"),bufferWhileConnecting:this.config.network.node.contentDeliveryBufferWhileConnecting},metricsContext:new $v}}destroy=nJ((async()=>{const e=this.cachedNode;if(this.cachedNode=void 0,e&&this.startNodeCalled){if(!this.startNodeComplete){const e=this.startNodeTask();this.startNodeTask.reset(),await e}await e.stop()}this.startNodeTask.reset()}));startNodeTask=nJ((async(e=!0)=>{this.startNodeCalled=!0;try{const t=await this.initNode();return this.destroySignal.isDestroyed()||await t.start(e),t.addMessageListener((e=>{if(this.messageListeners.length>0)try{const t=TW.toClientProtocol(e);for(const e of this.messageListeners)e(t)}catch(e){KX.trace("Could not translate message",{err:e})}})),this.destroySignal.isDestroyed()?await t.stop():this.eventEmitter.emit("start"),this.destroySignal.assertNotDestroyed(),t}finally{this.startNodeComplete=!0}}));async initNode(){if(this.destroySignal.assertNotDestroyed(),this.cachedNode)return this.cachedNode;const e=this.networkNodeFactory.createNetworkNode(await this.getNetworkOptions());return this.destroySignal.isDestroyed()||(this.cachedNode=e),e}startNode=this.startNodeTask;getNode(){return this.destroySignal.assertNotDestroyed(),this.startNodeTask()}async getNodeId(){return(await this.getNode()).getNodeId()}async join(e,t,r){const n=await this.getNode();await n.join(e,t,r)}async leave(e){const t=await this.getNode();await t.leave(e)}async broadcast(e,t){(await this.getNode()).broadcast(TW.toProtobuf(e),t)}addMessageListener(e){this.messageListeners.push(e)}removeMessageListener(e){Ej(this.messageListeners,e)}async isProxiedStreamPart(e){return(await this.getNode()).isProxiedStreamPart(e)}async getMetricsContext(){return(await this.getNode()).getMetricsContext()}async getPeerDescriptor(){return(await this.getNode()).getPeerDescriptor()}async getDiagnosticInfo(){return(await this.getNode()).getDiagnosticInfo()}async getStreamParts(){return(await this.getNode()).getStreamParts()}async getNeighbors(e){return(await this.getNode()).getNeighbors(e)}async getOptions(){return(await this.getNode()).getOptions()}async inspect(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=WW(e);return this.cachedNode.inspect(r,t)}async setProxies(e,t,r,n){this.isStarting()&&await this.startNodeTask(!1);const i=t.map(WW);await this.cachedNode.setProxies(e,i,await this.identity.getUserId(),r,n)}async setStreamPartEntryPoints(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=t.map(WW);this.cachedNode.setStreamPartEntryPoints(e,r)}async discoverOperators(e,t){const r=await this.createExternalRpcClient(FX);return(await r.discoverOperators(DX.create({streamPartId:t}),{sourceDescriptor:await this.getPeerDescriptor(),targetDescriptor:WW(e)})).operators.map((e=>JW(e)))}async createExternalRpcClient(e){return this.isStarting()&&await this.startNodeTask(!1),this.cachedNode.createExternalRpcClient(e)}async registerOperator(e){(await this.getNode()).registerExternalNetworkRpcMethod(DX,BX,"discoverOperators",(async t=>{const r=AE.parse(t.streamPartId),n=e.getAssignedNodesForStreamPart(r);return BX.create({operators:n.map((e=>WW(e)))})}))}isStarting(){return!this.cachedNode||!this.startNodeComplete}once(e,t){this.eventEmitter.once(e,t)}async getEntryPoints(){const e=this.config.network.controlLayer.entryPointDiscovery,t=e?.enabled?await this.operatorRegistry.findRandomNetworkEntrypoints(e.maxEntryPoints,e.maxQueryResults,e.maxHeartbeatAgeHours):[];return[...this.config.network.controlLayer.entryPoints,...t]}};GX=UX([q(d.ContainerScoped),qX(2,U(cA)),qX(3,U(kA)),jX("design:paramtypes",[zX,UY,Object,RA,dJ])],GX);const VX=()=>Wv(20),HX=t=>{const r=Buffer.concat([Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}`),void 0!==t.prevMsgRef?Buffer.from(`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`):new Uint8Array(0)]);if(t.messageType===e.StreamMessageType.MESSAGE){const e=t.newGroupKey?Buffer.from(t.newGroupKey.id):void 0;return Buffer.concat([r,t.content,e??new Uint8Array(0),t.newGroupKey?.data??new Uint8Array(0)])}if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST){const e=DH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,e.publicKey,Buffer.concat(e.groupKeyIds.map((e=>pw(e))))])}if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE){const e=BH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,Buffer.concat(e.groupKeys.map((e=>Buffer.concat([pw(e.id),e.data]))))])}throw new Error(`Assertion failed: unknown message type ${t.messageType}`)};var $X=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},WX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},JX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};e.MessageSigner=class{identity;constructor(e){this.identity=e}async createSignedMessage(e,t){const r=await this.identity.createMessageSignature(HX(e));return new PW({...e,signature:r,signatureType:t})}},e.MessageSigner=$X([q(d.ContainerScoped),JX(0,U(kA)),WX("design:paramtypes",[RA])],e.MessageSigner);var QX=["function isValidSignature(bytes32 hash, bytes signature) view returns (bytes4 magicValue)"],ZX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},YX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const XX=new TE;let e0=class{contractsByAddress;publisherCache=new yE((()=>6e5));constructor(e,t){this.contractsByAddress=BJ({valueFactory:async r=>e.createReadContract(r,QX,t.getProvider(),"erc1271Contract")})}async isValidSignature(e,t,r){const n=function(e,t){return`${e}_${t}`}(e,kE(XX.recoverSignerUserId(r,t))),i=this.publisherCache.get(n);if(void 0!==i)return i;{const i=await this.contractsByAddress.get(e),s="0x1626ba7e"===await i.isValidSignature(XX.keccakHash(t),r);return this.publisherCache.set(n,s),s}}};e0=ZX([q(d.ContainerScoped),YX("design:paramtypes",[SD,e.RpcProviderSource])],e0);const t0=t=>{const r=void 0!==t.prevMsgRef?`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`:"",n=void 0!==t.newGroupKey?(({id:e,data:t})=>JSON.stringify([e,gw(t)]))(t.newGroupKey):"",i=t.encryptionType===e.EncryptionType.NONE?fw(t.content):gw(t.content);return Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}${r}${i}${n}`)};class r0 extends RA{publicKeyString;publicKey;privateKey;constructor(e,t){super(),this.publicKey=e,this.privateKey=t,this.publicKeyString=kE(this.publicKey),this.assertValidKeyPair()}async getUserIdRaw(){return this.publicKey}async getUserId(){return this.publicKeyString}async getPrivateKey(){return this.privateKey}async getTransactionSigner(e){throw new Error("This key pair can not sign transactions!")}static getKeyPairFromConfig(e){const t=e.auth;if(!t.privateKey)throw new Error("A privateKey was expected in the config, but none is defined!");return t}}const n0=new TE;class i0 extends r0{assertValidKeyPair(){n0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return n0.createSignature(e,this.privateKey)}async getTransactionSigner(e){const t=e.getProvider();return new GO(gw(this.privateKey),t)}static fromConfig(e){const t=e.auth.privateKey,r=e.auth.publicKey;return i0.fromPrivateKey(t,r)}static fromPrivateKey(e,t){return new i0(mw(t??new GO(e).address),mw(e))}static generate(){const e=n0.generateKeyPair();return new i0(e.publicKey,e.privateKey)}}class s0 extends RA{provider;expectedChainId;signer;cachedUserIdString;cachedUserIdBytes;rateLimitedSigner;constructor(e,t){super(),this.provider=e,this.expectedChainId=t,this.signer=e.getSigner(),this.rateLimitedSigner=rJ((async e=>{const t=await(await this.signer).signMessage(e);return await Qv(50),mw(t)}),1)}async getUserIdRaw(){return this.cachedUserIdBytes??=RE(await this.getUserId()),this.cachedUserIdBytes}async getUserId(){return this.cachedUserIdString??=kE(await(await this.signer).getAddress()),this.cachedUserIdString}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return this.rateLimitedSigner(e)}async getTransactionSigner(){if(void 0===this.expectedChainId)throw new Error("Streamr chainId not configuredin the StreamrClient options!");const e=(await this.provider.getNetwork()).chainId;if(e!==BigInt(this.expectedChainId))throw new Error(`Connect your wallet to the chain with chainId ${this.expectedChainId} (chainId of currently selected chain is ${e})`);return this.signer}static fromConfig(e){const t=e.auth?.ethereum,r=new Ex(t);return new s0(r,e.contracts.ethereumNetwork.chainId)}}const o0=PE.getInstance("ML_DSA_87");class a0 extends r0{assertValidKeyPair(){o0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ML_DSA_87}async createMessageSignature(e){return o0.createSignature(e,this.privateKey)}static fromConfig(e){const t=r0.getKeyPairFromConfig(e);if(!t.publicKey)throw new Error("ML-DSA identity requires a publicKey to be given in the config!");return new a0(mw(t.publicKey),mw(t.privateKey))}static generate(){const e=o0.generateKeyPair();return new a0(e.publicKey,e.privateKey)}}const c0=new _E;class u0 extends r0{cachedJWK;assertValidKeyPair(){c0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256R1}async createMessageSignature(e){return this.cachedJWK??=c0.privateKeyToJWK(this.privateKey),c0.createSignature(e,this.cachedJWK)}static fromConfig(e){const t=r0.getKeyPairFromConfig(e),r=mw(t.privateKey),n=t.publicKey?mw(t.publicKey):c0.getPublicKeyFromPrivateKey(r);return new u0(n,r)}static generate(){const e=c0.generateKeyPair();return new u0(e.publicKey,e.privateKey)}}const l0=[{keyType:"ECDSA_SECP256K1_EVM",fromConfig:i0.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256K1_EVM},{keyType:"ECDSA_SECP256R1",fromConfig:u0.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256R1},{keyType:"ML_DSA_87",fromConfig:a0.fromConfig,signatureType:e.SignatureType.ML_DSA_87}],h0="ECDSA_SECP256K1_EVM";["ECDSA_SECP256K1_EVM","ECDSA_SECP256R1","ML_DSA_87"].forEach((e=>{if(!l0.find((t=>t.keyType===e)))throw new Error(`keyType missing from IDENTITIES: ${e}`)}));var d0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},f0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const p0=Object.fromEntries(l0.map((e=>[e.signatureType,PE.getInstance(e.keyType)]))),g0=PE.getInstance("ECDSA_SECP256K1_EVM");let m0=class{erc1271ContractFacade;constructor(e){this.erc1271ContractFacade=e}async assertSignatureIsValid(e){let t;try{t=await this.validate(e)}catch(t){throw new uA(`An error occurred during address recovery from signature: ${t}`,"INVALID_SIGNATURE",e)}if(!t)throw new uA("Signature validation failed","INVALID_SIGNATURE",e)}async validate(t){const r=p0[t.signatureType];if(r)return r.verifySignature(RE(t.getPublisherId()),HX(t),t.signature);if(t.signatureType===e.SignatureType.ECDSA_SECP256K1_LEGACY)return g0.verifySignature(RE(t.getPublisherId()),t0(t),t.signature);if(t.signatureType===e.SignatureType.ERC_1271)return this.erc1271ContractFacade.isValidSignature(nb(t.getPublisherId()),HX(t),t.signature);throw new Error(`Cannot validate message signature, unsupported signatureType: "${t.signatureType}"`)}};m0=d0([q(d.ContainerScoped),f0("design:paramtypes",[e0])],m0);const y0=async(e,t,r,n)=>{await b0(e,t,r,n).catch((t=>{throw t.streamMessage??=e,t}))},b0=async(t,r,n,i)=>{switch(await n.assertSignatureIsValid(t),t.messageType){case e.StreamMessageType.MESSAGE:return w0(t,r,i);case e.StreamMessageType.GROUP_KEY_REQUEST:return v0(t,kE(DH.fromBinary(t.content).recipientId),t.getPublisherId(),r,i);case e.StreamMessageType.GROUP_KEY_RESPONSE:return v0(t,t.getPublisherId(),kE(BH.fromBinary(t.content).recipientId),r,i);default:throw new uA(`Unknown message type: ${t.messageType}!`,"ASSERTION_FAILED",t)}},w0=async(e,t,r)=>{const n=e.getStreamId();if(r.validation.partitions){const r=await t.getStreamMetadata(n),i=IJ(r);if(e.getStreamPartition()<0||e.getStreamPartition()>=i)throw new uA(`Partition ${e.getStreamPartition()} is out of range (0..${i-1})`,"INVALID_PARTITION",e)}if(r.validation.permissions){const r=e.getPublisherId();if(!await t.isStreamPublisher(n,r))throw new uA(`${r} is not a publisher on stream ${n}`,"MISSING_PERMISSION",e)}},v0=async(e,t,r,n,i)=>{if(i.validation.permissions){const i=e.getStreamId();if(!await n.isStreamPublisher(i,t))throw new uA(`${t} is not a publisher on stream ${i}`,"MISSING_PERMISSION",e);if(!await n.isStreamSubscriber(i,r))throw new uA(`${r} is not a subscriber on stream ${i}`,"MISSING_PERMISSION",e)}};async function E0(e,{isPrivate:t=!1}={}){const r=t?"pkcs8":"spki",n=function(e){return String.fromCharCode.apply(null,[...new Uint8Array(e)])}(await Tv().exportKey(r,e)),i=t?"PRIVATE":"PUBLIC";return`-----BEGIN ${i} KEY-----\n${btoa(n)}\n-----END ${i} KEY-----\n`}class A0{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return pw(this.publicKey)}getPrivateKey(){return pw(this.privateKey)}getEncryptionType(){return PH.RSA}static async create(e){const{privateKey:t,publicKey:r}=await async function(e){const{publicKey:t,privateKey:r}=await Tv().generateKey({name:"RSA-OAEP",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),[n,i]=await Promise.all([E0(r,{isPrivate:!0}),E0(t,{isPrivate:!1})]);return{privateKey:n,publicKey:i}}(e);return new A0(t,r)}}class S0{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return this.publicKey}getPrivateKey(){return this.privateKey}getEncryptionType(){return PH.ML_KEM}static create(){const e=JQ.keygen();return new S0(Buffer.from(e.secretKey),Buffer.from(e.publicKey))}}const k0=new Set([e.SignatureType.ML_DSA_87]),R0=new Set([PH.ML_KEM]),C0=new Set([e.EncryptionType.AES]);function I0(e,t){const r=C0.has(e),n=t.encryption?.requireQuantumResistantEncryption;return r||!n}function P0(e){return k0.has(e.getSignatureType())}const T0={Resends:Symbol("Resends"),Subscriber:Symbol("Subscriber")};var _0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},N0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},M0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let x0=class{keyPair;pendingRequests=new $W(5e4);networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;subscriber;identity;logger;ensureStarted;config;requestGroupKey;constructor(e,t,r,n,i,s,o,a,c){var u,l;this.networkNodeFacade=e,this.streamRegistry=t,this.signatureValidator=r,this.messageSigner=n,this.store=i,this.subscriber=s,this.identity=a,this.logger=c.createLogger("SubscriberKeyExchange"),this.config=o,void 0===o.encryption.keys?(this.ensureStarted=nJ((async()=>{this.keyPair=await async function(e,t){return t.encryption.requireQuantumResistantKeyExchange||P0(e)?S0.create():A0.create(t.encryption.rsaKeyLength)}(a,o),e.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),this.requestGroupKey=(u=(e,t,r)=>this.doRequestGroupKey(e,t,r),l=o.encryption.maxKeyRequestsPerSecond,tJ({limit:l,interval:1e3})(u))):(this.ensureStarted=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")},this.requestGroupKey=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")})}async doRequestGroupKey(e,t,r){await this.ensureStarted();const n=xF(),{message:i,request:s}=await this.createRequest(e,r,t,n);await this.networkNodeFacade.broadcast(i),this.pendingRequests.add(n),this.logger.debug("Sent group key request (waiting for response)",{groupKeyId:e,requestId:n,publisherId:t,keyEncryptionType:PH[s.encryptionType]})}async createRequest(t,r,n,i){const s={recipientId:RE(n),requestId:i,publicKey:this.keyPair.getPublicKey(),groupKeyIds:[t],encryptionType:this.keyPair.getEncryptionType()},o=this.subscriber.getERC1271ContractAddress(r);return{message:await this.messageSigner.createSignedMessage({messageId:new CW(AE.getStreamID(r),AE.getStreamPartition(r),Date.now(),0,void 0===o?await this.identity.getUserId():kE(o),VX()),content:DH.toBinary(s),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_REQUEST,encryptionType:e.EncryptionType.NONE},void 0===o?this.identity.getSignatureType():e.SignatureType.ERC_1271),request:s}}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE)try{const{requestId:e,recipientId:r,groupKeys:n,encryptionType:i}=BH.fromBinary(t.content),s=kE(r);await this.isAssignedToMe(t.getStreamPartID(),s,e)&&(this.logger.debug("Handle group key response",{requestId:e}),this.pendingRequests.delete(e),await y0(t,this.streamRegistry,this.signatureValidator,this.config),await Promise.all(n.map((async e=>{const r=await YQ.decryptWithPrivateKey(e.data,this.keyPair.getPrivateKey(),i);await this.store.set(e.id,t.getPublisherId(),r)}))))}catch(e){this.logger.debug("Failed to handle group key response",{err:e})}}async isAssignedToMe(e,t,r){if(this.pendingRequests.has(r)){const r=await this.identity.getUserId(),n=this.subscriber.getERC1271ContractAddress(e);return t===r||void 0!==n&&t===kE(n)}return!1}};x0=_0([q(d.ContainerScoped),M0(1,U(k((()=>EQ)))),M0(5,U(T0.Subscriber)),M0(6,U(cA)),M0(7,U(kA)),N0("design:paramtypes",[GX,EQ,m0,e.MessageSigner,OZ,Function,Object,RA,uD])],x0);var O0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},D0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},B0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const L0=async(e,t,r)=>{if(void 0!==r.keys)for(const n of Object.entries(r.keys))if(await t.toStreamID(n[0])===e)return new eZ(n[1].id,Buffer.from(mw(n[1].data)))};let F0=class{subscriberKeyExchange;localGroupKeyStore;explicitKeys;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i,s,o){this.subscriberKeyExchange=e,this.localGroupKeyStore=t,this.config=n,this.identity=i,this.eventEmitter=s,this.destroySignal=o,void 0!==n.encryption.keys&&(this.explicitKeys=BJ({valueFactory:async e=>L0(e,r,n.encryption)}))}async fetchKey(e,t,r){if(void 0!==this.explicitKeys){const r=await this.explicitKeys.get(AE.getStreamID(e));if(void 0!==r)return r;throw new uA(`No encryption key available for stream part ID: groupKeyId=${t}, streamPartId=${e}`,"UNEXPECTED_INPUT")}let n=await this.localGroupKeyStore.get(t,r);if(void 0!==n)return n;await this.subscriberKeyExchange.requestGroupKey(t,r,e);const i=await eE(this.eventEmitter,"encryptionKeyStoredToLocalStore",this.config.encryption.keyRequestTimeout,(e=>e===t),this.destroySignal.abortSignal);return n=await this.localGroupKeyStore.get(i[0],r),n}async fetchLatestEncryptionKey(e,t){if(e!==await this.identity.getUserId())throw new Error("storeKey: fetching latest encryption keys for other publishers not supported.");const r=await this.localGroupKeyStore.getLatestEncryptionKeyId(e,t);return void 0!==r?this.localGroupKeyStore.get(r,e):void 0}async storeKey(e,t,r){if(t!==await this.identity.getUserId())throw new Error("storeKey: storing latest encryption keys for other publishers not supported.");if(void 0===e){const t=Buffer.from(so(32));e=new eZ(KW("GroupKey"),t)}return await this.localGroupKeyStore.set(e.id,t,e.data),await this.localGroupKeyStore.setLatestEncryptionKeyId(e.id,t,r),e}addKeyToLocalStore(e,t){return this.localGroupKeyStore.set(e.id,t,e.data)}};F0=O0([q(d.ContainerScoped),B0(3,U(cA)),B0(4,U(kA)),D0("design:paramtypes",[x0,OZ,RJ,Object,RA,sD,dJ])],F0);class U0{busy=new uE(!0);inputBuffer=[];outputBuffer;processMessageFn;onError;constructor(e,t,r){this.outputBuffer=e,this.processMessageFn=t,this.onError=r}async addMessage(e){if(this.inputBuffer.push(e),this.busy.isOpen()){for(this.busy.close();this.inputBuffer.length>0;){const e=this.inputBuffer.shift();try{const t=await this.processMessageFn(e);this.outputBuffer.push(t)}catch(e){this.onError.trigger(e)}}this.busy.open()}}}class j0{outputBuffer=new DW;processors=new Map;processMessageFn;onError;constructor(e,t){this.processMessageFn=e,this.onError=t}addMessage(e){const t=`${e.getPublisherId()}-${e.getMsgChainId()}`;let r=this.processors.get(t);void 0===r&&(r=new U0(this.outputBuffer,this.processMessageFn,this.onError),this.processors.set(t,r)),r.addMessage(e)}async flush(){await Promise.all(Array.from(this.processors.values()).map((e=>e.busy.waitUntilOpen())))}stop(e){this.outputBuffer.endWrite(e)}[Symbol.asyncIterator](){return this.outputBuffer}}const q0=new Bv("GapFiller"),z0=async e=>{try{await e()}catch(e){if("AbortError"!==e.code)throw e}};class K0{currentTask=void 0;chain;resend;getStorageNodeAddresses;strategy;initialWaitTime;retryWaitTime;maxRequestsPerGap;constructor(e){this.chain=e.chain,this.resend=e.resend,this.getStorageNodeAddresses=e.getStorageNodeAddresses,this.strategy=e.strategy,this.initialWaitTime=e.initialWaitTime,this.retryWaitTime=e.retryWaitTime,this.maxRequestsPerGap=e.maxRequestsPerGap,e.abortSignal.addEventListener("abort",(()=>{this.currentTask?.abortController.abort()}))}start(){this.chain.on("gapFound",(e=>this.onGapFound(e))),this.chain.on("gapResolved",(()=>this.onGapResolved()))}async onGapFound(e){const t=new AbortController;this.currentTask={gap:e,abortController:t};try{await z0((async()=>{if(await Qv(this.initialWaitTime,t.signal),this.maxRequestsPerGap>0&&await this.fetchFromStorageNode(e,t.signal),"full"===this.strategy)this.chain.resolveMessages(e.to.getMessageRef(),!0);else{if("light"!==this.strategy)throw new Error(`Assertion failed: unexpected gap fill strategy "${this.strategy}"`);this.chain.resolveMessages(void 0,!1)}}))}catch(t){this.onError(t,e)}}onGapResolved(){void 0!==this.currentTask&&(this.currentTask.abortController.abort(),this.currentTask=void 0)}async fetchFromStorageNode(e,t){const r=await this.getStorageNodeAddresses();if(r.length>0)for(let n=0;n<this.maxRequestsPerGap;n++){try{await z0((async()=>{const n=this.resend(e,oA(r),t);for await(const e of n)this.chain.addMessage(e)}))}catch(t){this.onError(t,e)}n!==this.maxRequestsPerGap-1&&await Qv(this.retryWaitTime,t)}}onError(e,t){q0.debug("Unable to fill gap",{error:{message:e?.message,code:e?.code},context:this.chain.getContext(),from:t.from.getMessageRef(),to:t.to.getMessageRef()})}}const G0=new Bv("OrderedMessageChain"),V0=(e,t)=>0===e.compareTo(t);class H0{lastOrderedMsg;currentGap;pendingMsgs;eventEmitter;context;abortSignal;constructor(e,t){this.context=e,this.pendingMsgs=new fE(((e,t)=>e.getMessageRef().compareTo(t.getMessageRef()))),this.eventEmitter=new Sl,this.abortSignal=t,t.addEventListener("abort",(()=>{this.eventEmitter.removeAllListeners()}))}addMessage(e){this.isStaleMessage(e)||(this.pendingMsgs.push(e),this.consumePendingOrderedMessages((e=>this.isNextOrderedMessage(e))))}resolveMessages(e,t){this.consumePendingOrderedMessages((t=>{if(this.isNextOrderedMessage(t))return!0;if(void 0===e||t.getMessageRef().compareTo(e)<=0){const e={from:this.lastOrderedMsg,to:t};return this.eventEmitter.emit("unfillableGap",e),!0}return!1}),t)}async waitUntilIdle(){const e=()=>this.pendingMsgs.isEmpty()||this.abortSignal.aborted;if(!e()){const t=new uE(!1),r=()=>{e()&&t.open()};this.on("orderedMessageAdded",r),this.abortSignal.addEventListener("abort",r),await t.waitUntilOpen(),this.off("orderedMessageAdded",r),this.abortSignal.removeEventListener("abort",r)}}consumePendingOrderedMessages(e,t=!0){for(;!this.pendingMsgs.isEmpty()&&e(this.pendingMsgs.peek());){const e=this.pendingMsgs.pop();this.lastOrderedMsg=e,this.eventEmitter.emit("orderedMessageAdded",e),this.checkGapResolved()}t&&this.checkGapFound()}checkGapFound(){this.pendingMsgs.isEmpty()||void 0!==this.currentGap||(this.currentGap={from:this.lastOrderedMsg,to:this.pendingMsgs.peek()},G0.debug("Gap found",{context:this.context,from:this.currentGap.from.getMessageRef(),to:this.currentGap.to.getMessageRef()}),this.eventEmitter.emit("gapFound",this.currentGap))}checkGapResolved(){if(void 0!==this.currentGap&&V0(this.lastOrderedMsg.getMessageRef(),this.currentGap.to.getMessageRef())){const e=this.currentGap;this.currentGap=void 0,G0.debug("Gap resolved",{context:this.context,from:e.from.getMessageRef(),to:e.to.getMessageRef()}),this.eventEmitter.emit("gapResolved")}}isNextOrderedMessage(e){const t=e.prevMsgRef;return void 0===this.lastOrderedMsg||void 0===t||V0(t,this.lastOrderedMsg.getMessageRef())}isStaleMessage(e){return void 0!==this.lastOrderedMsg&&e.getMessageRef().compareTo(this.lastOrderedMsg.getMessageRef())<=0||this.pendingMsgs.contains(e)}getContext(){return this.context}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}class $0{chains;outBuffer=new DW;abortController=new AbortController;constructor(e,t,r,n,i){this.chains=BJ({valueFactory:async([s,o])=>{const a=((e,t,r,n,i,s)=>{const o=new H0(e,s);return o.on("unfillableGap",(e=>r(e))),new K0({chain:o,resend:async function*(t,r,i){const s=await n.resend(e.streamPartId,{from:{timestamp:t.from.getMessageRef().timestamp,sequenceNumber:t.from.getMessageRef().sequenceNumber+1},to:t.to.prevMsgRef,publisherId:e.publisherId,msgChainId:e.msgChainId,raw:!0},(async()=>[r]),i);yield*s},getStorageNodeAddresses:()=>t(AE.getStreamID(e.streamPartId)),strategy:i.gapFillStrategy,initialWaitTime:i.gapFillTimeout,retryWaitTime:i.retryResendAfter,maxRequestsPerGap:i.gapFill?i.maxGapRequests:0,abortSignal:s}).start(),o})({streamPartId:e,publisherId:s,msgChainId:o},t,r,n,i,this.abortController.signal);return a.on("orderedMessageAdded",(e=>this.onOrdered(e))),a}})}onOrdered(e){this.outBuffer.isDone()||pE((()=>this.outBuffer.push(e)))}destroy(){this.outBuffer.endWrite(),this.abortController.abort()}async addMessages(e){try{for await(const t of e){if(this.abortController.signal.aborted)return;(await this.chains.get([t.getPublisherId(),t.getMsgChainId()])).addMessage(t)}await Promise.all([...this.chains.values()].map((e=>e.waitUntilIdle()))),this.outBuffer.endWrite()}catch(e){this.outBuffer.endWrite(e)}}[Symbol.asyncIterator](){return this.outBuffer}}const W0=t=>{const r=t.loggerFactory.createLogger("messagePipeline"),n=new uJ,i=new j0((async n=>{if(await y0(n,t.streamRegistry,t.signatureValidator,t.config),n.encryptionType!==e.EncryptionType.NONE&&!I0(n.encryptionType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the encryption type violates configured requirements (encryptionType: ${n.encryptionType})!`,"ENCRYPTION_POLICY_VIOLATION",n);if(!function(e,t){const r=k0.has(e),n=t.encryption?.requireQuantumResistantSignatures;return r||!n}(n.signatureType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the signature type violates configured requirements (signatureType: ${n.encryptionType})!`,"SIGNATURE_POLICY_VIOLATION",n);let i;if(PW.isAESEncrypted(n))try{i=await(async(t,r,n)=>{if(n.isDestroyed())return t;let i;try{i=await r.fetchKey(t.getStreamPartID(),t.groupKeyId,t.getPublisherId())}catch{if(n.isDestroyed())return t;throw new uA(`Could not get encryption key ${t.groupKeyId}`,"DECRYPT_ERROR",t)}if(n.isDestroyed())return t;const[s,o]=YQ.decryptStreamMessage(t,i);return void 0!==o&&await r.addKeyToLocalStore(o,t.getPublisherId()),new PW({...t,content:s,encryptionType:e.EncryptionType.NONE})})(n,t.groupKeyManager,t.destroySignal)}catch(e){throw r.debug("Failed to decrypt",{messageId:n.messageId,err:e}),t.streamRegistry.invalidatePermissionCaches(n.getStreamId()),e}else i=n;return i.getParsedContent(),i}),n.onError),s=new WeakSet;if(n.onError.listen(((e,t)=>{throw t&&s.add(t.messageId),e&&"messageId"in e&&e.messageId&&s.add(e.messageId),e})),t.config.orderMessages){const e=new $0(t.streamPartId,t.getStorageNodes,(()=>{}),t.resends,t.config);n.pipe((async function*(t){setImmediate((()=>{e.addMessages(t)})),yield*e})),n.onBeforeFinally.listen((()=>{e.destroy()}))}return n.pipe((async function*(e){setImmediate((async()=>{let t;try{for await(const t of e)i.addMessage(t)}catch(e){t=e}await i.flush(),i.stop(t)})),yield*i})).filter((e=>!s.has(e.messageId))),n};var J0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},Q0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},Z0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let Y0=class{resends;streamStorageRegistry;streamRegistry;signatureValidator;groupKeyManager;config;destroySignal;loggerFactory;constructor(e,t,r,n,i,s,o,a){this.resends=e,this.streamStorageRegistry=t,this.streamRegistry=r,this.signatureValidator=n,this.groupKeyManager=i,this.config=s,this.destroySignal=o,this.loggerFactory=a}createMessagePipeline(e){return W0({...e,getStorageNodes:e.getStorageNodes??(e=>this.streamStorageRegistry.getStorageNodes(e)),resends:this.resends,streamRegistry:this.streamRegistry,signatureValidator:this.signatureValidator,groupKeyManager:this.groupKeyManager,config:e.config??this.config,destroySignal:this.destroySignal,loggerFactory:this.loggerFactory})}};Y0=J0([q(d.ContainerScoped),Z0(0,U(T0.Resends)),Z0(2,U(k((()=>EQ)))),Z0(4,U(k((()=>F0)))),Z0(5,U(cA)),Q0("design:paramtypes",[Function,OQ,EQ,m0,F0,Object,dJ,uD])],Y0);var X0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},e1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},t1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const r1=(e,t,r,n={})=>{const i={...n,format:"raw"},[s,o]=AE.getStreamIDAndPartition(r),a=(e=>{const t=Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)));return new URLSearchParams(t).toString()})(i);return`${e}/streams/${encodeURIComponent(s)}/data/partitions/${o}/${t}?${a}`},n1=e=>({...e,publisherId:"publisherId"in e&&void 0!==e.publisherId?kE(e.publisherId):void 0});let i1=class{storageNodeRegistry;messagePipelineFactory;config;logger;constructor(e,t,r,n){this.storageNodeRegistry=e,this.messagePipelineFactory=t,this.config=r,this.logger=n.createLogger("Resends")}async resend(e,t,r,n){const i=t.raw??!1;if(function(e){return e&&"object"==typeof e&&"last"in e&&null!=e.last}(t)){if(t.last<=0){const e=new uJ;return e.endWrite(),e}return this.fetchStream("last",e,{count:t.last},i,r,n)}if(function(e){return e&&"object"==typeof e&&"from"in e&&"to"in e&&e.to&&null!=e.from}(t))return this.fetchStream("range",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,toTimestamp:new Date(t.to.timestamp).getTime(),toSequenceNumber:t.to.sequenceNumber,publisherId:t.publisherId,msgChainId:t.msgChainId},i,r,n);if(function(e){return e&&"object"==typeof e&&"from"in e&&!("to"in e)&&null!=e.from}(t))return this.fetchStream("from",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,publisherId:t.publisherId},i,r,n);throw new uA(`can not resend without valid resend options: ${JSON.stringify({streamPartId:e,options:t})}`,"INVALID_ARGUMENT")}async fetchStream(e,t,r,n,i,s){const o=Wv(5);this.logger.debug("Fetch resend data",{loggerIdx:o,resendType:e,streamPartId:t,query:r});const a=AE.getStreamID(t),c=await i(a);if(!c.length)throw new uA(`no storage assigned: ${a}`,"NO_STORAGE_NODES");const u=c[XE(0,c.length-1)],l=(await this.storageNodeRegistry.getStorageNodeMetadata(u)).urls,h=r1(oA(l),e,t,r),d=n?new uJ:this.messagePipelineFactory.createMessagePipeline({streamPartId:t,getStorageNodes:async()=>ju(c,u),config:1===c.length?{...this.config,orderMessages:!1}:this.config}),f=async function*(e,t){try{for await(const t of e)yield t}catch(e){throw await t(e)}}(async function*(e,t){GW.debug("Send HTTP request",{url:e});const r=new AbortController,n=rE(r.signal,t);try{const t=await fetch(e,{signal:n});if(GW.debug("Received HTTP response",{url:e,status:t.status}),!t.ok)throw new ZW(t);if(!t.body)throw new Error("No Response Body");let i;try{const e=UW(t.body);i=e.pipe(new gE),e.on("error",(e=>i.destroy(e))),i.once("close",(()=>{r.abort()})),yield*i}catch(e){throw r.abort(),e}finally{i?.destroy()}}finally{n.destroy()}}(h,s),(async e=>{let t;if(e instanceof ZW){const r=await e.response.text();let n;try{n=`: ${JSON.parse(r).error}`}catch{n=""}t=`Storage node fetch failed${n}, httpStatus=${e.response.status}, url=${e.response.url}`}else t=e?.message??"Unknown error";return new uA(t,"STORAGE_NODE_ERROR")}));return setImmediate((async()=>{let e=0;const t=MW(f,(e=>_W(e)));await async function(e,t){if(!e)throw new Error("no source");try{for await(const r of e)if(!await t.push(r))break}catch(e){t.endWrite(e)}finally{t.endWrite()}}(NW(t,(()=>e++)),d),this.logger.debug("Finished resend",{loggerIdx:o,messageCount:e})})),d}};function s1(e){return e.filter(Boolean).join("\n")}function o1(e){return e.flatMap((e=>function(e){return e instanceof a1?[e.ownStack,...[...e.errors].map((({stack:e})=>e))]:[e.stack]}(e))).filter(Boolean).join("\n")}i1=X0([j(),t1(0,U(k((()=>ID)))),t1(1,U(k((()=>Y0)))),t1(2,U(cA)),e1("design:paramtypes",[ID,Y0,Object,uD])],i1);class a1 extends Error{errors;ownMessage;ownStack;constructor(e=[],t=""){const r=s1([t,...e.map((e=>e.message))]);super(r),e.forEach((e=>{Object.assign(this,e)})),this.message=r,this.ownMessage=t,this.errors=new Set(e),this.ownStack=this.stack,this.stack=o1([this,...e])}static fromAllSettled(e=[],t=""){const r=e.map((({reason:e})=>e)).filter(Boolean);if(r.length)return new this(r,t)}static throwAllSettled(e=[],t=""){const r=this.fromAllSettled(e,t);if(r)throw r}static from(e,t,r){return t?e?e instanceof a1?e.extend(t,r,this):new this([e]).extend(t,r):(t&&r&&(t.message=s1([t.message,r])),t):(e&&r&&(e.message=s1([e.message,r])),e)}extend(e,t="",r=this.constructor){if(e===this||this.errors.has(e))return this;return new r([e,...this.errors],s1([t,this.ownMessage]))}}const c1=()=>{};function u1(e=[],t,{id:r="",onError:n,onDone:i,onChange:s}={}){let o;const a=e.slice().reverse().map((e=>async()=>{const t=await e();return"function"==typeof t?t:c1})),c=[],u=[],l=gD(1);let h=!1,d=!1;function f(e){try{if("function"!=typeof n)throw e;n(e)}catch(e){o=a1.from(o,e,`ScaffoldError:${r}`)}}let p=!1,g=!1;const m=gD(1);async function y(){p=await(async()=>{if(o)return!1;try{return await t()}catch(e){f(e)}return!1})();const e=g!==p;if(g=p,e&&"function"==typeof s){try{await s(p)}catch(e){f(e)}return y()}if(p){if(a.length){let e;h=!1,d=!0;const t=a.pop();c.push(t);try{e=await t()}catch(e){f(e)}return u.push(e??(()=>{})),void await y()}}else{if(u.length){h=!1,d=!0;const e=u.pop();try{await e()}catch(e){f(e)}return a.push(c.pop()),void await y()}if(o){const e=o;throw o=void 0,h=!0,e}}return h=!0,Promise.resolve()}function b(){return!(d&&h&&!l.activeCount&&!l.pendingCount)}const w=async()=>{await m((()=>y()))};let v;return Object.assign((async()=>{let e;try{v=l((()=>w())),await v}catch(t){throw e=t,t}finally{if(!b()&&(d=!1,"function"==typeof i)){const t=e;e=void 0,await i(p,t)}}}),{next:w,isActive:b,getCurrentStep:()=>v,get activeCount(){return l.activeCount},get pendingCount(){return l.pendingCount},setError(e){o=a1.from(o,e)},getError:()=>o,clearError(){const e=o;return o=void 0,e}})}class l1{streamPartId;onRetired=sJ.once();isRetired=!1;isStopped=!1;subscriptions=new Set;pendingRemoval=new WeakSet;pipeline;node;constructor(e,t,r){this.streamPartId=e,this.distributeMessage=this.distributeMessage.bind(this),this.node=r,this.onError=this.onError.bind(this),this.pipeline=t.createMessagePipeline({streamPartId:e}),this.pipeline.onError.listen(this.onError),this.pipeline.pipe(this.distributeMessage).onBeforeFinally.listen((async()=>{this.isStopped||await this.stop()})),this.pipeline.flow()}async retire(){this.isRetired||(this.isRetired=!0,await this.onRetired.trigger())}async onError(e){await Promise.allSettled([...this.subscriptions].map((async t=>{await t.handleError(e)})))}async*distributeMessage(e){for await(const t of e)await Promise.all([...this.subscriptions].map((async e=>{await e.push(t)}))),yield t}onMessageInput=async t=>{if(!t||this.isStopped||this.isRetired)return;if(t.getStreamPartID()!==this.streamPartId)return;if(t.messageType!==e.StreamMessageType.MESSAGE)return;const r=[];let n=!1;for(const e of this.subscriptions.values())e.isRaw?r.push(e.push(t)):n=!0;n&&r.push(this.pipeline.push(t)),await Promise.all(r)};async subscribe(){if(this.node.addMessageListener(this.onMessageInput),!await this.node.isProxiedStreamPart(this.streamPartId)){const e=(e=>e.values().next().value)(this.subscriptions).deliveryOptions;await this.node.join(this.streamPartId,void 0,e)}}async unsubscribe(){this.pipeline.end(),this.pipeline.return(),this.pipeline.onError.end(new Error("done")),this.node.removeMessageListener(this.onMessageInput),await this.node.leave(this.streamPartId)}updateNodeSubscriptions=(()=>u1([async()=>(await this.subscribe(),async()=>{await this.unsubscribe(),await this.stop()})],(()=>this.shouldBeSubscribed())))();async updateSubscriptions(){await this.updateNodeSubscriptions(),this.shouldBeSubscribed()||this.isStopped||await this.stop()}shouldBeSubscribed(){return!this.isRetired&&!this.isStopped&&!!this.count()}async stop(){this.isStopped=!0,this.pipeline.end(),await this.retire(),await this.pipeline.return()}has(e){return this.subscriptions.has(e)}async add(e){if(!e||this.subscriptions.has(e)||this.pendingRemoval.has(e))return;const t=this.getERC1271ContractAddress();if(this.subscriptions.size>0&&t!==e.erc1271ContractAddress)throw new Error("Subscription ERC-1271 mismatch");this.subscriptions.add(e),e.onBeforeFinally.listen((()=>this.remove(e))),await this.updateSubscriptions()}async remove(e){if(e&&!this.pendingRemoval.has(e)&&this.subscriptions.has(e)){this.pendingRemoval.add(e),this.subscriptions.delete(e);try{e.isDone()||await e.unsubscribe()}finally{await this.updateSubscriptions()}}}getERC1271ContractAddress(){for(const e of this.subscriptions)if(void 0!==e.erc1271ContractAddress)return e.erc1271ContractAddress}count(){return this.subscriptions.size}}var h1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},d1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},f1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let p1=class{subSessions=new Map;node;messagePipelineFactory;logger;constructor(e,t,r){this.node=e,this.messagePipelineFactory=t,this.logger=r.createLogger("Subscriber")}getOrCreateSubscriptionSession(e){if(this.subSessions.has(e))return this.getSubscriptionSession(e);const t=new l1(e,this.messagePipelineFactory,this.node);return this.subSessions.set(e,t),t.onRetired.listen((()=>{this.subSessions.delete(e)})),this.logger.debug("Created new SubscriptionSession",{streamPartId:e}),t}async add(e){const t=this.getOrCreateSubscriptionSession(e.streamPartId);try{await t.add(e)}catch(t){throw this.logger.debug("Failed to add Subscription to SubscriptionSession",t),await this.remove(e),t}}async remove(e){const t=this.subSessions.get(e.streamPartId);t&&await t.remove(e)}getSubscriptions(){return[...this.subSessions.values()].reduce(((e,t)=>(e.push(...t.subscriptions),e)),[])}getERC1271ContractAddress(e){return this.subSessions.get(e)?.getERC1271ContractAddress()}getSubscriptionSession(e){return this.subSessions.get(e)}countSubscriptionSessions(){return this.subSessions.size}};p1=h1([j(),f1(1,U(k((()=>Y0)))),d1("design:paramtypes",[GX,Y0,uD])],p1),F.register(T0.Resends,{useClass:i1},{lifecycle:d.ContainerScoped}),F.register(T0.Subscriber,{useClass:p1},{lifecycle:d.ContainerScoped});var g1,m1,y1={},b1={};var w1,v1=function(){if(m1)return y1;m1=1,Object.defineProperty(y1,"__esModule",{value:!0}),y1.isConstructorToken=y1.isTransformDescriptor=y1.isTokenDescriptor=y1.isNormalToken=void 0;const e=function(){if(g1)return b1;g1=1,Object.defineProperty(b1,"__esModule",{value:!0}),b1.delay=b1.DelayedConstructor=void 0;class e{constructor(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}createProxy(e){let t,r=!1;return new Proxy({},this.createHandler((()=>(r||(t=e(this.wrap()),r=!0),t))))}createHandler(e){const t={};return this.reflectMethods.forEach((r=>{t[r]=(...t)=>(t[0]=e(),(0,Reflect[r])(...t))})),t}}return b1.DelayedConstructor=e,b1.delay=function(t){if(void 0===t)throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new e(t)},b1}();return y1.isNormalToken=function(e){return"string"==typeof e||"symbol"==typeof e},y1.isTokenDescriptor=function(e){return"object"==typeof e&&"token"in e&&"multiple"in e},y1.isTransformDescriptor=function(e){return"object"==typeof e&&"token"in e&&"transform"in e},y1.isConstructorToken=function(t){return"function"==typeof t||t instanceof e.DelayedConstructor},y1}(),E1={};var A1,S1,k1=(w1||(w1=1,Object.defineProperty(E1,"__esModule",{value:!0}),E1.formatErrorCtor=void 0,E1.formatErrorCtor=function(e,t,r){const[,n=null]=e.toString().match(/constructor\(([\w, ]+)\)/)||[];return function(e,t,r=" "){return[e,...t.message.split("\n").map((e=>r+e))].join("\n")}(`Cannot inject the dependency ${function(e,t){return null===e?`at position #${t}`:`"${e.split(",")[t].trim()}" at position #${t}`}(n,t)} of "${e.name}" constructor. Reason:`,r)}),E1);F.constructor.prototype.resolveParams=function(e,t){return(r,n)=>{try{return v1.isTokenDescriptor(r)?v1.isTransformDescriptor(r)?r.multiple?this.resolve(r.transform).transform(this.resolveAll(r.token),...r.transformArgs):this.resolve(r.transform).transform(this.resolve(r.token,e),...r.transformArgs):r.multiple?this.resolveAll(r.token):this.resolve(r.token,e):v1.isTransformDescriptor(r)?this.resolve(r.transform,e).transform(this.resolve(r.token,e),...r.transformArgs):this.resolve(r,e)}catch(e){throw e.message=k1.formatErrorCtor(t,n,e),e}}};var R1,C1,I1=function(){if(S1)return A1;S1=1;var e=Td(),t=Nd()((function(t,r,n){e(t,r,n)}));return A1=t}(),P1=n(I1);var T1=function(){if(C1)return R1;C1=1;var e=De(),t=qu(),r=Be();return R1=function(n){return"string"==typeof n||!t(n)&&r(n)&&"[object String]"==e(n)}}(),_1=n(T1);class N1{currentGroupKey;queuedGroupKey;streamId;identity;groupKeyManager;static async createInstance(e,t,r,n){const i=new N1(e,t,r);return i.currentGroupKey=n??await i.groupKeyManager.fetchLatestEncryptionKey(await t.getUserId(),e)??void 0,i}constructor(e,t,r){this.streamId=e,this.identity=t,this.groupKeyManager=r}async useGroupKey(){this.currentGroupKey||(this.currentGroupKey=this.queuedGroupKey??await this.rekey(),this.queuedGroupKey=void 0);const e={current:this.currentGroupKey,next:this.queuedGroupKey};return this.queuedGroupKey&&(this.currentGroupKey=this.queuedGroupKey,this.queuedGroupKey=void 0),e}async rotate(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.queuedGroupKey=e,e}async rekey(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.currentGroupKey=e,this.queuedGroupKey=void 0,e}}class M1{streamId;identity;defaultPartition;defaultMessageChainIds;prevMsgRefs=new Map;streamRegistry;groupKeyQueue;signatureValidator;messageSigner;config;firstMessage=!0;constructor(e){this.streamId=e.streamId,this.identity=e.identity,this.streamRegistry=e.streamRegistry,this.groupKeyQueue=e.groupKeyQueue,this.signatureValidator=e.signatureValidator,this.messageSigner=e.messageSigner,this.config=e.config,this.defaultMessageChainIds=BJ({valueFactory:async()=>VX()})}async createMessage(t,r,n){const i=await this.getPublisherId(r);if(this.config.validation.permissions){if(!await this.streamRegistry.isStreamPublisher(this.streamId,i))throw this.streamRegistry.invalidatePermissionCaches(this.streamId),new uA(`You don't have permission to publish to this stream. Using address: ${i}`,"MISSING_PERMISSION")}let s;if(this.config.validation.partitions){const e=await this.streamRegistry.getStreamMetadata(this.streamId),t=IJ(e);if(void 0!==n){if(n<0||n>=t)throw new Error(`Partition ${n} is out of range (0..${t-1})`);if(void 0!==r.partitionKey)throw new Error('Invalid combination of "partition" and "partitionKey"');s=n}else s=void 0!==r.partitionKey?function(e,t){if(!(Number.isSafeInteger(e)&&e>0))throw new Error(`lengthOfArray is not a safe positive integer! ${e}`);if(1===e)return 0;if("number"==typeof t)return Math.abs(t)%e;const r=_v(t).readInt32LE(0);return Math.abs(r)%e}(t,r.partitionKey):this.getDefaultPartition(t)}else{if(void 0===n)throw new Error("Explicit partition must be set when partition validation is disabled");s=n}const o=r.msgChainId??await this.defaultMessageChainIds.get(s),a=QW([s,o]),c=this.prevMsgRefs.get(a),u=((e,t)=>{if(void 0!==t&&e<t.timestamp)throw new Error("prevMessageRef must come before current");const r=t?.timestamp===e?t.sequenceNumber+1:0;return new RW(e,r)})(r.timestamp,c);this.prevMsgRefs.set(a,u);const l=new CW(this.streamId,s,u.timestamp,u.sequenceNumber,i,o),h=this.config.validation.permissions&&await this.streamRegistry.hasPublicSubscribePermission(this.streamId)?e.EncryptionType.NONE:e.EncryptionType.AES;if(!I0(h,this.config))throw new uA(`Publishing to stream ${this.streamId} was prevented because configuration requires encryption!`,"ENCRYPTION_POLICY_VIOLATION");let d,f,p,g;if(t instanceof Uint8Array?(g=e.ContentType.BINARY,p=t):(g=e.ContentType.JSON,p=pw(JSON.stringify(t))),h===e.EncryptionType.AES){const e=await this.groupKeyQueue.useGroupKey();p=YQ.encryptWithAES(p,e.current.data),d=e.current.id,void 0!==e.next&&(f=e.current.encryptNextGroupKey(e.next))}const m=await this.messageSigner.createSignedMessage({messageId:l,messageType:e.StreamMessageType.MESSAGE,content:p,prevMsgRef:c,encryptionType:h,groupKeyId:d,newGroupKey:f,contentType:g},void 0!==r.erc1271Contract?e.SignatureType.ERC_1271:this.identity.getSignatureType());return this.firstMessage&&(this.firstMessage=!1,void 0!==r.erc1271Contract&&await this.signatureValidator.assertSignatureIsValid(m)),m}async getPublisherId(e){return void 0!==e.erc1271Contract?kE(nb(e.erc1271Contract)):this.identity.getUserId()}getDefaultPartition(e){return(void 0===this.defaultPartition||this.defaultPartition>=e)&&(this.defaultPartition=XE(e-1)),this.defaultPartition}}var x1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},O1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},D1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let B1=class{messageFactories;groupKeyQueues;concurrencyLimit=gD(1);node;streamRegistry;streamIdBuilder;identity;signatureValidator;messageSigner;config;constructor(e,t,r,n,i,s,o,a){this.node=e,this.streamRegistry=t,this.streamIdBuilder=n,this.identity=i,this.signatureValidator=s,this.messageSigner=o,this.config=a,this.messageFactories=BJ({valueFactory:async e=>this.createMessageFactory(e)}),this.groupKeyQueues=BJ({valueFactory:async e=>{const t=await L0(e,this.streamIdBuilder,this.config.encryption);return await N1.createInstance(e,this.identity,r,t)}})}async publish(e,t,r,n){const i=(e=>void 0===e?.timestamp?Date.now():e.timestamp instanceof Date?e.timestamp.getTime():_1(e.timestamp)?new Date(e.timestamp).getTime():e.timestamp)(r);return this.concurrencyLimit((async()=>{const[s,o]=await this.streamIdBuilder.toStreamPartElements(e);try{const e=await this.messageFactories.get(s),a=await e.createMessage(t,{...r,timestamp:i},o);return await this.node.broadcast(a,n),a}catch(e){const t=e instanceof uA?e.code:"UNKNOWN_ERROR";throw new uA(`Failed to publish to stream ${s}. Cause: ${e.message}`,t)}}))}getGroupKeyQueue(e){return this.groupKeyQueues.get(e)}async createMessageFactory(e){return new M1({streamId:e,identity:this.identity,streamRegistry:this.streamRegistry,groupKeyQueue:await this.groupKeyQueues.get(e),signatureValidator:this.signatureValidator,messageSigner:this.messageSigner,config:this.config})}};var L1,F1;B1=x1([q(d.ContainerScoped),D1(4,U(kA)),D1(7,U(cA)),O1("design:paramtypes",[GX,EQ,F0,RJ,RA,m0,e.MessageSigner,Object])],B1);var U1,j1=n(function(){if(F1)return L1;F1=1;var e=MY();return L1=function(t){return e(t,5)}}()),q1={exports:{}};var z1=function(){if(U1)return q1.exports;U1=1,q1.exports=u,q1.exports.default=u;const e={properties:{environment:{type:"string",enum:["polygon","polygonAmoy","peaq","iotex","dev2"],description:"applies all environment-specific defaults for the given environment"},id:{type:"string"},logLevel:{type:"string",enum:["silent","fatal","error","warn","info","debug","trace"],default:"info"},auth:{type:"object",additionalProperties:!1,properties:{publicKey:{type:"string",format:"hex-string"},privateKey:{type:"string",format:"hex-string"},keyType:{type:"string",default:"ECDSA_SECP256K1_EVM"},ethereum:{type:"object"},identity:{type:"object"}}},orderMessages:{type:"boolean",default:!0},gapFill:{type:"boolean",default:!0},maxGapRequests:{type:"number",default:5},retryResendAfter:{type:"number",default:5e3},gapFillTimeout:{type:"number",default:5e3},gapFillStrategy:{type:"string",enum:["light","full"],default:"light"},network:{type:"object",additionalProperties:!1,required:[],properties:{controlLayer:{type:"object",additionalProperties:!1,properties:{entryPoints:{type:"array",items:{$ref:"#/definitions/peerDescriptor"}},entryPointDiscovery:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"},maxEntryPoints:{type:"number"},maxQueryResults:{type:"number"},maxHeartbeatAgeHours:{type:"number"}},default:{enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}},websocketPortRange:{anyOf:[{type:"null"},{$ref:"#/definitions/portRange"}],default:{min:32200,max:32250}},websocketHost:{type:"string",format:"hostname"},peerDescriptor:{$ref:"#/definitions/peerDescriptor"},maxConnections:{type:"number",default:80},tlsCertificate:{description:"Files to use for TLS",type:"object",required:["certFileName","privateKeyFileName"],additionalProperties:!1,properties:{certFileName:{type:"string",description:"Path of certificate file"},privateKeyFileName:{type:"string",description:"Path of private key file"}}},iceServers:{type:"array",items:{type:"object",required:["url","port"],additionalProperties:!1,properties:{url:{type:"string"},port:{type:"number"},username:{type:"string"},password:{type:"string"},tcp:{type:"boolean"}}},default:[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]},webrtcAllowPrivateAddresses:{type:"boolean",default:!1},webrtcDatachannelBufferThresholdLow:{type:"number",default:32768},webrtcDatachannelBufferThresholdHigh:{type:"number",default:131072},maxMessageSize:{type:"number",default:1048576},externalIp:{type:"string",format:"ipv4"},webrtcPortRange:{$ref:"#/definitions/portRange",default:{min:5e4,max:64e3}},networkConnectivityTimeout:{type:"number",default:1e4},websocketServerEnableTls:{type:"boolean",default:!0},autoCertifierUrl:{type:"string",default:"https://ns1.streamr-nodes.xyz:59833"},autoCertifierConfigFile:{type:"string",default:"~/.streamr/certificate.json"},geoIpDatabaseFolder:{type:"string"}},default:{}},node:{type:"object",additionalProperties:!1,properties:{streamPartitionNeighborTargetCount:{type:"number",default:4},streamPartitionMinPropagationTargets:{type:"number",default:2},streamPartitionMaxPropagationBufferSize:{type:"number",default:150},contentDeliveryBufferWhileConnecting:{type:"boolean",default:!0},acceptProxyConnections:{type:"boolean",default:!1}},default:{}}},default:{}},contracts:{type:"object",additionalProperties:!1,properties:{ethereumNetwork:{type:"object",additionalProperties:!1,properties:{chainId:{type:"number"},overrides:{type:"object"},highGasPriceStrategy:{type:"boolean"}},default:{}},streamRegistryChainAddress:{type:"string",format:"ethereum-address"},streamStorageRegistryChainAddress:{type:"string",format:"ethereum-address"},storageNodeRegistryChainAddress:{type:"string",format:"ethereum-address"},sponsorshipFactoryChainAddress:{type:"string",format:"ethereum-address"},rpcs:{type:"array",items:{type:"object",$ref:"#/definitions/rpcProviderConfig"},minItems:1},rpcQuorum:{type:"number",default:2},theGraphUrl:{type:"string",format:"uri"},maxConcurrentCalls:{type:"number",default:10},pollInterval:{type:"number",default:4e3}},default:{}},encryption:{type:"object",additionalProperties:!1,properties:{keyRequestTimeout:{type:"number",default:3e4},maxKeyRequestsPerSecond:{type:"number",default:20},rsaKeyLength:{type:"number",default:4096},requireQuantumResistantKeyExchange:{type:"boolean",default:!1},requireQuantumResistantSignatures:{type:"boolean",default:!1},requireQuantumResistantEncryption:{type:"boolean",default:!1},keys:{type:"object",propertyNames:{$ref:"#/definitions/streamIdOrPath"},additionalProperties:{$ref:"#/definitions/encryptionKey"}}},default:{}},validation:{type:"object",additionalProperties:!1,properties:{permissions:{type:"boolean",default:!0},partitions:{type:"boolean",default:!0}},default:{}},metrics:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!1,properties:{periods:{type:"array",items:{type:"object",required:["streamId","duration"],properties:{id:{type:"string"},duration:{type:"number"}}}},maxPublishDelay:{type:"number"}}}]},cache:{type:"object",additionalProperties:!1,properties:{maxSize:{type:"number",default:1e4},maxAge:{type:"number",default:864e5}},default:{}},_timeouts:{type:"object",additionalProperties:!1,properties:{theGraph:{type:"object",additionalProperties:!1,properties:{indexTimeout:{type:"number",default:6e4},indexPollInterval:{type:"number",default:1e3},fetchTimeout:{type:"number",default:3e4}},default:{}},storageNode:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:3e4},retryInterval:{type:"number",default:1e3}},default:{}},ensStreamCreation:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:18e4},retryInterval:{type:"number",default:1e3}},default:{}},jsonRpcTimeout:{type:"number",default:3e4}},default:{}}}},t=Object.prototype.hasOwnProperty,r=/^(0x)?[a-fA-F0-9]+$/,n=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,i=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,s=/^0x[a-fA-F0-9]{40}$/,o=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,a={enum:["browser","nodejs"]};function c(e,{instancePath:t="",parentData:r,parentDataProperty:n,rootData:i=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return c.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const r in e)if("nodeId"!==r&&"id"!==r&&"type"!==r&&"websocket"!==r)return c.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(void 0!==e.nodeId){const r=0;if("string"!=typeof e.nodeId)return c.errors=[{instancePath:t+"/nodeId",schemaPath:"#/properties/nodeId/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var s=0===r}else s=!0;if(s){if(void 0!==e.id){const r=0;if("string"!=typeof e.id)return c.errors=[{instancePath:t+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;s=0===r}else s=!0;if(s){if(void 0!==e.type){let r=e.type;const n=0;if("string"!=typeof r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("browser"!==r&&"nodejs"!==r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/enum",keyword:"enum",params:{allowedValues:a.enum},message:"must be equal to one of the allowed values"}],!1;s=0===n}else s=!0;if(s)if(void 0!==e.websocket){let r=e.websocket;const n=0;if(!r||"object"!=typeof r||Array.isArray(r))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===r.host&&(e="host")||void 0===r.port&&(e="port")||void 0===r.tls&&(e="tls"))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;for(const e in r)if("host"!==e&&"port"!==e&&"tls"!==e)return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(void 0!==r.host){const e=0;if("string"!=typeof r.host)return c.errors=[{instancePath:t+"/websocket/host",schemaPath:"#/definitions/connectivityMethod/properties/host/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var o=0===e}else o=!0;if(o){if(void 0!==r.port){let e=r.port;const n=0;if("number"!=typeof e||!isFinite(e))return c.errors=[{instancePath:t+"/websocket/port",schemaPath:"#/definitions/connectivityMethod/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;o=0===n}else o=!0;if(o)if(void 0!==r.tls){const e=0;if("boolean"!=typeof r.tls)return c.errors=[{instancePath:t+"/websocket/tls",schemaPath:"#/definitions/connectivityMethod/properties/tls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;o=0===e}else o=!0}}s=0===n}else s=!0}}return c.errors=null,!0}function u(a,{instancePath:l="",parentData:h,parentDataProperty:d,rootData:f=a}={}){let p=null,g=0;if(0===g){if(!a||"object"!=typeof a||Array.isArray(a))return u.errors=[{instancePath:l,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===a.logLevel&&(a.logLevel="info"),void 0===a.orderMessages&&(a.orderMessages=!0),void 0===a.gapFill&&(a.gapFill=!0),void 0===a.maxGapRequests&&(a.maxGapRequests=5),void 0===a.retryResendAfter&&(a.retryResendAfter=5e3),void 0===a.gapFillTimeout&&(a.gapFillTimeout=5e3),void 0===a.gapFillStrategy&&(a.gapFillStrategy="light"),void 0===a.network&&(a.network={}),void 0===a.contracts&&(a.contracts={}),void 0===a.encryption&&(a.encryption={}),void 0===a.validation&&(a.validation={}),void 0===a.cache&&(a.cache={}),void 0===a._timeouts&&(a._timeouts={});const h=g;for(const r in a)if(!t.call(e.properties,r))return u.errors=[{instancePath:l,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(h===g){if(void 0!==a.environment){let t=a.environment;const r=g;if("string"!=typeof t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("polygon"!==t&&"polygonAmoy"!==t&&"peaq"!==t&&"iotex"!==t&&"dev2"!==t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/enum",keyword:"enum",params:{allowedValues:e.properties.environment.enum},message:"must be equal to one of the allowed values"}],!1;var m=r===g}else m=!0;if(m){if(void 0!==a.id){const e=g;if("string"!=typeof a.id)return u.errors=[{instancePath:l+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;m=e===g}else m=!0;if(m){let h=a.logLevel;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("silent"!==h&&"fatal"!==h&&"error"!==h&&"warn"!==h&&"info"!==h&&"debug"!==h&&"trace"!==h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/enum",keyword:"enum",params:{allowedValues:e.properties.logLevel.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){if(void 0!==a.auth){let e=a.auth;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyType&&(e.keyType="ECDSA_SECP256K1_EVM");const t=g;for(const t in e)if("publicKey"!==t&&"privateKey"!==t&&"keyType"!==t&&"ethereum"!==t&&"identity"!==t)return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.publicKey){let t=e.publicKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}var y=n===g}else y=!0;if(y){if(void 0!==e.privateKey){let t=e.privateKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}y=n===g}else y=!0;if(y){const t=g;if("string"!=typeof e.keyType)return u.errors=[{instancePath:l+"/auth/keyType",schemaPath:"#/properties/auth/properties/keyType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(y=t===g){if(void 0!==e.ethereum){let t=e.ethereum;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/ethereum",schemaPath:"#/properties/auth/properties/ethereum/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0;if(y)if(void 0!==e.identity){let t=e.identity;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/identity",schemaPath:"#/properties/auth/properties/identity/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0}}}}}}m=t===g}else m=!0;if(m){const h=g;if("boolean"!=typeof a.orderMessages)return u.errors=[{instancePath:l+"/orderMessages",schemaPath:"#/properties/orderMessages/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){const h=g;if("boolean"!=typeof a.gapFill)return u.errors=[{instancePath:l+"/gapFill",schemaPath:"#/properties/gapFill/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){let h=a.maxGapRequests;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/maxGapRequests",schemaPath:"#/properties/maxGapRequests/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.retryResendAfter;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/retryResendAfter",schemaPath:"#/properties/retryResendAfter/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillTimeout;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/gapFillTimeout",schemaPath:"#/properties/gapFillTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillStrategy;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("light"!==h&&"full"!==h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/enum",keyword:"enum",params:{allowedValues:e.properties.gapFillStrategy.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){let h=a.network;const d=g;if(g===d){if(!h||"object"!=typeof h||Array.isArray(h))return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===h.controlLayer&&(h.controlLayer={}),void 0===h.node&&(h.node={});const r=g;for(const e in h)if("controlLayer"!==e&&"node"!==e)return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(r===g){let r=h.controlLayer;const s=g;if(g===s){if(!r||"object"!=typeof r||Array.isArray(r))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===r.entryPointDiscovery&&(r.entryPointDiscovery={enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}),void 0===r.websocketPortRange&&(r.websocketPortRange={min:32200,max:32250}),void 0===r.maxConnections&&(r.maxConnections=80),void 0===r.iceServers&&(r.iceServers=[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]),void 0===r.webrtcAllowPrivateAddresses&&(r.webrtcAllowPrivateAddresses=!1),void 0===r.webrtcDatachannelBufferThresholdLow&&(r.webrtcDatachannelBufferThresholdLow=32768),void 0===r.webrtcDatachannelBufferThresholdHigh&&(r.webrtcDatachannelBufferThresholdHigh=131072),void 0===r.maxMessageSize&&(r.maxMessageSize=1048576),void 0===r.webrtcPortRange&&(r.webrtcPortRange={min:5e4,max:64e3}),void 0===r.networkConnectivityTimeout&&(r.networkConnectivityTimeout=1e4),void 0===r.websocketServerEnableTls&&(r.websocketServerEnableTls=!0),void 0===r.autoCertifierUrl&&(r.autoCertifierUrl="https://ns1.streamr-nodes.xyz:59833"),void 0===r.autoCertifierConfigFile&&(r.autoCertifierConfigFile="~/.streamr/certificate.json");const s=g;for(const n in r)if(!t.call(e.properties.network.properties.controlLayer.properties,n))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:n},message:"must NOT have additional properties"}],!1;if(s===g){if(void 0!==r.entryPoints){let e=r.entryPoints;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPoints/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){const t=g;if(c(e[r],{instancePath:l+"/network/controlLayer/entryPoints/"+r,parentData:e,parentDataProperty:r,rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length),!(t===g))break}}}var b=t===g}else b=!0;if(b){let e=r.entryPointDiscovery;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("enabled"!==t&&"maxEntryPoints"!==t&&"maxQueryResults"!==t&&"maxHeartbeatAgeHours"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.enabled){const t=g;if("boolean"!=typeof e.enabled)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/enabled",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/enabled/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;var w=t===g}else w=!0;if(w){if(void 0!==e.maxEntryPoints){let t=e.maxEntryPoints;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxEntryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxEntryPoints/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w){if(void 0!==e.maxQueryResults){let t=e.maxQueryResults;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxQueryResults",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxQueryResults/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w)if(void 0!==e.maxHeartbeatAgeHours){let t=e.maxHeartbeatAgeHours;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxHeartbeatAgeHours",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxHeartbeatAgeHours/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0}}}}}if(b=t===g){let e=r.websocketPortRange;const t=g,s=g;let o=!1;const a=g;if(null!==e){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};null===p?p=[e]:p.push(e),g++}var v=a===g;if(o=o||v,!o){const t=g;if(g===g)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max")){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{const t=g;for(const t in e)if("min"!==t&&"max"!==t){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}var E=r===g}else E=!0;if(E)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}E=r===g}else E=!0}}}else{const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}v=t===g;o=o||v}if(!o){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}if(g=s,null!==p&&(s?p.length=s:p=null),b=t===g){if(void 0!==r.websocketHost){let e=r.websocketHost;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!n.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/format",keyword:"format",params:{format:"hostname"},message:'must match format "hostname"'}],!1}b=t===g}else b=!0;if(b){if(void 0!==r.peerDescriptor){const e=g;c(r.peerDescriptor,{instancePath:l+"/network/controlLayer/peerDescriptor",parentData:r,parentDataProperty:"peerDescriptor",rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length);b=e===g}else b=!0;if(b){let e=r.maxConnections;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxConnections",schemaPath:"#/properties/network/properties/controlLayer/properties/maxConnections/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.tlsCertificate){let e=r.tlsCertificate;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.certFileName&&(t="certFileName")||void 0===e.privateKeyFileName&&(t="privateKeyFileName"))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("certFileName"!==t&&"privateKeyFileName"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.certFileName){const t=g;if("string"!=typeof e.certFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/certFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/certFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var A=t===g}else A=!0;if(A)if(void 0!==e.privateKeyFileName){const t=g;if("string"!=typeof e.privateKeyFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/privateKeyFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/privateKeyFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;A=t===g}else A=!0}}}}b=t===g}else b=!0;if(b){let e=r.iceServers;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url")||void 0===t.port&&(e="port"))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;{const e=g;for(const e in t)if("url"!==e&&"port"!==e&&"username"!==e&&"password"!==e&&"tcp"!==e)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){if(void 0!==t.url){const e=g;if("string"!=typeof t.url)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/url",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=e===g}else S=!0;if(S){if(void 0!==t.port){let e=t.port;const n=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/port",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;S=n===g}else S=!0;if(S){if(void 0!==t.username){const e=g;if("string"!=typeof t.username)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/username",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/username/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S){if(void 0!==t.password){const e=g;if("string"!=typeof t.password)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/password",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/password/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S)if(void 0!==t.tcp){const e=g;if("boolean"!=typeof t.tcp)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/tcp",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/tcp/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;S=e===g}else S=!0}}}}}}}if(!(n===g))break}}}if(b=t===g){const e=g;if("boolean"!=typeof r.webrtcAllowPrivateAddresses)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcAllowPrivateAddresses",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcAllowPrivateAddresses/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){let e=r.webrtcDatachannelBufferThresholdLow;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdLow",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdLow/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.webrtcDatachannelBufferThresholdHigh;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdHigh",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdHigh/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.maxMessageSize;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxMessageSize",schemaPath:"#/properties/network/properties/controlLayer/properties/maxMessageSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.externalIp){let e=r.externalIp;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!i.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/format",keyword:"format",params:{format:"ipv4"},message:'must match format "ipv4"'}],!1}b=t===g}else b=!0;if(b){let e=r.webrtcPortRange;const t=g;if(g===g){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max"))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("min"!==t&&"max"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var k=r===g}else k=!0;if(k)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;k=r===g}else k=!0}}}}if(b=t===g){let e=r.networkConnectivityTimeout;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/networkConnectivityTimeout",schemaPath:"#/properties/network/properties/controlLayer/properties/networkConnectivityTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){const e=g;if("boolean"!=typeof r.websocketServerEnableTls)return u.errors=[{instancePath:l+"/network/controlLayer/websocketServerEnableTls",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketServerEnableTls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierUrl)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierUrl",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierConfigFile)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierConfigFile",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierConfigFile/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g)if(void 0!==r.geoIpDatabaseFolder){const e=g;if("string"!=typeof r.geoIpDatabaseFolder)return u.errors=[{instancePath:l+"/network/controlLayer/geoIpDatabaseFolder",schemaPath:"#/properties/network/properties/controlLayer/properties/geoIpDatabaseFolder/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;b=e===g}else b=!0}}}}}}}}}}}}}}}}}}}}if(s===g){let e=h.node;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.streamPartitionNeighborTargetCount&&(e.streamPartitionNeighborTargetCount=4),void 0===e.streamPartitionMinPropagationTargets&&(e.streamPartitionMinPropagationTargets=2),void 0===e.streamPartitionMaxPropagationBufferSize&&(e.streamPartitionMaxPropagationBufferSize=150),void 0===e.contentDeliveryBufferWhileConnecting&&(e.contentDeliveryBufferWhileConnecting=!0),void 0===e.acceptProxyConnections&&(e.acceptProxyConnections=!1);const t=g;for(const t in e)if("streamPartitionNeighborTargetCount"!==t&&"streamPartitionMinPropagationTargets"!==t&&"streamPartitionMaxPropagationBufferSize"!==t&&"contentDeliveryBufferWhileConnecting"!==t&&"acceptProxyConnections"!==t)return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.streamPartitionNeighborTargetCount;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionNeighborTargetCount",schemaPath:"#/properties/network/properties/node/properties/streamPartitionNeighborTargetCount/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMinPropagationTargets;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMinPropagationTargets",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMinPropagationTargets/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMaxPropagationBufferSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMaxPropagationBufferSize",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMaxPropagationBufferSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){const t=g;if("boolean"!=typeof e.contentDeliveryBufferWhileConnecting)return u.errors=[{instancePath:l+"/network/node/contentDeliveryBufferWhileConnecting",schemaPath:"#/properties/network/properties/node/properties/contentDeliveryBufferWhileConnecting/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.acceptProxyConnections)return u.errors=[{instancePath:l+"/network/node/acceptProxyConnections",schemaPath:"#/properties/network/properties/node/properties/acceptProxyConnections/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}}}}}}}}if(m=d===g){let n=a.contracts;const i=g;if(g===i){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===n.ethereumNetwork&&(n.ethereumNetwork={}),void 0===n.rpcQuorum&&(n.rpcQuorum=2),void 0===n.maxConcurrentCalls&&(n.maxConcurrentCalls=10),void 0===n.pollInterval&&(n.pollInterval=4e3);const r=g;for(const r in n)if(!t.call(e.properties.contracts.properties,r))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(r===g){let e=n.ethereumNetwork;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("chainId"!==t&&"overrides"!==t&&"highGasPriceStrategy"!==t)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.chainId){let t=e.chainId;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/chainId",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/chainId/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var R=r===g}else R=!0;if(R){if(void 0!==e.overrides){let t=e.overrides;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/overrides",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/overrides/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;R=r===g}else R=!0;if(R)if(void 0!==e.highGasPriceStrategy){const t=g;if("boolean"!=typeof e.highGasPriceStrategy)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/highGasPriceStrategy",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/highGasPriceStrategy/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;R=t===g}else R=!0}}}}if(C=t===g){if(void 0!==n.streamRegistryChainAddress){let e=n.streamRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}var C=t===g}else C=!0;if(C){if(void 0!==n.streamStorageRegistryChainAddress){let e=n.streamStorageRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.storageNodeRegistryChainAddress){let e=n.storageNodeRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.sponsorshipFactoryChainAddress){let e=n.sponsorshipFactoryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.rpcs){let e=n.rpcs;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;if(e.length<1)return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/properties/contracts/properties/rpcs/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;if(g===g){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url"))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;if(void 0!==t.url){let e=t.url;if(g===g&&g===g){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}}}}if(!(n===g))break}}}C=t===g}else C=!0;if(C){let e=n.rpcQuorum;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/rpcQuorum",schemaPath:"#/properties/contracts/properties/rpcQuorum/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){if(void 0!==n.theGraphUrl){let e=n.theGraphUrl;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}C=t===g}else C=!0;if(C){let e=n.maxConcurrentCalls;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/maxConcurrentCalls",schemaPath:"#/properties/contracts/properties/maxConcurrentCalls/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){let e=n.pollInterval;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/pollInterval",schemaPath:"#/properties/contracts/properties/pollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;C=t===g}}}}}}}}}}}}if(m=i===g){let e=a.encryption;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyRequestTimeout&&(e.keyRequestTimeout=3e4),void 0===e.maxKeyRequestsPerSecond&&(e.maxKeyRequestsPerSecond=20),void 0===e.rsaKeyLength&&(e.rsaKeyLength=4096),void 0===e.requireQuantumResistantKeyExchange&&(e.requireQuantumResistantKeyExchange=!1),void 0===e.requireQuantumResistantSignatures&&(e.requireQuantumResistantSignatures=!1),void 0===e.requireQuantumResistantEncryption&&(e.requireQuantumResistantEncryption=!1);const t=g;for(const t in e)if("keyRequestTimeout"!==t&&"maxKeyRequestsPerSecond"!==t&&"rsaKeyLength"!==t&&"requireQuantumResistantKeyExchange"!==t&&"requireQuantumResistantSignatures"!==t&&"requireQuantumResistantEncryption"!==t&&"keys"!==t)return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.keyRequestTimeout;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/keyRequestTimeout",schemaPath:"#/properties/encryption/properties/keyRequestTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.maxKeyRequestsPerSecond;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/maxKeyRequestsPerSecond",schemaPath:"#/properties/encryption/properties/maxKeyRequestsPerSecond/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.rsaKeyLength;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/rsaKeyLength",schemaPath:"#/properties/encryption/properties/rsaKeyLength/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantKeyExchange)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantKeyExchange",schemaPath:"#/properties/encryption/properties/requireQuantumResistantKeyExchange/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantSignatures)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantSignatures",schemaPath:"#/properties/encryption/properties/requireQuantumResistantSignatures/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantEncryption)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantEncryption",schemaPath:"#/properties/encryption/properties/requireQuantumResistantEncryption/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g)if(void 0!==e.keys){let t=e.keys;const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const e in t){const t=g;if("string"!=typeof e){const t={instancePath:l+"/encryption/keys",schemaPath:"#/definitions/streamIdOrPath/type",keyword:"type",params:{type:"string"},message:"must be string",propertyName:e};null===p?p=[t]:p.push(t),g++}var I=t===g;if(!I){const t={instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/propertyNames",keyword:"propertyNames",params:{propertyName:e},message:"property name must be valid"};return null===p?p=[t]:p.push(t),g++,u.errors=p,!1}}if(I)for(const e in t){let n=t[e];const i=g;if(g===g){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===n.id&&(t="id")||void 0===n.data&&(t="data"))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;if(void 0!==n.id){const t=g;if("string"!=typeof n.id)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/id",schemaPath:"#/definitions/encryptionKey/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var P=t===g}else P=!0;if(P)if(void 0!==n.data){let t=n.data;const i=g;if(g===i&&g===i){if("string"!=typeof t)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}P=i===g}else P=!0}}if(!(i===g))break}}}else;}}}}}}}}if(m=t===g){let e=a.validation;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.permissions&&(e.permissions=!0),void 0===e.partitions&&(e.partitions=!0);const t=g;for(const t in e)if("permissions"!==t&&"partitions"!==t)return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.permissions)return u.errors=[{instancePath:l+"/validation/permissions",schemaPath:"#/properties/validation/properties/permissions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.partitions)return u.errors=[{instancePath:l+"/validation/partitions",schemaPath:"#/properties/validation/properties/partitions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}if(m=t===g){if(void 0!==a.metrics){let e=a.metrics;const t=g,r=g;let n=!1;const i=g;if("boolean"!=typeof e){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/0/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};null===p?p=[e]:p.push(e),g++}var T=i===g;if(n=n||T,!n){const t=g;if(g===t)if(e&&"object"==typeof e&&!Array.isArray(e)){const t=g;for(const t in e)if("periods"!==t&&"maxPublishDelay"!==t){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.periods){let t=e.periods;const r=g;if(g===r)if(Array.isArray(t)){const e=t.length;for(let r=0;r<e;r++){let e=t[r];const n=g;if(g===n)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.streamId&&(t="streamId")||void 0===e.duration&&(t="duration")){const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{if(void 0!==e.id){const t=g;if("string"!=typeof e.id){const e={instancePath:l+"/metrics/periods/"+r+"/id",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};null===p?p=[e]:p.push(e),g++}var _=t===g}else _=!0;if(_)if(void 0!==e.duration){let t=e.duration;const n=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/periods/"+r+"/duration",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/duration/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}_=n===g}else _=!0}}else{const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}if(!(n===g))break}}else{const e={instancePath:l+"/metrics/periods",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/type",keyword:"type",params:{type:"array"},message:"must be array"};null===p?p=[e]:p.push(e),g++}var N=r===g}else N=!0;if(N)if(void 0!==e.maxPublishDelay){let t=e.maxPublishDelay;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/maxPublishDelay",schemaPath:"#/properties/metrics/anyOf/1/properties/maxPublishDelay/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}N=r===g}else N=!0}}else{const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}T=t===g;n=n||T}if(!n){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}g=r,null!==p&&(r?p.length=r:p=null);m=t===g}else m=!0;if(m){let e=a.cache;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.maxSize&&(e.maxSize=1e4),void 0===e.maxAge&&(e.maxAge=864e5);const t=g;for(const t in e)if("maxSize"!==t&&"maxAge"!==t)return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.maxSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxSize",schemaPath:"#/properties/cache/properties/maxSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.maxAge;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxAge",schemaPath:"#/properties/cache/properties/maxAge/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(m=t===g){let e=a._timeouts;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.theGraph&&(e.theGraph={}),void 0===e.storageNode&&(e.storageNode={}),void 0===e.ensStreamCreation&&(e.ensStreamCreation={}),void 0===e.jsonRpcTimeout&&(e.jsonRpcTimeout=3e4);const t=g;for(const t in e)if("theGraph"!==t&&"storageNode"!==t&&"ensStreamCreation"!==t&&"jsonRpcTimeout"!==t)return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.theGraph;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.indexTimeout&&(t.indexTimeout=6e4),void 0===t.indexPollInterval&&(t.indexPollInterval=1e3),void 0===t.fetchTimeout&&(t.fetchTimeout=3e4);const e=g;for(const e in t)if("indexTimeout"!==e&&"indexPollInterval"!==e&&"fetchTimeout"!==e)return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.indexTimeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.indexPollInterval;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexPollInterval",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexPollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.fetchTimeout;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/fetchTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/fetchTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}if(r===g){let t=e.storageNode;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=3e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/timeout",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/retryInterval",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.ensStreamCreation;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=18e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/timeout",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/retryInterval",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.jsonRpcTimeout;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/_timeouts/jsonRpcTimeout",schemaPath:"#/properties/_timeouts/properties/jsonRpcTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}}m=t===g}}}}}}}}}}}}}}}}}}}return u.errors=p,0===g}return q1.exports}(),K1=n(z1);const G1={network:{controlLayer:{entryPointDiscovery:{enabled:!1},websocketPortRange:{min:32400,max:32800},iceServers:[],webrtcAllowPrivateAddresses:!0,websocketServerEnableTls:!1}},encryption:{rsaKeyLength:640},_timeouts:{theGraph:{indexTimeout:1e4,indexPollInterval:500},storageNode:{timeout:3e4,retryInterval:500},ensStreamCreation:{timeout:2e4,retryInterval:500}},metrics:!1};nb("0xde1112f631486CfC759A50196853011528bC5FA0");const V1=(e={})=>{let t=j1(e);const r=t.environment??aA;t=H1(r,t);const n=$1(t);return n.id??=VW("undefined"!=typeof process&&process.pid?`${process.pid}`:Wv(4),"/"),n},H1=(e,t)=>{const r=ZO.config[e];let n=aE({environment:e,network:{controlLayer:{entryPoints:r.entryPoints}},contracts:{ethereumNetwork:{chainId:r.id},streamRegistryChainAddress:r.contracts.StreamRegistry,streamStorageRegistryChainAddress:r.contracts.StreamStorageRegistry,storageNodeRegistryChainAddress:r.contracts.StorageNodeRegistry,sponsorshipFactoryChainAddress:r.contracts.SponsorshipFactory,rpcs:r.rpcEndpoints,theGraphUrl:r.theGraphUrl}},t);return"polygon"===e?n.contracts.ethereumNetwork={highGasPriceStrategy:!0,...n.contracts.ethereumNetwork}:"dev2"===e&&(n=aE(G1,n)),n},$1=e=>{if(!K1(e))throw new Error(K1.errors.map((e=>{let t=e.instancePath+" "+e.message;return e.params.additionalProperty&&(t+=`: ${e.params.additionalProperty}`),t})).join("\n"));return e},W1={...Object.fromEntries(l0.map((e=>[e.signatureType,e.keyType]))),[e.SignatureType.ECDSA_SECP256K1_LEGACY]:"ECDSA_SECP256K1_LEGACY",[e.SignatureType.ERC_1271]:"ERC_1271"};function J1(e){const t=W1[e];if(!t)throw new Error(`Unknown signature type: ${e}`);return t}const Q1=e=>({content:e.getParsedContent(),streamId:e.getStreamId(),streamPartition:e.getStreamPartition(),timestamp:e.getTimestamp(),sequenceNumber:e.getSequenceNumber(),signature:e.signature,signatureType:J1(e.signatureType),publisherId:e.getPublisherId(),msgChainId:e.getMsgChainId(),encryptionKeyId:e.groupKeyId,streamMessage:e});var Z1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},Y1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},X1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const e2={periods:[{duration:6e4,streamId:"streamr.eth/metrics/nodes/firehose/min"},{duration:36e5,streamId:"streamr.eth/metrics/nodes/firehose/hour"},{duration:864e5,streamId:"streamr.eth/metrics/nodes/firehose/day"}],maxPublishDelay:3e4};let t2=class{publisher;node;config;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.publisher=e,this.node=t,this.config=(e=>{if(!0===e.metrics)return e2;if(!1===e.metrics)return{...e2,periods:[]};if(void 0!==e.metrics)return aE(e2,e.metrics);{const t=void 0!==e.auth?.ethereum;return{...e2,periods:t?[]:e2.periods}}})(r),this.eventEmitter=n,this.destroySignal=i;const s=nJ((async()=>{const e=await this.node.getMetricsContext(),t=await this.node.getNodeId();this.config.periods.forEach((r=>{e.createReportProducer((async e=>{await this.publish(e,r.streamId,t)}),r.duration,this.destroySignal.abortSignal)}))}));this.config.periods.length>0&&(this.eventEmitter.on("messagePublished",(()=>s())),this.eventEmitter.on("streamPartSubscribed",(()=>s())))}async publish(e,t,r){await Qv(Math.random()*this.config.maxPublishDelay);const n={...e,node:{...e.node,id:r}};try{await this.publisher.publish(t,n,{timestamp:e.period.end,partitionKey:r})}catch(e){console.warn(`Unable to publish metrics: ${e.message}`)}}};t2=Z1([q(d.ContainerScoped),X1(2,U(cA)),Y1("design:paramtypes",[B1,GX,Object,sD,dJ])],t2);var r2=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},n2=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let i2=class{streamIdBuilder;operatorRegistry;node;logger;constructor(e,t,r,n){this.streamIdBuilder=e,this.operatorRegistry=t,this.node=r,this.logger=n.createLogger("ProxyNodeFinder")}async find(e,t=1,r=100,n=24){const[i,s]=await this.streamIdBuilder.toStreamPartElements(e);this.logger.debug(`Trying to find ${t} proxy nodes for stream ${i} partition ${s}`);const o=await this.operatorRegistry.findOperatorsOnStream(i,r,n);if(this.logger.debug(`Found ${o.length} operators on stream ${i}`),o.length<t)throw new Error(`Not enough operators found for stream ${i}: found ${o.length} operators, but ${t} are required`);const a=JU(o),c=[];let u=()=>{};const l=new Promise((e=>{u=e}));let h=0;const d=async e=>{for(;h<a.length&&c.length<t;){const r=a[h];h++;const n=EE(i,s??0);try{const i=await this.node.discoverOperators(r.peerDescriptor,n);i.length>0?c.length<t&&(this.logger.debug(`(worker ${e}): found ${i.length} nodes for operator ${r.operatorId} and streamPartId ${n}`),c.push(oA(i)),c.length>=t&&u()):this.logger.debug(`(worker ${e}): no nodes found for operator ${r.operatorId} and streamPartId ${n}`)}catch(t){this.logger.error(`(worker ${e}): error discovering nodes for operator ${r.operatorId}: ${t.message}`)}}};if(await Promise.race([Promise.all(Array.from({length:t},((e,t)=>d(t)))),l]),c.length<t)throw new Error(`Not enough proxy nodes were resolved for stream ${i}: found ${c.length} nodes, but ${t} are required`);return c}};var s2,o2;i2=r2([q(d.ContainerScoped),n2("design:paramtypes",[RJ,UY,GX,uD])],i2);var a2,c2,u2,l2,h2,d2,f2=n(function(){if(o2)return s2;o2=1;var e=De(),t=Be();return s2=function(r){return"number"==typeof r||t(r)&&"[object Number]"==e(r)}}());function p2(){if(l2)return u2;l2=1;var e=function(){if(c2)return a2;c2=1;var e=Math.ceil,t=Math.max;return a2=function(r,n,i,s){for(var o=-1,a=t(e((n-r)/(i||1)),0),c=Array(a);a--;)c[s?a:++o]=r,r+=i;return c}}(),t=_d(),r=Fe();return u2=function(n){return function(i,s,o){return o&&"number"!=typeof o&&t(i,s,o)&&(s=o=void 0),i=r(i),void 0===s?(s=i,i=0):s=r(s),o=void 0===o?i<s?1:-1:r(o),e(i,s,o,n)}}}var g2=function(){if(d2)return h2;d2=1;var e=p2()();return h2=e}(),m2=n(g2);class y2{id;client;constructor(e,t){this.id=e,this.client=t}publish(e,t){return this.client.publish(this.id,e,t)}async hasPermission(e){return this.client.hasPermission({streamId:this.id,...e})}async getPermissions(){return this.client.getPermissions(this.id)}async grantPermissions(...e){return this.client.grantPermissions(this.id,...e.map(NJ))}async revokePermissions(...e){return this.client.revokePermissions(this.id,...e.map(NJ))}async addToStorageNode(e,t={wait:!1}){await this.client.addStreamToStorageNode(this.id,e,t)}async removeFromStorageNode(e){return this.client.removeStreamFromStorageNode(this.id,nb(e))}async getStorageNodes(){return this.client.getStorageNodes(this.id)}async getStreamParts(){return m2(0,await this.getPartitionCount()).map((e=>EE(this.id,e)))}async getPartitionCount(){return IJ(await this.getMetadata())}async getDescription(){const e=(await this.getMetadata()).description;return _1(e)?e:void 0}async setDescription(e){await this.setMetadata({...await this.getMetadata(),description:e})}async getStorageDayCount(){const e=(await this.getMetadata()).storageDays;return f2(e)?e:void 0}async setStorageDayCount(e){await this.setMetadata({...await this.getMetadata(),storageDays:e})}async getMetadata(){return this.client.getStreamMetadata(this.id)}async setMetadata(e){await this.client.setStreamMetadata(this.id,e)}}function b2(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const i=o.prototype,s=Object.keys(i);for(let e=0;e<s.length;e++){const t=s[e];t in r||(r[t]=i[t].bind(r))}}const i=r?.Parent??Object;class s extends i{}function o(e){var t;const i=r?.Parent?new s:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}class w2 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v2 extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const E2={};function A2(e){return E2}function S2(e,t){return"bigint"==typeof t?t.toString():t}function k2(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function R2(e){return null==e}function C2(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const I2=Symbol("evaluating");function P2(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==I2)return void 0===n&&(n=I2,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function T2(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _2(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function N2(e){return JSON.stringify(e)}const M2="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function x2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const O2=k2((()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}}));function D2(e){if(!1===x2(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const r=t.prototype;return!1!==x2(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function B2(e){return D2(e)?{...e}:Array.isArray(e)?[...e]:e}const L2=new Set(["string","number","symbol"]);function F2(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function U2(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const j2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function q2(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function z2(e,t){return t.map((t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t}))}function K2(e){return"string"==typeof e?e:e?.message}function G2(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=K2(e.inst?._zod.def?.error?.(e))??K2(t?.error?.(e))??K2(r.customError?.(e))??K2(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function V2(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function H2(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const $2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,S2,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},W2=b2("$ZodError",$2),J2=b2("$ZodError",$2,{Parent:Error});const Q2=e=>(t,r,n,i)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new w2;if(o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>G2(e,s,A2()))));throw M2(t,i?.callee),t}return o.value},Z2=e=>async(t,r,n,i)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>G2(e,s,A2()))));throw M2(t,i?.callee),t}return o.value},Y2=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new w2;return s.issues.length?{success:!1,error:new(e??W2)(s.issues.map((e=>G2(e,i,A2()))))}:{success:!0,data:s.value}},X2=Y2(J2),e3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map((e=>G2(e,i,A2()))))}:{success:!0,data:s.value}},t3=e3(J2),r3=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Q2(e)(t,r,i)},n3=e=>(t,r,n)=>Q2(e)(t,r,n),i3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Z2(e)(t,r,i)},s3=e=>async(t,r,n)=>Z2(e)(t,r,n),o3=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Y2(e)(t,r,i)},a3=e=>(t,r,n)=>Y2(e)(t,r,n),c3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return e3(e)(t,r,i)},u3=e=>async(t,r,n)=>e3(e)(t,r,n),l3=/^-?\d+$/,h3=/^-?\d+(?:\.\d+)?/,d3=b2("$ZodCheck",((e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])})),f3={number:"number",bigint:"bigint",object:"date"},p3=b2("$ZodCheckLessThan",((e,t)=>{d3.init(e,t);const r=f3[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),g3=b2("$ZodCheckGreaterThan",((e,t)=>{d3.init(e,t);const r=f3[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),m3=b2("$ZodCheckMultipleOf",((e,t)=>{d3.init(e,t),e._zod.onattach.push((e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)})),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){const e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const s=r>i?r:i;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}})),y3=b2("$ZodCheckNumberFormat",((e,t)=>{d3.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=j2[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=l3)})),e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),b3=b2("$ZodCheckMaxLength",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const i=V2(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),w3=b2("$ZodCheckMinLength",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=V2(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),v3=b2("$ZodCheckLengthEquals",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length})),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const s=V2(n),o=i>t.length;r.issues.push({origin:s,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}})),E3=b2("$ZodCheckOverwrite",((e,t)=>{d3.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class A3{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),r=Math.min(...t.map((e=>e.length-e.trimStart().length))),n=t.map((e=>e.slice(r))).map((e=>" ".repeat(2*this.indent)+e));for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map((e=>` ${e}`))].join("\n"))}}const S3={major:4,minor:1,patch:13},k3=b2("$ZodType",((e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=S3;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,r)=>{let n,i=q2(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,o=s._zod.check(e);if(o instanceof Promise&&!1===r?.async)throw new w2;if(n||o instanceof Promise)n=(n??Promise.resolve()).then((async()=>{await o;e.issues.length!==t&&(i||(i=q2(e,t)))}));else{if(e.issues.length===t)continue;i||(i=q2(e,t))}}return n?n.then((()=>e)):e},r=(r,i,s)=>{if(q2(r))return r.aborted=!0,r;const o=t(i,n,s);if(o instanceof Promise){if(!1===s.async)throw new w2;return o.then((t=>e._zod.parse(t,s)))}return e._zod.parse(o,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){const t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then((e=>r(e,i,s))):r(t,i,s)}const o=e._zod.parse(i,s);if(o instanceof Promise){if(!1===s.async)throw new w2;return o.then((e=>t(e,n,s)))}return t(o,n,s)}}e["~standard"]={validate:t=>{try{const r=X2(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return t3(e,t).then((e=>e.success?{value:e.data}:{issues:e.error?.issues}))}},vendor:"zod",version:1}})),R3=b2("$ZodNumber",((e,t)=>{k3.init(e,t),e._zod.pattern=e._zod.bag.pattern??h3,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}})),C3=b2("$ZodNumberFormat",((e,t)=>{y3.init(e,t),R3.init(e,t)})),I3=b2("$ZodUnknown",((e,t)=>{k3.init(e,t),e._zod.parse=e=>e})),P3=b2("$ZodNever",((e,t)=>{k3.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}));function T3(e,t,r){e.issues.length&&t.issues.push(...z2(r,e.issues)),t.value[r]=e.value}const _3=b2("$ZodArray",((e,t)=>{k3.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let e=0;e<i.length;e++){const o=i[e],a=t.element._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then((t=>T3(t,r,e)))):T3(a,r,e)}return s.length?Promise.all(s).then((()=>r)):r}}));function N3(e,t,r,n){e.issues.length&&t.issues.push(...z2(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function M3(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=e.shape,Object.keys(n).filter((e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout)));var n;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function x3(e,t,r,n,i,s){const o=[],a=i.keySet,c=i.catchall._zod,u=c.def.type;for(const i in t){if(a.has(i))continue;if("never"===u){o.push(i);continue}const s=c.run({value:t[i],issues:[]},n);s instanceof Promise?e.push(s.then((e=>N3(e,r,i,t)))):N3(s,r,i,t)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then((()=>r)):r}const O3=b2("$ZodObject",((e,t)=>{k3.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=k2((()=>M3(t)));P2(e._zod,"propValues",(()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r}));const i=x2,s=t.catchall;let o;e._zod.parse=(t,r)=>{o??(o=n.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=o.shape;for(const e of o.keys){const n=u[e]._zod.run({value:a[e],issues:[]},r);n instanceof Promise?c.push(n.then((r=>N3(r,t,e,a)))):N3(n,t,e,a)}return s?x3(c,a,t,r,n.value,e):c.length?Promise.all(c).then((()=>t)):t}})),D3=b2("$ZodObjectJIT",((e,t)=>{O3.init(e,t);const r=e._zod.parse,n=k2((()=>M3(t)));let i;const s=x2,o=!E2.jitless,a=o&&O2.value,c=t.catchall;let u;e._zod.parse=(l,h)=>{u??(u=n.value);const d=l.value;return s(d)?o&&a&&!1===h?.async&&!0!==h.jitless?(i||(i=(e=>{const t=new A3(["shape","payload","ctx"]),r=n.value,i=e=>{const t=N2(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let o=0;for(const e of r.keys)s[e]="key_"+o++;t.write("const newResult = {};");for(const e of r.keys){const r=s[e],n=N2(e);t.write(`const ${r} = ${i(e)};`),t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}]\n })));\n }\n \n \n if (${r}.value === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n newResult[${n}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),l=i(l,h),c?x3([],d,l,h,u,e):l):r(l,h):(l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l)}}));function B3(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter((e=>!q2(e)));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((e=>e.issues.map((e=>G2(e,n,A2())))))}),t)}const L3=b2("$ZodUnion",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),P2(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),P2(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),P2(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>C2(e.source))).join("|")})$`)}}));const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},s);if(t instanceof Promise)a.push(t),o=!0;else{if(0===t.issues.length)return t;a.push(t)}}return o?Promise.all(a).then((t=>B3(t,i,e,s))):B3(a,i,e,s)}})),F3=b2("$ZodIntersection",((e,t)=>{k3.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,i=t.left._zod.run({value:n,issues:[]},r),s=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then((([t,r])=>j3(e,t,r))):j3(e,i,s)}}));function U3(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(D2(e)&&D2(t)){const r=Object.keys(t),n=Object.keys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const r of n){const n=U3(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=U3(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function j3(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),q2(e))return e;const n=U3(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const q3=b2("$ZodEnum",((e,t)=>{k3.init(e,t);const r=function(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,r])=>-1===t.indexOf(+e))).map((([e,t])=>t))}(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((e=>L2.has(typeof e))).map((e=>"string"==typeof e?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e.toString())).join("|")})$`),e._zod.parse=(t,i)=>{const s=t.value;return n.has(s)||t.issues.push({code:"invalid_value",values:r,input:s,inst:e}),t}})),z3=b2("$ZodTransform",((e,t)=>{k3.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new v2(e.constructor.name);const i=t.transform(r.value,r);if(n.async){return(i instanceof Promise?i:Promise.resolve(i)).then((e=>(r.value=e,r)))}if(i instanceof Promise)throw new w2;return r.value=i,r}}));function K3(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const G3=b2("$ZodOptional",((e,t)=>{k3.init(e,t),e._zod.optin="optional",e._zod.optout="optional",P2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),P2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${C2(e.source)})?$`):void 0})),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((t=>K3(t,e.value))):K3(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}})),V3=b2("$ZodNullable",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.innerType._zod.optin)),P2(e._zod,"optout",(()=>t.innerType._zod.optout)),P2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${C2(e.source)}|null)$`):void 0})),P2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)})),H3=b2("$ZodDefault",((e,t)=>{k3.init(e,t),e._zod.optin="optional",P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((e=>$3(e,t))):$3(n,t)}}));function $3(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const W3=b2("$ZodPrefault",((e,t)=>{k3.init(e,t),e._zod.optin="optional",P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))})),J3=b2("$ZodNonOptional",((e,t)=>{k3.init(e,t),P2(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then((t=>Q3(t,e))):Q3(i,e)}}));function Q3(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Z3=b2("$ZodCatch",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.innerType._zod.optin)),P2(e._zod,"optout",(()=>t.innerType._zod.optout)),P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>G2(e,r,A2())))},input:e.value}),e.issues=[]),e))):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>G2(e,r,A2())))},input:e.value}),e.issues=[]),e)}})),Y3=b2("$ZodPipe",((e,t)=>{k3.init(e,t),P2(e._zod,"values",(()=>t.in._zod.values)),P2(e._zod,"optin",(()=>t.in._zod.optin)),P2(e._zod,"optout",(()=>t.out._zod.optout)),P2(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,r)=>{if("backward"===r.direction){const n=t.out._zod.run(e,r);return n instanceof Promise?n.then((e=>X3(e,t.in,r))):X3(n,t.in,r)}const n=t.in._zod.run(e,r);return n instanceof Promise?n.then((e=>X3(e,t.out,r))):X3(n,t.out,r)}}));function X3(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const e6=b2("$ZodReadonly",((e,t)=>{k3.init(e,t),P2(e._zod,"propValues",(()=>t.innerType._zod.propValues)),P2(e._zod,"values",(()=>t.innerType._zod.values)),P2(e._zod,"optin",(()=>t.innerType?._zod?.optin)),P2(e._zod,"optout",(()=>t.innerType?._zod?.optout)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t6):t6(n)}}));function t6(e){return e.value=Object.freeze(e.value),e}const r6=b2("$ZodCustom",((e,t)=>{d3.init(e,t),k3.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then((t=>n6(t,r,n,e)));n6(i,r,n,e)}}));function n6(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(H2(e))}}var i6;class s6{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(i6=globalThis).__zod_globalRegistry??(i6.__zod_globalRegistry=new s6);const o6=globalThis.__zod_globalRegistry;function a6(e,t){return new p3({check:"less_than",...U2(t),value:e,inclusive:!1})}function c6(e,t){return new p3({check:"less_than",...U2(t),value:e,inclusive:!0})}function u6(e,t){return new g3({check:"greater_than",...U2(t),value:e,inclusive:!1})}function l6(e,t){return new g3({check:"greater_than",...U2(t),value:e,inclusive:!0})}function h6(e,t){return new m3({check:"multiple_of",...U2(t),value:e})}function d6(e,t){return new w3({check:"min_length",...U2(t),minimum:e})}function f6(e){const t=function(e,t){const r=new d3({check:"custom",...U2(t)});return r._zod.check=e,r}((r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(H2(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(H2(n))}},e(r.value,r))));return t}const p6=b2("ZodError",((e,t)=>{W2.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const r={_errors:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map((e=>n({issues:e})));else if("invalid_key"===i.code)n({issues:i.issues});else if("invalid_element"===i.code)n({issues:i.issues});else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(e),r}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,S2,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,S2,2)}},isEmpty:{get:()=>0===e.issues.length}})}),{Parent:Error}),g6=Q2(p6),m6=Z2(p6),y6=Y2(p6),b6=e3(p6),w6=r3(p6),v6=n3(p6),E6=i3(p6),A6=s3(p6),S6=o3(p6),k6=a3(p6),R6=c3(p6),C6=u3(p6),I6=b2("ZodType",((e,t)=>(k3.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(_2(t,{checks:[...t.checks??[],...r.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]})),e.clone=(t,r)=>F2(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>g6(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>y6(e,t,r),e.parseAsync=async(t,r)=>m6(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>b6(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>w6(e,t,r),e.decode=(t,r)=>v6(e,t,r),e.encodeAsync=async(t,r)=>E6(e,t,r),e.decodeAsync=async(t,r)=>A6(e,t,r),e.safeEncode=(t,r)=>S6(e,t,r),e.safeDecode=(t,r)=>k6(e,t,r),e.safeEncodeAsync=async(t,r)=>R6(e,t,r),e.safeDecodeAsync=async(t,r)=>C6(e,t,r),e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...U2(r)})}(X6,e,t)}(t,r)),e.superRefine=t=>e.check(f6(t)),e.overwrite=t=>e.check(new E3({check:"overwrite",tx:t})),e.optional=()=>K6(e),e.nullable=()=>V6(e),e.nullish=()=>K6(V6(e)),e.nonoptional=t=>function(e,t){return new W6({type:"nonoptional",innerType:e,...U2(t)})}(e,t),e.array=()=>{return function(e,t,r){return new e({type:"array",element:t,...U2(r)})}(B6,e,t);var t},e.or=t=>{return new F6({type:"union",options:[e,t],...U2(r)});var r},e.and=t=>new U6({type:"intersection",left:e,right:t}),e.transform=t=>Z6(e,new q6({type:"transform",transform:t})),e.default=t=>{return r=t,new H6({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():B2(r)}});var r},e.prefault=t=>{return r=t,new $6({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():B2(r)}});var r},e.catch=t=>{return new J6({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>Z6(e,t),e.readonly=()=>new Y6({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return o6.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>o6.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return o6.get(e);const r=e.clone();return o6.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),P6=b2("ZodNumber",((e,t)=>{R3.init(e,t),I6.init(e,t),e.gt=(t,r)=>e.check(u6(t,r)),e.gte=(t,r)=>e.check(l6(t,r)),e.min=(t,r)=>e.check(l6(t,r)),e.lt=(t,r)=>e.check(a6(t,r)),e.lte=(t,r)=>e.check(c6(t,r)),e.max=(t,r)=>e.check(c6(t,r)),e.int=t=>e.check(N6(t)),e.safe=t=>e.check(N6(t)),e.positive=t=>e.check(u6(0,t)),e.nonnegative=t=>e.check(l6(0,t)),e.negative=t=>e.check(a6(0,t)),e.nonpositive=t=>e.check(c6(0,t)),e.multipleOf=(t,r)=>e.check(h6(t,r)),e.step=(t,r)=>e.check(h6(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}));function T6(e){return function(e,t){return new e({type:"number",checks:[],...U2(t)})}(P6,e)}const _6=b2("ZodNumberFormat",((e,t)=>{C3.init(e,t),P6.init(e,t)}));function N6(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U2(t)})}(_6,e)}const M6=b2("ZodUnknown",((e,t)=>{I3.init(e,t),I6.init(e,t)}));function x6(){return new M6({type:"unknown"})}const O6=b2("ZodNever",((e,t)=>{P3.init(e,t),I6.init(e,t)}));function D6(e){return function(e,t){return new e({type:"never",...U2(t)})}(O6,e)}const B6=b2("ZodArray",((e,t)=>{_3.init(e,t),I6.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(d6(t,r)),e.nonempty=t=>e.check(d6(1,t)),e.max=(t,r)=>e.check(function(e,t){return new b3({check:"max_length",...U2(t),maximum:e})}(t,r)),e.length=(t,r)=>e.check(function(e,t){return new v3({check:"length_equals",...U2(t),length:e})}(t,r)),e.unwrap=()=>e.element}));const L6=b2("ZodObject",((e,t)=>{D3.init(e,t),I6.init(e,t),P2(e,"shape",(()=>t.shape)),e.keyof=()=>function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new j6({type:"enum",entries:r,...U2(t)})}(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:x6()}),e.loose=()=>e.clone({...e._zod.def,catchall:x6()}),e.strict=()=>e.clone({...e._zod.def,catchall:D6()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!D2(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const n=_2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return T2(this,"shape",r),r},checks:[]});return F2(e,n)}(e,t),e.safeExtend=t=>function(e,t){if(!D2(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return T2(this,"shape",r),r},checks:e._zod.def.checks};return F2(e,r)}(e,t),e.merge=t=>function(e,t){const r=_2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return T2(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return F2(e,r)}(e,t),e.pick=t=>function(e,t){const r=e._zod.def,n=_2(e._zod.def,{get shape(){const e={};for(const n in t){if(!(n in r.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return T2(this,"shape",e),e},checks:[]});return F2(e,n)}(e,t),e.omit=t=>function(e,t){const r=e._zod.def,n=_2(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const e in t){if(!(e in r.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return T2(this,"shape",n),n},checks:[]});return F2(e,n)}(e,t),e.partial=(...t)=>function(e,t,r){const n=_2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return T2(this,"shape",i),i},checks:[]});return F2(t,n)}(z6,e,t[0]),e.required=(...t)=>function(e,t,r){const n=_2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return T2(this,"shape",i),i},checks:[]});return F2(t,n)}(W6,e,t[0])}));const F6=b2("ZodUnion",((e,t)=>{L3.init(e,t),I6.init(e,t),e.options=t.options}));const U6=b2("ZodIntersection",((e,t)=>{F3.init(e,t),I6.init(e,t)}));const j6=b2("ZodEnum",((e,t)=>{q3.init(e,t),I6.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const i={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new j6({...t,checks:[],...U2(n),entries:i})},e.exclude=(e,n)=>{const i={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new j6({...t,checks:[],...U2(n),entries:i})}}));const q6=b2("ZodTransform",((e,t)=>{z3.init(e,t),I6.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new v2(e.constructor.name);r.addIssue=n=>{if("string"==typeof n)r.issues.push(H2(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(H2(t))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then((e=>(r.value=e,r))):(r.value=i,r)}}));const z6=b2("ZodOptional",((e,t)=>{G3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function K6(e){return new z6({type:"optional",innerType:e})}const G6=b2("ZodNullable",((e,t)=>{V3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function V6(e){return new G6({type:"nullable",innerType:e})}const H6=b2("ZodDefault",((e,t)=>{H3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));const $6=b2("ZodPrefault",((e,t)=>{W3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const W6=b2("ZodNonOptional",((e,t)=>{J3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const J6=b2("ZodCatch",((e,t)=>{Z3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));const Q6=b2("ZodPipe",((e,t)=>{Y3.init(e,t),I6.init(e,t),e.in=t.in,e.out=t.out}));function Z6(e,t){return new Q6({type:"pipe",in:e,out:t})}const Y6=b2("ZodReadonly",((e,t)=>{e6.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const X6=b2("ZodCustom",((e,t)=>{r6.init(e,t),I6.init(e,t)}));class e4 extends Error{reasonText;constructor(e){super(`Failed to parse metadata: ${e}`),this.reasonText=e}}const t4=new Bv("Operator");class r4{contractAddress;contract;contractReadonly;contractFactory;rpcProviderSource;theGraphClient;identity;getEthersOverrides;eventEmitter=new sE;constructor(e,t,r,n,i,s,o,a,c){this.contractAddress=e,this.contractFactory=t,this.rpcProviderSource=r,this.contractReadonly=t.createReadContract(nb(e),SA.OperatorABI,r.getProvider(),"operator"),this.theGraphClient=i,this.identity=s,this.getEthersOverrides=c,this.initEventGateways(e,n,a),o.onDestroy.listen((()=>{this.eventEmitter.removeAllListeners()}))}initEventGateways(e,t,r){const n=new uN(SA.OperatorABI),i=([e])=>({sponsorship:nb(e)});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Staked"),contractAddress:e},sourceEmitter:t,targetName:"staked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Unstaked"),contractAddress:e},sourceEmitter:t,targetName:"unstaked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("ReviewRequest"),contractAddress:e},sourceEmitter:t,targetName:"reviewRequested",targetEmitter:this.eventEmitter,transformation:([e,t,r,n,i])=>{const s=function(e){if(void 0===e)throw new e4("no metadata");let t;try{t=JSON.parse(e)}catch{throw new e4("malformed metadata")}const r=Number(t.partition);if(isNaN(r))throw new e4('invalid or missing "partition" field');try{vE(r)}catch{throw new e4("invalid partition numbering")}return r}(i);return{sponsorship:nb(e),targetOperator:nb(t),partition:s,votingPeriodStartTimestamp:1e3*Number(r),votingPeriodEndTimestamp:1e3*Number(n)}},loggerFactory:r})}async writeHeartbeat(e){const t=JSON.stringify(e);await this.connectToContract(),await(await this.contract.heartbeat(t,await this.getEthersOverrides())).wait()}async getTimestampOfLastHeartbeat(){const e=await this.theGraphClient.queryEntity({query:`{\n operator(id: "${await this.getContractAddress()}") {\n latestHeartbeatTimestamp\n }\n }`});if(null!==e.operator&&null!==e.operator.latestHeartbeatTimestamp){const t=parseInt(e.operator.latestHeartbeatTimestamp);if(isNaN(t))throw new Error("Assertion failed: unexpected non-integer latestHeartbeatTimestamp");return 1e3*t}}async getContractAddress(){return nb(await this.contractReadonly.getAddress())}async getSponsorships(){const e=await this.getContractAddress(),t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n operator(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n sponsorship {\n id\n operatorCount\n stream {\n id\n }\n }\n }\n }\n }\n `})),(e=>e.operator?.stakes??[])),r=[];for await(const e of t)r.push({sponsorshipAddress:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id),operatorCount:e.sponsorship.operatorCount});return r}async getExpiredFlags(e,t){const r=Math.floor((Date.now()-t)/1e3),n=this.theGraphClient.queryEntities(((t,n)=>({query:`\n {\n flags (where : {\n id_gt: "${t}",\n voteEndTimestamp_lt: ${r},\n result_in: ["waiting", "voting"],\n sponsorship_in: ${JSON.stringify(e)}\n }, first: ${n}) {\n id\n flaggingTimestamp\n target {\n id\n }\n sponsorship {\n id\n }\n }\n }`}))),i=[];for await(const e of n)i.push({id:e.id,flaggingTimestamp:e.flaggingTimestamp,targetOperator:nb(e.target.id),sponsorship:nb(e.sponsorship.id)});return i}async getOperatorsInSponsorship(e){const t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n sponsorship(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n operator {\n id\n }\n }\n }\n }\n `})),(e=>e.sponsorship?.stakes??[])),r=[];for await(const e of t)r.push(nb(e.operator.id));return r}async flag(e,t,r){const n=JSON.stringify({partition:r});await this.connectToContract(),await(await this.contract.flag(e,t,n,await this.getEthersOverrides())).wait()}async getEarnings(e,t){const{addresses:r,earnings:n,maxAllowedEarnings:i}=await this.contractReadonly.getSponsorshipsAndEarnings(),s=r.map(((e,t)=>({address:e,earnings:n[t]}))).filter((t=>t.earnings>=e)).sort(((e,t)=>((e,t)=>e<t?-1:e>t?1:0)(e.earnings,t.earnings))).slice(0,t);return{sponsorshipAddresses:s.map((e=>nb(e.address))),sum:s.reduce(((e,t)=>e+t.earnings),0n),maxAllowedEarnings:i}}async withdrawEarningsFromSponsorships(e){await this.connectToContract(),await(await this.contract.withdrawEarningsFromSponsorships(e,await this.getEthersOverrides())).wait()}async triggerAnotherOperatorWithdraw(e,t){await this.connectToContract(),await(await this.contract.triggerAnotherOperatorWithdraw(e,t,await this.getEthersOverrides())).wait()}async getStakedOperators(){const e=this.theGraphClient.queryEntities(((e,t)=>({query:`\n {\n operators(where: {totalStakeInSponsorshipsWei_gt: "0", id_gt: "${e}"}, first: ${t}) {\n id\n }\n }\n `}))),t=[];for await(const r of e)t.push(nb(r.id));return t}async*pullStakedStreams(e){const t=await this.getContractAddress();this.theGraphClient.updateRequiredBlockNumber(e);const r=this.theGraphClient.queryEntities(((e,r)=>({query:`\n {\n operator(id: "${t}") {\n stakes(where: {id_gt: "${e}"}, first: ${r}) {\n sponsorship {\n id\n stream {\n id\n }\n }\n }\n }\n _meta {\n block {\n number\n }\n }\n }\n `})),(e=>e.operator?e.operator.stakes:(t4.error("Unable to find operator in The Graph",{operatorContractAddress:t}),[])));for await(const e of r)yield{sponsorship:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id)}}async hasOpenFlag(e){const t=await this.getContractAddress(),r=this.theGraphClient.queryEntities((()=>({query:`\n {\n flags(where: {\n sponsorship: "${e}",\n target: "${t}",\n result_in: ["waiting", "voting"]\n }) {\n id\n }\n }\n `}))),n=await cE(r,1);return n.length>0&&(t4.debug("Found open flag",{flag:n[0]}),!0)}async getStreamId(e){const t=this.contractFactory.createReadContract(nb(e),SA.SponsorshipABI,this.rpcProviderSource.getProvider(),"sponsorship");return bE(await t.streamId())}async voteOnFlag(e,t,r){const n=r?"0x0000000000000000000000000000000000000000000000000000000000000001":"0x0000000000000000000000000000000000000000000000000000000000000000";await this.connectToContract();const i=1300000n,s=await this.contract.voteOnFlag.estimateGas(e,t,n);if(s>i)throw new Error(`Gas estimate (${s}) exceeds limit (1300000)`);await(await this.contract.voteOnFlag(e,t,n,{...await this.getEthersOverrides(),gasLimit:i})).wait()}async closeFlag(e,t){await this.voteOnFlag(e,t,!1)}async fetchRedundancyFactor(){const e=function(e,t){const r={type:"object",shape:e??{},...U2(t)};return new L6(r)}({redundancyFactor:T6().int().gte(1)}),t=await this.contractReadonly.metadata();if(0===t.length)return 1;let r,n;try{r=JSON.parse(t)}catch{return void t4.warn("Encountered malformed metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t})}try{n=e.parse(r)}catch(e){return void t4.warn("Encountered invalid metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t,reason:e?.reason})}return n.redundancyFactor}getCurrentBlockNumber(){return this.rpcProviderSource.getProvider().getBlockNumber()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}async connectToContract(){if(void 0===this.contract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.contract=this.contractFactory.createWriteContract(this.contractAddress,SA.OperatorABI,e,"operator")}}}var n4=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},i4=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s4=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let o4=class{config;constructor(e,t,r,n){this.config=t,this.initEventListener(r,e,n)}initEventListener(e,t,r){const n=nb(this.config.contracts.sponsorshipFactoryChainAddress),i=new uN(SA.SponsorshipFactoryABI);wD({sourceDefinition:{contractInterfaceFragment:i.getEvent("NewSponsorship"),contractAddress:n},sourceEmitter:t,targetName:"sponsorshipCreated",targetEmitter:e,transformation:([e,t],r)=>({sponsorshipContractAddress:nb(e),streamId:bE(t),blockNumber:r}),loggerFactory:r})}};o4=n4([q(d.ContainerScoped),s4(1,U(cA)),i4("design:paramtypes",[cQ,Object,sD,uD])],o4);var a4,c4=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},u4=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},l4=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};!function(e){e[e.NONE=0]="NONE",e[e.NORMAL=1]="NORMAL",e[e.ERC_1271=2]="ERC_1271"}(a4||(a4={}));let h4=class{networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;identity;logger;erc1271Publishers=new Set;config;constructor(t,r,n,i,s,o,a,c,u){this.networkNodeFacade=t,this.streamRegistry=r,this.signatureValidator=n,this.messageSigner=i,this.store=s,this.identity=o,this.logger=u.createLogger("PublisherKeyExchange"),this.config=a,void 0===a.encryption.keys&&(t.once("start",(async()=>{t.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),c.on("messagePublished",(t=>{if(t.signatureType===e.SignatureType.ERC_1271){const e=t.getPublisherId();this.erc1271Publishers.has(e)||(this.logger.debug("Add ERC-1271 publisher",{publisherId:e}),this.erc1271Publishers.add(e))}})))}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)try{const{recipientId:e,requestId:r,publicKey:n,groupKeyIds:i,encryptionType:s}=DH.fromBinary(t.content),o=kE(e);if(!function(e,t){const r=R0.has(e),n=t.encryption?.requireQuantumResistantKeyExchange;return r||!n}(s,this.config))throw new uA(`EncryptionType in key request (${s}) is not compliant with encryption settings!`,"ENCRYPTION_POLICY_VIOLATION",t);const a=await this.getResponseType(o);if(a!==a4.NONE){this.logger.debug("Handling group key request",{requestId:r,responseType:a,keyEncryptionType:PH[s]}),await y0(t,this.streamRegistry,this.signatureValidator,this.config);const e=await this.identity.getUserId(),c=ju(await Promise.all(i.map((t=>this.store.get(t,e)))),void 0);if(c.length>0){const e=await this.createResponse(c,a,o,t.getStreamPartID(),n,t.getPublisherId(),r,s);await this.networkNodeFacade.broadcast(e),this.logger.debug("Handled group key request (found keys)",{groupKeyIds:c.map((e=>e.id)).join(),recipient:t.getPublisherId()})}else this.logger.debug("Handled group key request (no keys found)",{requestId:r,recipient:t.getPublisherId()})}}catch(e){this.logger.debug("Failed to handle group key request",e)}}async getResponseType(e){return e===await this.identity.getUserId()?a4.NORMAL:this.erc1271Publishers.has(e)?a4.ERC_1271:a4.NONE}async createResponse(t,r,n,i,s,o,a,c){const u=await Promise.all(t.map((async e=>({id:e.id,data:await YQ.encryptForPublicKey(e.data,s,c)})))),l={recipientId:RE(o),requestId:a,groupKeys:u,encryptionType:c};return this.messageSigner.createSignedMessage({messageId:new CW(AE.getStreamID(i),AE.getStreamPartition(i),Date.now(),0,n,VX()),content:BH.toBinary(l),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_RESPONSE,encryptionType:e.EncryptionType.NONE},r===a4.NORMAL?this.identity.getSignatureType():e.SignatureType.ERC_1271)}};h4=c4([q(d.ContainerScoped),l4(5,U(kA)),l4(6,U(cA)),u4("design:paramtypes",[GX,EQ,m0,e.MessageSigner,OZ,RA,Object,sD,uD])],h4);class d4{pipeline;onFinally;onBeforeFinally;onError;constructor(e){this.pipeline=e??new uJ,this.onFinally=this.pipeline.onFinally,this.onBeforeFinally=this.pipeline.onBeforeFinally,this.onError=this.pipeline.onError}useLegacyOnMessageHandler(e){return this.pipeline.onMessage.listen((async t=>{const r=Q1(t);await e(r.content,BY(r,"content"))})),this.pipeline.flow(),this}async*[Symbol.asyncIterator](){for await(const e of this.pipeline)yield Q1(e)}async push(e){await this.pipeline.push(e)}pipe(e){return this.pipeline.pipe(e)}async handleError(e){await this.pipeline.handleError(e)}end(e){this.pipeline.end(e)}isDone(){return this.pipeline.isDone()}return(){return this.pipeline.return()}}class f4 extends d4{streamPartId;isRaw;erc1271ContractAddress;deliveryOptions;eventEmitter;logger;constructor(e,t,r,n,i,s){super(),this.streamPartId=e,this.isRaw=t,this.erc1271ContractAddress=r,this.deliveryOptions=n,this.eventEmitter=i,this.logger=s.createLogger("Subscription"),this.onError.listen((e=>{this.eventEmitter.emit("error",e),this.logger.debug("Encountered error",{err:e})}))}async unsubscribe(){this.end(),await this.return(),this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}}const p4=new Bv("waitForStorage");const g4=async(e,t,r,n,i,s,o,a,c)=>{if(r.wait){if(await o.isStoredStream(e,t))return;let u;try{const s=EE(HW(t),0);u=new f4(s,!1,void 0,void 0,new Sl,a),await i.add(u);const l=async function(e,t,r){const n=new Set;for await(const i of e){const e=i.content.streamPart;try{const r=AE.parse(e),[i,s]=AE.getStreamIDAndPartition(r);if(i===t.id&&s<t.partitions&&(n.add(s),n.size===t.partitions))return}catch{r.createLogger("waitForAssignmentsToPropagate").debug("Ignore malformed content")}}}(u,{id:e,partitions:n},a);await o.addStreamToStorageNode(e,t),await Xv(l,r.timeout??c._timeouts.storageNode.timeout,"storage node did not respond")}finally{s.invalidatePermissionCaches(e),await(u?.unsubscribe())}}else await o.addStreamToStorageNode(e,t)},m4=new Bv("StreamrClient");const y4=function(e,t){DA("string"==typeof e,"value must be a string","value",e);let r=18;return r=cS(t,"unit"),HS.fromString(e,{decimals:r,width:512}).value}("1",18);const b4=new Bv("operatorContractUtils");const w4=async(e,t,r,n,i)=>{const s=A4(n),o=await s.connect(e).transferAndCall(t,r,"0x");await o.wait(void 0,i)},v4=e=>new JN(e,SA.OperatorABI),E4=e=>new JN(e,SA.SponsorshipABI),A4=e=>new JN(e,SA.DATAv2ABI),S4={delegate:async(e,t,r,n)=>{b4.debug("Delegate",{amount:r.toString()});const i=await v4(t).connect(e.provider).token();await w4(e,t,r,i,n)},undelegate:async(e,t,r,n)=>{b4.debug("Undelegate",{amount:r.toString()}),await(await v4(t).connect(e).undelegate(r)).wait(void 0,n)},deploySponsorshipContract:async function(e){b4.debug("Deploying SponsorshipContract");const t=[{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipStakeWeightedAllocationPolicy,param:e.earningsPerSecond},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipDefaultLeavePolicy,param:e.minStakeDuration??0},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipVoteKickPolicy,param:0}];void 0!==e.maxOperatorCount&&t.push({contractAddress:ZO.config[e.environmentId].contracts.SponsorshipMaxOperatorsJoinPolicy,param:e.maxOperatorCount});const r=rN.defaultAbiCoder().encode(["uint32","string","string","address[]","uint[]"],[(e.minOperatorCount??1).toString(),e.streamId,e.metadata??"{}",t.map((e=>e.contractAddress)),t.map((e=>e.param))]),n=await A4(ZO.config[e.environmentId].contracts.DATA).connect(e.deployer).transferAndCall(ZO.config[e.environmentId].contracts.SponsorshipFactory,e.sponsorAmount??0n,r),i=await n.wait(void 0,e.transactionTimeout),s=new uN(SA.SponsorshipFactoryABI),o=i.logs.map((e=>s.parseLog(e))).find((e=>"NewSponsorship"===e?.name)).args.sponsorshipContract;return b4.debug("Deployed SponsorshipContract",{address:o}),new JN(o,SA.SponsorshipABI,e.deployer)},sponsor:async(e,t,r,n)=>{b4.debug("Sponsor",{amount:r.toString()});const i=await E4(t).connect(e.provider).token();await w4(e,t,r,i,n)},stake:async(e,t,r,n,i={},s=()=>{},o)=>{b4.debug("Stake",{amount:rk(n),sponsorshipContractAddress:r});const a=v4(t).connect(e),c=await a.stake(r,n,i);b4.debug("Stake: transaction submitted",{tx:c.hash,nonce:c.nonce}),s(c),b4.debug("Stake: waiting for transaction to be mined",{tx:c.hash,timeout:o});try{const e=await c.wait(void 0,o);return b4.debug("Stake: confirmation received",{receipt:e?.hash}),e}catch(e){throw b4.error("Stake: error waiting for tx to be mined",{tx:c.hash,error:e}),e}},unstake:async(e,t,r,n,i={},s=()=>{},o)=>{b4.debug("Unstake",{amount:rk(n),sponsorshipContractAddress:r});const a=v4(t).connect(e),c=E4(r).connect(e),u=await c.stakedWei(t)-n,l=await a.reduceStakeTo(r,u,i);b4.debug("Unstake: transaction submitted",{tx:l.hash,nonce:l.nonce}),s(l),b4.debug("Unstake: waiting for transaction to be mined",{tx:l.hash,timeout:o});try{const e=await l.wait(void 0,o);return b4.debug("Unstake: confirmation received",{receipt:e?.hash}),e}catch(e){throw b4.error("Unstake: error waiting for tx to be mined",{tx:l.hash,error:e}),e}},deployOperatorContract:async function(e){b4.debug("Deploying OperatorContract");const t=new JN(ZO.config[e.environmentId].contracts.OperatorFactory,SA.OperatorFactoryABI,e.deployer);if(await t.operators(await e.deployer.getAddress())!==CI)throw new Error("Operator already has a contract");var r,n;const i=(await(await t.deployOperator((r=y4,n=(e.operatorsCutPercentage??0)/100,r*BigInt(IE*n)/BigInt(IE)),e.operatorTokenName??`OperatorToken-${Date.now()}`,e.metadata??"",[ZO.config[e.environmentId].contracts.OperatorDefaultDelegationPolicy,ZO.config[e.environmentId].contracts.OperatorDefaultExchangeRatePolicy,ZO.config[e.environmentId].contracts.OperatorDefaultUndelegationPolicy],[0,0,0])).wait(void 0,e.transactionTimeout)).logs.find((e=>"NewOperator"===e.fragment?.name)).args.operatorContractAddress,s=new JN(i,SA.OperatorABI,e.deployer);return b4.debug("Deployed OperatorContract",{address:i}),s},getOperatorContract:v4};e.ConfigInjectionToken=cA,e.DEFAULT_ENVIRONMENT_ID=aA,e.DEFAULT_KEY_TYPE=h0,e.ECDSAKeyPairIdentity=u0,e.ENVIRONMENT_IDS=["polygon","polygonAmoy","peaq","iotex","dev2"],e.EncryptedGroupKey=LH,e.EncryptionKey=eZ,e.EthereumKeyPairIdentity=i0,e.EthereumProviderIdentity=s0,e.Identity=RA,e.KeyPairIdentity=r0,e.MLDSAKeyPairIdentity=a0,e.MessageID=CW,e.MessageRef=RW,e.Operator=r4,e.STREAMR_STORAGE_NODE_ADDRESS="0x9dc08ff97f5c156181ec6a0b13fc3946454e529a",e.STREAMR_STORAGE_NODE_GERMANY="0x31546eEA76F2B2b3C5cC06B1c93601dc35c9D916",e.Stream=y2,e.StreamMessage=PW,e.StreamrClient=class{id;publisher;subscriber;resends;node;rpcProviderSource;streamRegistry;streamStorageRegistry;storageNodeRegistry;operatorRegistry;contractFactory;localGroupKeyStore;chainEventPoller;theGraphClient;streamIdBuilder;config;identity;eventEmitter;destroySignal;loggerFactory;proxyNodeFinder;constructor(t={},r=F){const n=V1(t),i=function(e){if(void 0!==e.auth?.privateKey){const t=e.auth.keyType??h0,r=l0.find((e=>e.keyType===t));if(r)return r.fromConfig(e);throw new Error(`Unsupported keyType given in config: ${t}`)}return void 0!==e.auth?.identity?e.auth?.identity:void 0!==e.auth?.ethereum?s0.fromConfig(e):i0.generate()}(n);!function(e,t){const r=P0(e),n=t.encryption?.requireQuantumResistantSignatures;if(n&&!r)throw new uA("Quantum resistant signatures are required, but the configured key type doesn't enable quantum resistance!","SIGNATURE_POLICY_VIOLATION")}(i,n),(e=>{void 0!==e.auth?.privateKey&&(e.auth.privateKey="(redacted)")})(n);const s=r.createChildContainer();s.register(kA,{useValue:i}),s.register(cA,{useValue:n});const o=((e,t)=>{const r=new lE({serverUrl:t.contracts.theGraphUrl,fetch:(e,r)=>{const n=t._timeouts.theGraph.fetchTimeout,i=[AbortSignal.timeout(n)];r?.signal instanceof AbortSignal&&i.push(r.signal);const s=rE(...i);try{return fetch(e,aE(r,{signal:s}))}finally{s.destroy()}},indexTimeout:t._timeouts.theGraph.indexTimeout,indexPollInterval:t._timeouts.theGraph.indexPollInterval});return e.on("contractTransactionConfirmed",(e=>{null!=e.receipt&&r.updateRequiredBlockNumber(e.receipt.blockNumber)})),r})(s.resolve(sD),n);s.register(lE,{useValue:o}),this.id=n.id,this.config=n,this.identity=i,this.theGraphClient=o,this.publisher=s.resolve(B1),this.subscriber=s.resolve(T0.Subscriber),this.resends=s.resolve(T0.Resends),this.node=s.resolve(GX),this.rpcProviderSource=s.resolve(e.RpcProviderSource),this.streamRegistry=s.resolve(EQ),this.streamStorageRegistry=s.resolve(OQ),this.storageNodeRegistry=s.resolve(ID),this.operatorRegistry=s.resolve(UY),this.contractFactory=s.resolve(SD),this.localGroupKeyStore=s.resolve(OZ),this.chainEventPoller=s.resolve(cQ),this.streamIdBuilder=s.resolve(RJ),this.eventEmitter=s.resolve(sD),this.destroySignal=s.resolve(dJ),this.loggerFactory=s.resolve(uD),this.proxyNodeFinder=s.resolve(i2),s.resolve(h4),s.resolve(t2),s.resolve(o4)}async publish(e,t,r,n){const i=await this.publisher.publish(e,t,r,n);return this.eventEmitter.emit("messagePublished",i),Q1(i)}async publishRaw(e,t){await this.node.broadcast(e,t),this.eventEmitter.emit("messagePublished",e)}async updateEncryptionKey(e){if(void 0===e.streamId)throw new Error("streamId required");const t=await this.streamIdBuilder.toStreamID(e.streamId),r=await this.publisher.getGroupKeyQueue(t);if("rotate"===e.distributionMethod)await r.rotate(e.key);else{if("rekey"!==e.distributionMethod)throw new Error(`assertion failed: distribution method ${e.distributionMethod}`);await r.rekey(e.key)}}async addEncryptionKey(e,t){await this.localGroupKeyStore.set(e.id,kE(t),e.data)}async subscribe(e,t){if(!0===e.raw&&void 0!==e.resend)throw new Error("Raw subscriptions are not supported for resend");const r=await this.streamIdBuilder.toStreamPartID(e),n=new Sl,i=new f4(r,e.raw??!1,void 0!==e.erc1271Contract?nb(e.erc1271Contract):void 0,e.delivery??{},n,this.loggerFactory);return void 0!==e.resend&&((e,t,r,n,i,s,o)=>{if(e.pipe((async function*(i){try{const i=await r.resend(e.streamPartId,n1(t),n);e.onBeforeFinally.listen((async()=>{i.end(),await i.return()})),yield*i}catch(r){"NO_STORAGE_NODES"===r.code?o.createLogger("resendSubscription").warn("Skip resend (no storage assigned to stream)",{streamPartId:e.streamPartId,resendOptions:t}):await e.handleError(r)}s.emit("resendCompleted"),yield*i})),i.orderMessages){const t=new $0(e.streamPartId,n,(()=>{}),r,i);e.pipe((async function*(e){setImmediate((()=>{t.addMessages(e)})),yield*t})),e.onBeforeFinally.listen((()=>t.destroy()))}})(i,e.resend,this.resends,(e=>this.streamStorageRegistry.getStorageNodes(e)),this.config,n,this.loggerFactory),await this.subscriber.add(i),void 0!==t&&i.useLegacyOnMessageHandler(t),this.eventEmitter.emit("streamPartSubscribed",void 0),i}async unsubscribe(e){if(e instanceof f4){const t=e;return this.subscriber.remove(t)}{const t=await this.getSubscriptions(e);return Promise.allSettled(t.map((e=>this.subscriber.remove(e))))}}async getSubscriptions(e){const t=void 0!==e?await this.streamIdBuilder.getMatcher(e):()=>!0;return this.subscriber.getSubscriptions().filter((e=>t(e.streamPartId)))}async resend(e,t,r){const n=await this.streamIdBuilder.toStreamPartID(e),i=await this.resends.resend(n,n1(t),(e=>this.streamStorageRegistry.getStorageNodes(e))),s=new d4(i);return void 0!==r&&s.useLegacyOnMessageHandler(r),s}waitForStorage(e,t){const r={interval:this.config._timeouts.storageNode.retryInterval,timeout:this.config._timeouts.storageNode.timeout,count:100};return(async(e,t,r,n)=>{if(!e)throw new uA("waitForStorage requires a Message","INVALID_ARGUMENT");const i=t.messageMatchFn??((e,t)=>yw(e.signature,t.signature)),s=Date.now();let o,a=!1;for(;!a;){const c=Date.now()-s;if(c>t.timeout)throw p4.debug("Timed out waiting for storage to contain message",{expected:e.streamMessage.messageId,lastReceived:o?.map((e=>e.messageId))}),new Error(`timed out after ${c}ms waiting for message`);const u=e=>n.getStorageNodes(e),l=await r.resend(EE(e.streamId,e.streamPartition),{last:t.count},u);o=await cE(l);for(const t of o)if(i(e,Q1(t)))return a=!0,void p4.debug("Found matching message");p4.debug("Retry after delay (matching message not found)",{expected:e.streamMessage.messageId,"last-3":o.slice(-3).map((e=>e.messageId)),delayInMs:t.interval}),await Qv(t.interval)}})(e,P1(r,t),this.resends,this.streamStorageRegistry)}async getStream(e){const t=await this.streamIdBuilder.toStreamID(e);return await this.streamRegistry.getStreamMetadata(t),new y2(t,this)}async createStream(e){const t="object"==typeof e?e:{id:e},r=await this.streamIdBuilder.toStreamID(t.id),n=P1({partitions:1},BY(t,"id"));return await this.streamRegistry.createStream(r,n),new y2(r,this)}async getOrCreateStream(e){try{return await this.getStream(e.id)}catch(t){if("STREAM_NOT_FOUND"===t.code)return this.createStream(e);throw t}}async getStreamMetadata(e){const t=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.getStreamMetadata(t)}async setStreamMetadata(e,t){const r=await this.streamIdBuilder.toStreamID(e);await this.streamRegistry.setStreamMetadata(r,t)}deleteStream(e){return this.streamRegistry.deleteStream(e)}searchStreams(e,t){if(m4.debug("Search for streams",{term:e,permissionFilter:t}),void 0===e&&void 0===t)throw new Error("Requires a search term or a permission filter");const r=this.streamRegistry.searchStreams(e,void 0!==t?(e=>({...e,userId:kE(e.userId)}))(t):void 0);return MW(r,(e=>new y2(e,this)))}getStreamPublishers(e){return this.streamRegistry.getStreamPublishers(e)}getStreamSubscribers(e){return this.streamRegistry.getStreamSubscribers(e)}async hasPermission(e){return this.streamRegistry.hasPermission(await(async(e,t)=>{const r={...e,streamId:await t.toStreamID(e.streamId)};return"userId"in r?{...r,userId:kE(r.userId)}:r})(e,this.streamIdBuilder))}getPermissions(e){return this.streamRegistry.getPermissions(e)}grantPermissions(e,...t){return this.streamRegistry.grantPermissions(e,...t.map(NJ))}revokePermissions(e,...t){return this.streamRegistry.revokePermissions(e,...t.map(NJ))}setPermissions(...e){return this.streamRegistry.setPermissions(...e.map((e=>({...e,assignments:e.assignments.map(NJ)}))))}async isStreamPublisher(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamPublisher(r,kE(t))}async isStreamSubscriber(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamSubscriber(r,kE(t))}async addStreamToStorageNode(e,t,r={wait:!1}){const n=await this.streamIdBuilder.toStreamID(e);await g4(n,nb(t),r,IJ(await this.streamRegistry.getStreamMetadata(n)),this.subscriber,this.streamRegistry,this.streamStorageRegistry,this.loggerFactory,this.config)}async removeStreamFromStorageNode(e,t){return this.streamStorageRegistry.removeStreamFromStorageNode(e,nb(t))}async isStoredStream(e,t){return this.streamStorageRegistry.isStoredStream(e,nb(t))}async getStoredStreams(e){const t=await this.streamStorageRegistry.getStoredStreams(nb(e));for(const e of t.streams)this.streamRegistry.populateMetadataCache(e.id,e.metadata);return{streams:t.streams.map((e=>new y2(e.id,this))),blockNumber:t.blockNumber}}async getStorageNodes(e){return this.streamStorageRegistry.getStorageNodes(e)}setStorageNodeMetadata(e){return this.storageNodeRegistry.setStorageNodeMetadata(e)}async getStorageNodeMetadata(e){return this.storageNodeRegistry.getStorageNodeMetadata(nb(e))}getSigner(){return this.identity.getTransactionSigner(this.rpcProviderSource)}async getUserId(){return await this.identity.getUserId()}getAddress(){return this.getUserId()}getNode(){return this.node}async inspect(e,t){const r=await this.streamIdBuilder.toStreamPartID(t);return this.node.inspect(e,r)}async setProxies(e,t,r,n){const i=await this.streamIdBuilder.toStreamPartID(e);await this.node.setProxies(i,t,r,n)}async setStreamPartitionEntryPoints(e,t){const r=await this.streamIdBuilder.toStreamPartID(e);await this.node.setStreamPartEntryPoints(r,t)}connect(){return this._connect()}_connect=nJ((async()=>{await this.node.startNode()}));destroy(){return this._destroy()}_destroy=nJ((async()=>{this.eventEmitter.removeAllListeners(),this._connect.reset();const e=[this.destroySignal.destroy().then((()=>{})),this.unsubscribe()];await Promise.allSettled(e),await Promise.all(e)}));async getPeerDescriptor(){return JW(await this.node.getPeerDescriptor())}async getNodeId(){return this.node.getNodeId()}async getDiagnosticInfo(){return this.node.getDiagnosticInfo()}getConfig(){return this.config}getTheGraphClient(){return this.theGraphClient}getEthersOverrides(){return nD(this.rpcProviderSource,this.config)}getOperator(e){return new r4(e,this.contractFactory,this.rpcProviderSource,this.chainEventPoller,this.theGraphClient,this.identity,this.destroySignal,this.loggerFactory,(()=>this.getEthersOverrides()))}async findProxyNodes(e,t=1,r=100,n=24){return this.proxyNodeFinder.find(e,t,r,n)}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}},e.Subscription=f4,e._operatorContractUtils=S4,e.convertBytesToStreamMessage=_W,e.convertStreamMessageToBytes=function(e){return xH.toBinary(TW.toProtobuf(e))},e.formStorageNodeAssignmentStreamId=HW,e.getStreamPartitionCount=IJ,e.parseStreamMetadata=CJ,e.peerDescriptorTranslator=WW,window.StreamrClient=window.StreamrClient.StreamrClient}));
71
71
  //# sourceMappingURL=exports-umd.min.js.map