From 7d1badcb3d001629523b4ab39ce3f3e4adfa4639 Mon Sep 17 00:00:00 2001 From: Robert Kiel Date: Thu, 7 Apr 2022 16:01:19 +0200 Subject: [PATCH 1/2] delete correct abortControllers --- src/dialer/dial-request.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/dialer/dial-request.js b/src/dialer/dial-request.js index 810cdfee69..0d97751aae 100644 --- a/src/dialer/dial-request.js +++ b/src/dialer/dial-request.js @@ -80,7 +80,7 @@ class DialRequest { const signal = dialAbortControllers[i].signal conn = await this.dialAction(addr, { ...options, signal: options.signal ? anySignal([signal, options.signal]) : signal }) // Remove the successful AbortController so it is not aborted - dialAbortControllers.splice(i, 1) + dialAbortControllers[i] = undefined } finally { completedDials++ // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it @@ -94,7 +94,11 @@ class DialRequest { return conn })) } finally { - dialAbortControllers.map(c => c.abort()) // success/failure happened, abort everything else + dialAbortControllers.forEach(c => { + if (c !== undefined) { + c.abort() + } + }) // success/failure happened, abort everything else tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer } } From 4ef6b5a0386bc8f7643b9146ccbe632145b39d60 Mon Sep 17 00:00:00 2001 From: Robert Kiel Date: Thu, 7 Apr 2022 16:21:18 +0200 Subject: [PATCH 2/2] add built files --- .gitignore | 2 +- dist/index.min.js | 55 ++ dist/src/address-manager/index.d.ts | 72 +++ dist/src/address-manager/index.d.ts.map | 1 + dist/src/circuit/auto-relay.d.ts | 107 ++++ dist/src/circuit/auto-relay.d.ts.map | 1 + dist/src/circuit/circuit/hop.d.ts | 67 +++ dist/src/circuit/circuit/hop.d.ts.map | 1 + dist/src/circuit/circuit/stop.d.ts | 14 + dist/src/circuit/circuit/stop.d.ts.map | 1 + dist/src/circuit/circuit/stream-handler.d.ts | 58 ++ .../circuit/circuit/stream-handler.d.ts.map | 1 + dist/src/circuit/circuit/utils.d.ts | 10 + dist/src/circuit/circuit/utils.d.ts.map | 1 + dist/src/circuit/constants.d.ts | 7 + dist/src/circuit/constants.d.ts.map | 1 + dist/src/circuit/index.d.ts | 85 +++ dist/src/circuit/index.d.ts.map | 1 + dist/src/circuit/listener.d.ts | 4 + dist/src/circuit/listener.d.ts.map | 1 + dist/src/circuit/multicodec.d.ts | 2 + dist/src/circuit/multicodec.d.ts.map | 1 + dist/src/circuit/protocol/index.d.ts | 173 ++++++ dist/src/circuit/transport.d.ts | 93 +++ dist/src/circuit/transport.d.ts.map | 1 + dist/src/circuit/utils.d.ts | 3 + dist/src/circuit/utils.d.ts.map | 1 + dist/src/config.d.ts | 86 +++ dist/src/config.d.ts.map | 1 + dist/src/connection-manager/auto-dialler.d.ts | 56 ++ .../connection-manager/auto-dialler.d.ts.map | 1 + dist/src/connection-manager/index.d.ts | 193 +++++++ dist/src/connection-manager/index.d.ts.map | 1 + .../connection-manager/latency-monitor.d.ts | 145 +++++ .../latency-monitor.d.ts.map | 1 + .../visibility-change-emitter.d.ts | 67 +++ .../visibility-change-emitter.d.ts.map | 1 + dist/src/constants.d.ts | 11 + dist/src/constants.d.ts.map | 1 + dist/src/content-routing/index.d.ts | 97 ++++ dist/src/content-routing/index.d.ts.map | 1 + dist/src/content-routing/utils.d.ts | 59 ++ dist/src/content-routing/utils.d.ts.map | 1 + dist/src/dht/dht-content-routing.d.ts | 30 + dist/src/dht/dht-content-routing.d.ts.map | 1 + dist/src/dht/dht-peer-routing.d.ts | 29 + dist/src/dht/dht-peer-routing.d.ts.map | 1 + dist/src/dialer/dial-request.d.ts | 55 ++ dist/src/dialer/dial-request.d.ts.map | 1 + dist/src/dialer/index.d.ts | 182 ++++++ dist/src/dialer/index.d.ts.map | 1 + dist/src/errors.d.ts | 66 +++ dist/src/errors.d.ts.map | 1 + dist/src/fetch/constants.d.ts | 2 + dist/src/fetch/constants.d.ts.map | 1 + dist/src/fetch/index.d.ts | 76 +++ dist/src/fetch/index.d.ts.map | 1 + dist/src/fetch/proto.d.ts | 134 +++++ dist/src/get-peer.d.ts | 15 + dist/src/get-peer.d.ts.map | 1 + dist/src/identify/consts.d.ts | 10 + dist/src/identify/consts.d.ts.map | 1 + dist/src/identify/index.d.ts | 120 ++++ dist/src/identify/index.d.ts.map | 1 + dist/src/identify/message.d.ts | 95 ++++ dist/src/index.d.ts | 534 ++++++++++++++++++ dist/src/index.d.ts.map | 1 + dist/src/insecure/plaintext.d.ts | 12 + dist/src/insecure/plaintext.d.ts.map | 1 + dist/src/insecure/proto.d.ts | 128 +++++ dist/src/keychain/cms.d.ts | 41 ++ dist/src/keychain/cms.d.ts.map | 1 + dist/src/keychain/index.d.ts | 158 ++++++ dist/src/keychain/index.d.ts.map | 1 + dist/src/keychain/util.d.ts | 24 + dist/src/keychain/util.d.ts.map | 1 + dist/src/metrics/index.d.ts | 151 +++++ dist/src/metrics/index.d.ts.map | 1 + dist/src/metrics/old-peers.d.ts | 3 + dist/src/metrics/old-peers.d.ts.map | 1 + dist/src/metrics/stats.d.ts | 139 +++++ dist/src/metrics/stats.d.ts.map | 1 + dist/src/metrics/tracked-map.d.ts | 8 + dist/src/metrics/tracked-map.d.ts.map | 1 + dist/src/nat-manager.d.ts | 121 ++++ dist/src/nat-manager.d.ts.map | 1 + dist/src/peer-routing.d.ts | 103 ++++ dist/src/peer-routing.d.ts.map | 1 + dist/src/peer-store/address-book.d.ts | 67 +++ dist/src/peer-store/address-book.d.ts.map | 1 + dist/src/peer-store/index.d.ts | 58 ++ dist/src/peer-store/index.d.ts.map | 1 + dist/src/peer-store/key-book.d.ts | 40 ++ dist/src/peer-store/key-book.d.ts.map | 1 + dist/src/peer-store/metadata-book.d.ts | 58 ++ dist/src/peer-store/metadata-book.d.ts.map | 1 + dist/src/peer-store/pb/peer.d.ts | 222 ++++++++ dist/src/peer-store/proto-book.d.ts | 43 ++ dist/src/peer-store/proto-book.d.ts.map | 1 + dist/src/peer-store/store.d.ts | 73 +++ dist/src/peer-store/store.d.ts.map | 1 + dist/src/peer-store/types.d.ts | 202 +++++++ dist/src/peer-store/types.d.ts.map | 1 + dist/src/ping/constants.d.ts | 5 + dist/src/ping/constants.d.ts.map | 1 + dist/src/ping/index.d.ts | 42 ++ dist/src/ping/index.d.ts.map | 1 + dist/src/ping/util.d.ts | 5 + dist/src/ping/util.d.ts.map | 1 + dist/src/pnet/crypto.d.ts | 8 + dist/src/pnet/crypto.d.ts.map | 1 + dist/src/pnet/errors.d.ts | 6 + dist/src/pnet/errors.d.ts.map | 1 + dist/src/pnet/index.d.ts | 32 ++ dist/src/pnet/index.d.ts.map | 1 + dist/src/pnet/key-generator.d.ts | 14 + dist/src/pnet/key-generator.d.ts.map | 1 + dist/src/pubsub-adapter.d.ts | 22 + dist/src/pubsub-adapter.d.ts.map | 1 + dist/src/record/envelope/envelope.d.ts | 77 +++ dist/src/record/envelope/index.d.ts | 80 +++ dist/src/record/envelope/index.d.ts.map | 1 + dist/src/record/peer-record/consts.d.ts | 4 + dist/src/record/peer-record/consts.d.ts.map | 1 + dist/src/record/peer-record/index.d.ts | 60 ++ dist/src/record/peer-record/index.d.ts.map | 1 + dist/src/record/peer-record/peer-record.d.ts | 133 +++++ dist/src/record/utils.d.ts | 12 + dist/src/record/utils.d.ts.map | 1 + dist/src/registrar.d.ts | 82 +++ dist/src/registrar.d.ts.map | 1 + dist/src/transport-manager.d.ts | 120 ++++ dist/src/transport-manager.d.ts.map | 1 + dist/src/types.d.ts | 90 +++ dist/src/types.d.ts.map | 1 + dist/src/upgrader.d.ts | 157 +++++ dist/src/upgrader.d.ts.map | 1 + src/dialer/dial-request.js | 1 + 138 files changed, 5478 insertions(+), 1 deletion(-) create mode 100644 dist/index.min.js create mode 100644 dist/src/address-manager/index.d.ts create mode 100644 dist/src/address-manager/index.d.ts.map create mode 100644 dist/src/circuit/auto-relay.d.ts create mode 100644 dist/src/circuit/auto-relay.d.ts.map create mode 100644 dist/src/circuit/circuit/hop.d.ts create mode 100644 dist/src/circuit/circuit/hop.d.ts.map create mode 100644 dist/src/circuit/circuit/stop.d.ts create mode 100644 dist/src/circuit/circuit/stop.d.ts.map create mode 100644 dist/src/circuit/circuit/stream-handler.d.ts create mode 100644 dist/src/circuit/circuit/stream-handler.d.ts.map create mode 100644 dist/src/circuit/circuit/utils.d.ts create mode 100644 dist/src/circuit/circuit/utils.d.ts.map create mode 100644 dist/src/circuit/constants.d.ts create mode 100644 dist/src/circuit/constants.d.ts.map create mode 100644 dist/src/circuit/index.d.ts create mode 100644 dist/src/circuit/index.d.ts.map create mode 100644 dist/src/circuit/listener.d.ts create mode 100644 dist/src/circuit/listener.d.ts.map create mode 100644 dist/src/circuit/multicodec.d.ts create mode 100644 dist/src/circuit/multicodec.d.ts.map create mode 100644 dist/src/circuit/protocol/index.d.ts create mode 100644 dist/src/circuit/transport.d.ts create mode 100644 dist/src/circuit/transport.d.ts.map create mode 100644 dist/src/circuit/utils.d.ts create mode 100644 dist/src/circuit/utils.d.ts.map create mode 100644 dist/src/config.d.ts create mode 100644 dist/src/config.d.ts.map create mode 100644 dist/src/connection-manager/auto-dialler.d.ts create mode 100644 dist/src/connection-manager/auto-dialler.d.ts.map create mode 100644 dist/src/connection-manager/index.d.ts create mode 100644 dist/src/connection-manager/index.d.ts.map create mode 100644 dist/src/connection-manager/latency-monitor.d.ts create mode 100644 dist/src/connection-manager/latency-monitor.d.ts.map create mode 100644 dist/src/connection-manager/visibility-change-emitter.d.ts create mode 100644 dist/src/connection-manager/visibility-change-emitter.d.ts.map create mode 100644 dist/src/constants.d.ts create mode 100644 dist/src/constants.d.ts.map create mode 100644 dist/src/content-routing/index.d.ts create mode 100644 dist/src/content-routing/index.d.ts.map create mode 100644 dist/src/content-routing/utils.d.ts create mode 100644 dist/src/content-routing/utils.d.ts.map create mode 100644 dist/src/dht/dht-content-routing.d.ts create mode 100644 dist/src/dht/dht-content-routing.d.ts.map create mode 100644 dist/src/dht/dht-peer-routing.d.ts create mode 100644 dist/src/dht/dht-peer-routing.d.ts.map create mode 100644 dist/src/dialer/dial-request.d.ts create mode 100644 dist/src/dialer/dial-request.d.ts.map create mode 100644 dist/src/dialer/index.d.ts create mode 100644 dist/src/dialer/index.d.ts.map create mode 100644 dist/src/errors.d.ts create mode 100644 dist/src/errors.d.ts.map create mode 100644 dist/src/fetch/constants.d.ts create mode 100644 dist/src/fetch/constants.d.ts.map create mode 100644 dist/src/fetch/index.d.ts create mode 100644 dist/src/fetch/index.d.ts.map create mode 100644 dist/src/fetch/proto.d.ts create mode 100644 dist/src/get-peer.d.ts create mode 100644 dist/src/get-peer.d.ts.map create mode 100644 dist/src/identify/consts.d.ts create mode 100644 dist/src/identify/consts.d.ts.map create mode 100644 dist/src/identify/index.d.ts create mode 100644 dist/src/identify/index.d.ts.map create mode 100644 dist/src/identify/message.d.ts create mode 100644 dist/src/index.d.ts create mode 100644 dist/src/index.d.ts.map create mode 100644 dist/src/insecure/plaintext.d.ts create mode 100644 dist/src/insecure/plaintext.d.ts.map create mode 100644 dist/src/insecure/proto.d.ts create mode 100644 dist/src/keychain/cms.d.ts create mode 100644 dist/src/keychain/cms.d.ts.map create mode 100644 dist/src/keychain/index.d.ts create mode 100644 dist/src/keychain/index.d.ts.map create mode 100644 dist/src/keychain/util.d.ts create mode 100644 dist/src/keychain/util.d.ts.map create mode 100644 dist/src/metrics/index.d.ts create mode 100644 dist/src/metrics/index.d.ts.map create mode 100644 dist/src/metrics/old-peers.d.ts create mode 100644 dist/src/metrics/old-peers.d.ts.map create mode 100644 dist/src/metrics/stats.d.ts create mode 100644 dist/src/metrics/stats.d.ts.map create mode 100644 dist/src/metrics/tracked-map.d.ts create mode 100644 dist/src/metrics/tracked-map.d.ts.map create mode 100644 dist/src/nat-manager.d.ts create mode 100644 dist/src/nat-manager.d.ts.map create mode 100644 dist/src/peer-routing.d.ts create mode 100644 dist/src/peer-routing.d.ts.map create mode 100644 dist/src/peer-store/address-book.d.ts create mode 100644 dist/src/peer-store/address-book.d.ts.map create mode 100644 dist/src/peer-store/index.d.ts create mode 100644 dist/src/peer-store/index.d.ts.map create mode 100644 dist/src/peer-store/key-book.d.ts create mode 100644 dist/src/peer-store/key-book.d.ts.map create mode 100644 dist/src/peer-store/metadata-book.d.ts create mode 100644 dist/src/peer-store/metadata-book.d.ts.map create mode 100644 dist/src/peer-store/pb/peer.d.ts create mode 100644 dist/src/peer-store/proto-book.d.ts create mode 100644 dist/src/peer-store/proto-book.d.ts.map create mode 100644 dist/src/peer-store/store.d.ts create mode 100644 dist/src/peer-store/store.d.ts.map create mode 100644 dist/src/peer-store/types.d.ts create mode 100644 dist/src/peer-store/types.d.ts.map create mode 100644 dist/src/ping/constants.d.ts create mode 100644 dist/src/ping/constants.d.ts.map create mode 100644 dist/src/ping/index.d.ts create mode 100644 dist/src/ping/index.d.ts.map create mode 100644 dist/src/ping/util.d.ts create mode 100644 dist/src/ping/util.d.ts.map create mode 100644 dist/src/pnet/crypto.d.ts create mode 100644 dist/src/pnet/crypto.d.ts.map create mode 100644 dist/src/pnet/errors.d.ts create mode 100644 dist/src/pnet/errors.d.ts.map create mode 100644 dist/src/pnet/index.d.ts create mode 100644 dist/src/pnet/index.d.ts.map create mode 100644 dist/src/pnet/key-generator.d.ts create mode 100644 dist/src/pnet/key-generator.d.ts.map create mode 100644 dist/src/pubsub-adapter.d.ts create mode 100644 dist/src/pubsub-adapter.d.ts.map create mode 100644 dist/src/record/envelope/envelope.d.ts create mode 100644 dist/src/record/envelope/index.d.ts create mode 100644 dist/src/record/envelope/index.d.ts.map create mode 100644 dist/src/record/peer-record/consts.d.ts create mode 100644 dist/src/record/peer-record/consts.d.ts.map create mode 100644 dist/src/record/peer-record/index.d.ts create mode 100644 dist/src/record/peer-record/index.d.ts.map create mode 100644 dist/src/record/peer-record/peer-record.d.ts create mode 100644 dist/src/record/utils.d.ts create mode 100644 dist/src/record/utils.d.ts.map create mode 100644 dist/src/registrar.d.ts create mode 100644 dist/src/registrar.d.ts.map create mode 100644 dist/src/transport-manager.d.ts create mode 100644 dist/src/transport-manager.d.ts.map create mode 100644 dist/src/types.d.ts create mode 100644 dist/src/types.d.ts.map create mode 100644 dist/src/upgrader.d.ts create mode 100644 dist/src/upgrader.d.ts.map diff --git a/.gitignore b/.gitignore index 69f5439f9c..f80f2c67b9 100644 --- a/.gitignore +++ b/.gitignore @@ -37,7 +37,7 @@ build node_modules lib -dist +# dist test/test-data/go-ipfs-repo/LOCK test/test-data/go-ipfs-repo/LOG test/test-data/go-ipfs-repo/LOG.old diff --git a/dist/index.min.js b/dist/index.min.js new file mode 100644 index 0000000000..5de39659a0 --- /dev/null +++ b/dist/index.min.js @@ -0,0 +1,55 @@ +(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2p = factory()}(typeof self !== 'undefined' ? self : this, function () { +var Libp2p=(()=>{var sI=Object.create;var Ya=Object.defineProperty;var oI=Object.getOwnPropertyDescriptor;var aI=Object.getOwnPropertyNames;var cI=Object.getPrototypeOf,uI=Object.prototype.hasOwnProperty;var f0=t=>Ya(t,"__esModule",{value:!0});var d0=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,r)=>(typeof require!="undefined"?require:e)[r]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var Te=(t,e)=>()=>(t&&(e=t(t=0)),e);var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_t=(t,e)=>{f0(t);for(var r in e)Ya(t,r,{get:e[r],enumerable:!0})},lI=(t,e,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of aI(e))!uI.call(t,n)&&n!=="default"&&Ya(t,n,{get:()=>e[n],enumerable:!(r=oI(e,n))||r.enumerable});return t},Lo=t=>lI(f0(Ya(t!=null?sI(cI(t)):{},"default",t&&t.__esModule&&"default"in t?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var dl=b((pq,h0)=>{var ys=1e3,gs=ys*60,ms=gs*60,xi=ms*24,fI=xi*7,dI=xi*365.25;h0.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return hI(t);if(r==="number"&&isFinite(t))return e.long?yI(t):pI(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function hI(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!!e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*dI;case"weeks":case"week":case"w":return r*fI;case"days":case"day":case"d":return r*xi;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ms;case"minutes":case"minute":case"mins":case"min":case"m":return r*gs;case"seconds":case"second":case"secs":case"sec":case"s":return r*ys;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function pI(t){var e=Math.abs(t);return e>=xi?Math.round(t/xi)+"d":e>=ms?Math.round(t/ms)+"h":e>=gs?Math.round(t/gs)+"m":e>=ys?Math.round(t/ys)+"s":t+"ms"}function yI(t){var e=Math.abs(t);return e>=xi?Qa(t,e,xi,"day"):e>=ms?Qa(t,e,ms,"hour"):e>=gs?Qa(t,e,gs,"minute"):e>=ys?Qa(t,e,ys,"second"):t+" ms"}function Qa(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var y0=b((yq,p0)=>{function gI(t){r.debug=r,r.default=r,r.coerce=c,r.disable=s,r.enable=i,r.enabled=o,r.humanize=dl(),r.destroy=u,Object.keys(t).forEach(l=>{r[l]=t[l]}),r.names=[],r.skips=[],r.formatters={};function e(l){let f=0;for(let d=0;d{if(M==="%%")return"%";W++;let ie=r.formatters[re];if(typeof ie=="function"){let z=v[W];M=ie.call(w,z),v.splice(W,1),W--}return M}),r.formatArgs.call(w,v),(w.log||r.log).apply(w,v)}return g.namespace=l,g.useColors=r.useColors(),g.color=r.selectColor(l),g.extend=n,g.destroy=r.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(p!==r.namespaces&&(p=r.namespaces,h=r.enabled(l)),h),set:v=>{d=v}}),typeof r.init=="function"&&r.init(g),g}function n(l,f){let d=r(this.namespace+(typeof f=="undefined"?":":f)+l);return d.log=this.log,d}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),p=d.length;for(f=0;f"-"+f)].join(",");return r.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=r.skips.length;f{ur.formatArgs=vI;ur.save=EI;ur.load=bI;ur.useColors=mI;ur.storage=wI();ur.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ur.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function mI(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function vI(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Xa.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}ur.log=console.debug||console.log||(()=>{});function EI(t){try{t?ur.storage.setItem("debug",t):ur.storage.removeItem("debug")}catch(e){}}function bI(){let t;try{t=ur.storage.getItem("debug")}catch(e){}return!t&&typeof process!="undefined"&&"env"in process&&(t=process.env.DEBUG),t}function wI(){try{return localStorage}catch(t){}}Xa.exports=y0()(ur);var{formatters:_I}=Xa.exports;_I.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var rr=b((gq,hl)=>{"use strict";var vs=typeof Reflect=="object"?Reflect:null,g0=vs&&typeof vs.apply=="function"?vs.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Za;vs&&typeof vs.ownKeys=="function"?Za=vs.ownKeys:Object.getOwnPropertySymbols?Za=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Za=function(e){return Object.getOwnPropertyNames(e)};function SI(t){console&&console.warn&&console.warn(t)}var m0=Number.isNaN||function(e){return e!==e};function ze(){ze.init.call(this)}hl.exports=ze;hl.exports.once=II;ze.EventEmitter=ze;ze.prototype._events=void 0;ze.prototype._eventsCount=0;ze.prototype._maxListeners=void 0;var v0=10;function Ja(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ze,"defaultMaxListeners",{enumerable:!0,get:function(){return v0},set:function(t){if(typeof t!="number"||t<0||m0(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");v0=t}});ze.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ze.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||m0(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function E0(t){return t._maxListeners===void 0?ze.defaultMaxListeners:t._maxListeners}ze.prototype.getMaxListeners=function(){return E0(this)};ze.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")g0(c,this,r);else for(var u=c.length,l=x0(c,u),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,SI(a)}return t}ze.prototype.addListener=function(e,r){return b0(this,e,r,!1)};ze.prototype.on=ze.prototype.addListener;ze.prototype.prependListener=function(e,r){return b0(this,e,r,!0)};function xI(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function w0(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=xI.bind(n);return i.listener=r,n.wrapFn=i,i}ze.prototype.once=function(e,r){return Ja(r),this.on(e,w0(this,e,r)),this};ze.prototype.prependOnceListener=function(e,r){return Ja(r),this.prependListener(e,w0(this,e,r)),this};ze.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ja(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount==0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():AI(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ze.prototype.off=ze.prototype.removeListener;ze.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function _0(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?CI(i):x0(i,i.length)}ze.prototype.listeners=function(e){return _0(this,e,!0)};ze.prototype.rawListeners=function(e){return _0(this,e,!1)};ze.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):S0.call(t,e)};ze.prototype.listenerCount=S0;function S0(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ze.prototype.eventNames=function(){return this._eventsCount>0?Za(this._events):[]};function x0(t,e){for(var r=new Array(e),n=0;n{"use strict";function C0(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function RI(t,e,r){if(!t||typeof t=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof e=="object"&&(r=e,e=""),e&&(r.code=e);try{return C0(t,r)}catch(n){r.message=t.message,r.stack=t.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(t)),C0(new i,r)}}I0.exports=RI});function R0(t,e,r){e=e||[],r=r||0;for(var n=r;t>=OI;)e[r++]=t&255|T0,t/=128;for(;t&NI;)e[r++]=t&255|T0,t>>>=7;return e[r]=t|0,R0.bytes=r-n+1,e}function pl(t,e){var r=0,e=e||0,n=0,i=e,s,o=t.length;do{if(i>=o)throw pl.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=n<28?(s&B0)<=LI);return pl.bytes=i-e,r}var BI,T0,PI,NI,OI,DI,LI,B0,kI,qI,UI,MI,FI,KI,VI,jI,$I,HI,zI,GI,ko,P0=Te(()=>{BI=R0,T0=128,PI=127,NI=~PI,OI=Math.pow(2,31);DI=pl,LI=128,B0=127;kI=Math.pow(2,7),qI=Math.pow(2,14),UI=Math.pow(2,21),MI=Math.pow(2,28),FI=Math.pow(2,35),KI=Math.pow(2,42),VI=Math.pow(2,49),jI=Math.pow(2,56),$I=Math.pow(2,63),HI=function(t){return t{P0();qo=t=>[ko.decode(t),ko.decode.bytes],Es=(t,e,r=0)=>(ko.encode(t,e,r),e),bs=t=>ko.encodingLength(t)});var bq,O0,_n,D0,L0,Un=Te(()=>{bq=new Uint8Array(0),O0=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},D0=t=>new TextEncoder().encode(t),L0=t=>new TextDecoder().decode(t)});var Uo={};_t(Uo,{Digest:()=>ws,create:()=>Mn,decode:()=>yl,equals:()=>gl});var Mn,yl,gl,ws,Ai=Te(()=>{Un();ec();Mn=(t,e)=>{let r=e.byteLength,n=bs(t),i=n+bs(r),s=new Uint8Array(i+r);return Es(t,s,0),Es(r,s,n),s.set(e,i),new ws(t,r,e,s)},yl=t=>{let e=_n(t),[r,n]=qo(e),[i,s]=qo(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new ws(r,i,o,e)},gl=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&O0(t.bytes,e.bytes),ws=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});function WI(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,W=new Uint8Array(q);w!==C;){for(var F=h[w],M=0,re=q-1;(F!==0||M>>0,W[re]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");v=M,w++}for(var ie=q-v;ie!==q&&W[ie]===0;)ie++;for(var z=c.repeat(g);ie>>0,q=new Uint8Array(C);h[g];){var W=r[h.charCodeAt(g)];if(W===255)return;for(var F=0,M=C-1;(W!==0||F>>0,q[M]=W%256>>>0,W=W/256>>>0;if(W!==0)throw new Error("Non-zero carry");w=F,g++}if(h[g]!==" "){for(var re=C-w;re!==C&&q[re]===0;)re++;for(var ie=new Uint8Array(v+(C-re)),z=v;re!==C;)ie[z++]=q[re++];return ie}}}function p(h){var g=d(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:p}}var YI,QI,q0,U0=Te(()=>{YI=WI,QI=YI,q0=QI});var M0,F0,K0,V0,j0,tc,Fn,XI,ZI,pt,Xr=Te(()=>{U0();Un();M0=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F0=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseDecode=n}decode(e){if(typeof e=="string")switch(e[0]){case this.prefix:return this.baseDecode(e.slice(1));default:throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)}else throw Error("Can only multibase decode strings")}or(e){return V0(this,e)}},K0=class{constructor(e){this.decoders=e}or(e){return V0(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},V0=(t,e)=>new K0({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),j0=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new M0(e,r,n),this.decoder=new F0(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},tc=({name:t,prefix:e,encode:r,decode:n})=>new j0(t,e,r,n),Fn=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=q0(r,e);return tc({prefix:t,name:e,encode:n,decode:s=>_n(i(s))})},XI=(t,e,r,n)=>{let i={};for(let l=0;l=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ZI=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<tc({prefix:e,name:t,encode(i){return ZI(i,n,r)},decode(i){return XI(i,n,r,t)}})});var Kn={};_t(Kn,{base58btc:()=>Zr,base58flickr:()=>JI});var Zr,JI,Vn=Te(()=>{Xr();Zr=Fn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),JI=Fn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Ci={};_t(Ci,{base32:()=>_s,base32hex:()=>nT,base32hexpad:()=>sT,base32hexpadupper:()=>oT,base32hexupper:()=>iT,base32pad:()=>tT,base32padupper:()=>rT,base32upper:()=>eT,base32z:()=>aT});var _s,eT,tT,rT,nT,iT,sT,oT,aT,Ii=Te(()=>{Xr();_s=pt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eT=pt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tT=pt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rT=pt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nT=pt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iT=pt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sT=pt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oT=pt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aT=pt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Fo={};_t(Fo,{CID:()=>At});var At,cT,uT,lT,Mo,fT,$0,H0,rc,nc,dT,hT,pT,Ss=Te(()=>{ec();Ai();Vn();Ii();Un();At=class{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:nc,byteLength:nc,code:rc,version:rc,multihash:rc,bytes:rc,_baseCache:nc,asCID:nc})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==Mo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==fT)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return At.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Mn(e,r);return At.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&gl(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return uT(r,i,e||Zr.encoder);default:return lT(r,i,e||_s.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return hT(/^0\.0/,pT),!!(e&&(e[H0]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof At)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new At(r,n,i,s||$0(r,n,i.bytes))}else if(e!=null&&e[H0]===!0){let{version:r,multihash:n,code:i}=e,s=yl(n);return At.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==Mo)throw new Error(`Version 0 CID must use dag-pb (code: ${Mo}) block encoding`);return new At(e,r,n,n.bytes)}case 1:{let i=$0(e,r,n.bytes);return new At(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return At.create(0,Mo,e)}static createV1(e,r){return At.create(1,e,r)}static decode(e){let[r,n]=At.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=At.inspectBytes(e),n=r.size-r.multihashSize,i=_n(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new ws(r.multihashCode,r.digestSize,s,i);return[r.version===0?At.createV0(o):At.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,d]=qo(e.subarray(r));return r+=d,f},i=n(),s=Mo;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),c=n(),u=r+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,i]=cT(e,r),s=At.decode(i);return s._baseCache.set(n,e),s}},cT=(t,e)=>{switch(t[0]){case"Q":{let r=e||Zr;return[Zr.prefix,r.decode(`${Zr.prefix}${t}`)]}case Zr.prefix:{let r=e||Zr;return[Zr.prefix,r.decode(t)]}case _s.prefix:{let r=e||_s;return[_s.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},uT=(t,e,r)=>{let{prefix:n}=r;if(n!==Zr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},lT=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},Mo=112,fT=18,$0=(t,e,r)=>{let n=bs(t),i=n+bs(e),s=new Uint8Array(i+r.byteLength);return Es(t,s,0),Es(e,s,n),s.set(r,i),s},H0=Symbol.for("@ipld/js-cid/CID"),rc={writable:!1,configurable:!1,enumerable:!0},nc={writable:!1,enumerable:!1,configurable:!1},dT="0.0.0-dev",hT=(t,e)=>{if(t.test(dT))console.warn(e);else throw new Error(e)},pT=`CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: + +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`});var ic={};_t(ic,{base36:()=>yT,base36upper:()=>gT});var yT,gT,ml=Te(()=>{Xr();yT=Fn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gT=Fn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var xs={};_t(xs,{base64:()=>mT,base64pad:()=>vT,base64url:()=>ET,base64urlpad:()=>bT});var mT,vT,ET,bT,Ko=Te(()=>{Xr();mT=pt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vT=pt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ET=pt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bT=pt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var sc={};_t(sc,{base16:()=>wT,base16upper:()=>_T});var wT,_T,vl=Te(()=>{Xr();wT=pt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_T=pt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var G0=b((qq,z0)=>{"use strict";z0.exports=ST;function ST(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";var oc=Q0;oc.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var As=new Array(64),W0=new Array(123);for(Ur=0;Ur<64;)W0[As[Ur]=Ur<26?Ur+65:Ur<52?Ur+71:Ur<62?Ur-4:Ur-59|43]=Ur++;var Ur;oc.encode=function(e,r,n){for(var i=null,s=[],o=0,a=0,c;r>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=As[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=As[c|u>>6],s[o++]=As[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=As[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var Y0="invalid encoding";oc.decode=function(e,r,n){for(var i=n,s=0,o,a=0;a1)break;if((c=W0[c])===void 0)throw Error(Y0);switch(s){case 0:o=c,s=1;break;case 1:r[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:r[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:r[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(Y0);return n-i};oc.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var J0=b((Mq,Z0)=>{"use strict";Z0.exports=ac;function ac(){this._listeners={}}ac.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};ac.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";sp.exports=ep(ep);function ep(t){return typeof Float32Array!="undefined"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3]}function s(c,u,l){e[0]=c,u[l]=r[3],u[l+1]=r[2],u[l+2]=r[1],u[l+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],e[0]}function a(c,u){return r[3]=c[u],r[2]=c[u+1],r[1]=c[u+2],r[0]=c[u+3],e[0]}t.readFloatLE=n?o:a,t.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,o)}}t.writeFloatLE=e.bind(null,tp),t.writeFloatBE=e.bind(null,rp);function r(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}t.readFloatLE=r.bind(null,np),t.readFloatBE=r.bind(null,ip)}(),typeof Float64Array!="undefined"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3],u[l+4]=r[4],u[l+5]=r[5],u[l+6]=r[6],u[l+7]=r[7]}function s(c,u,l){e[0]=c,u[l]=r[7],u[l+1]=r[6],u[l+2]=r[5],u[l+3]=r[4],u[l+4]=r[3],u[l+5]=r[2],u[l+6]=r[1],u[l+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],r[4]=c[u+4],r[5]=c[u+5],r[6]=c[u+6],r[7]=c[u+7],e[0]}function a(c,u){return r[7]=c[u],r[6]=c[u+1],r[5]=c[u+2],r[4]=c[u+3],r[3]=c[u+4],r[2]=c[u+5],r[1]=c[u+6],r[0]=c[u+7],e[0]}t.readDoubleLE=n?o:a,t.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var f=Math.floor(Math.log(o)/Math.LN2);f===1024&&(f=1023),l=o*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}t.writeDoubleLE=e.bind(null,tp,0,4),t.writeDoubleBE=e.bind(null,rp,4,0);function r(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,f=u>>>20&2047,d=4294967296*(u&1048575)+c;return f===2047?d?NaN:l*(1/0):f===0?l*5e-324*d:l*Math.pow(2,f-1075)*(d+4503599627370496)}t.readDoubleLE=r.bind(null,np,0,4),t.readDoubleBE=r.bind(null,ip,4,0)}(),t}function tp(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function rp(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function np(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function ip(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var ap=b((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var up=b(cp=>{"use strict";var El=cp;El.length=function(e){for(var r=0,n=0,i=0;i191&&c<224?o[a++]=(c&31)<<6|e[r++]&63:c>239&&c<365?(c=((c&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};El.write=function(e,r,n){for(var i=n,s,o,a=0;a>6|192,r[n++]=s&63|128):(s&64512)==55296&&((o=e.charCodeAt(a+1))&64512)==56320?(s=65536+((s&1023)<<10)+(o&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var fp=b((Vq,lp)=>{"use strict";lp.exports=xT;function xT(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return t(c);o+c>n&&(s=t(n),o=0);var u=e.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var hp=b((jq,dp)=>{"use strict";dp.exports=It;var Vo=$n();function It(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ti=It.zero=new It(0,0);Ti.toNumber=function(){return 0};Ti.zzEncode=Ti.zzDecode=function(){return this};Ti.length=function(){return 1};var AT=It.zeroHash="\0\0\0\0\0\0\0\0";It.fromNumber=function(e){if(e===0)return Ti;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new It(n,i)};It.from=function(e){if(typeof e=="number")return It.fromNumber(e);if(Vo.isString(e))if(Vo.Long)e=Vo.Long.fromString(e);else return It.fromNumber(parseInt(e,10));return e.low||e.high?new It(e.low>>>0,e.high>>>0):Ti};It.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};It.prototype.toLong=function(e){return Vo.Long?new Vo.Long(this.lo|0,this.hi|0,Boolean(e)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(e)}};var jn=String.prototype.charCodeAt;It.fromHash=function(e){return e===AT?Ti:new It((jn.call(e,0)|jn.call(e,1)<<8|jn.call(e,2)<<16|jn.call(e,3)<<24)>>>0,(jn.call(e,4)|jn.call(e,5)<<8|jn.call(e,6)<<16|jn.call(e,7)<<24)>>>0)};It.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};It.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};It.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};It.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var $n=b(bl=>{"use strict";var ue=bl;ue.asPromise=G0();ue.base64=X0();ue.EventEmitter=J0();ue.float=op();ue.inquire=ap();ue.utf8=up();ue.pool=fp();ue.LongBits=hp();ue.isNode=Boolean(typeof globalThis!="undefined"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);ue.global=ue.isNode&&globalThis||typeof window!="undefined"&&window||typeof self!="undefined"&&self||bl;ue.emptyArray=Object.freeze?Object.freeze([]):[];ue.emptyObject=Object.freeze?Object.freeze({}):{};ue.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};ue.isString=function(e){return typeof e=="string"||e instanceof String};ue.isObject=function(e){return e&&typeof e=="object"};ue.isset=ue.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};ue.Buffer=function(){try{var t=ue.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(e){return null}}();ue._Buffer_from=null;ue._Buffer_allocUnsafe=null;ue.newBuffer=function(e){return typeof e=="number"?ue.Buffer?ue._Buffer_allocUnsafe(e):new ue.Array(e):ue.Buffer?ue._Buffer_from(e):typeof Uint8Array=="undefined"?e:new Uint8Array(e)};ue.Array=typeof Uint8Array!="undefined"?Uint8Array:Array;ue.Long=ue.global.dcodeIO&&ue.global.dcodeIO.Long||ue.global.Long||ue.inquire("long");ue.key2Re=/^true|false|0|1$/;ue.key32Re=/^-?(?:0|[1-9][0-9]*)$/;ue.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;ue.longToHash=function(e){return e?ue.LongBits.from(e).toHash():ue.LongBits.zeroHash};ue.longFromHash=function(e,r){var n=ue.LongBits.fromHash(e);return ue.Long?ue.Long.fromBits(n.lo,n.hi,r):n.toNumber(Boolean(r))};function pp(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};ue.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";Ep.exports=De;var vr=$n(),wl,cc=vr.LongBits,gp=vr.base64,mp=vr.utf8;function jo(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function _l(){}function CT(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function De(){this.len=0,this.head=new jo(_l,0,0),this.tail=this.head,this.states=null}var vp=function(){return vr.Buffer?function(){return(De.create=function(){return new wl})()}:function(){return new De}};De.create=vp();De.alloc=function(e){return new vr.Array(e)};vr.Array!==Array&&(De.alloc=vr.pool(De.alloc,vr.Array.prototype.subarray));De.prototype._push=function(e,r,n){return this.tail=this.tail.next=new jo(e,r,n),this.len+=r,this};function Sl(t,e,r){e[r]=t&255}function IT(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function xl(t,e){this.len=t,this.next=void 0,this.val=e}xl.prototype=Object.create(jo.prototype);xl.prototype.fn=IT;De.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new xl((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};De.prototype.int32=function(e){return e<0?this._push(Al,10,cc.fromNumber(e)):this.uint32(e)};De.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Al(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}De.prototype.uint64=function(e){var r=cc.from(e);return this._push(Al,r.length(),r)};De.prototype.int64=De.prototype.uint64;De.prototype.sint64=function(e){var r=cc.from(e).zzEncode();return this._push(Al,r.length(),r)};De.prototype.bool=function(e){return this._push(Sl,1,e?1:0)};function Cl(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}De.prototype.fixed32=function(e){return this._push(Cl,4,e>>>0)};De.prototype.sfixed32=De.prototype.fixed32;De.prototype.fixed64=function(e){var r=cc.from(e);return this._push(Cl,4,r.lo)._push(Cl,4,r.hi)};De.prototype.sfixed64=De.prototype.fixed64;De.prototype.float=function(e){return this._push(vr.float.writeFloatLE,4,e)};De.prototype.double=function(e){return this._push(vr.float.writeDoubleLE,8,e)};var TT=vr.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(Sl,1,0);if(vr.isString(e)){var n=De.alloc(r=gp.length(e));gp.decode(e,n,0),e=n}return this.uint32(r)._push(TT,r,e)};De.prototype.string=function(e){var r=mp.length(e);return r?this.uint32(r)._push(mp.write,r,e):this._push(Sl,1,0)};De.prototype.fork=function(){return this.states=new CT(this),this.head=this.tail=new jo(_l,0,0),this.len=0,this};De.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new jo(_l,0,0),this.len=0),this};De.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};De.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};De._configure=function(t){wl=t,De.create=vp(),wl._configure()}});var _p=b((zq,wp)=>{"use strict";wp.exports=Jr;var bp=Il();(Jr.prototype=Object.create(bp.prototype)).constructor=Jr;var Hn=$n();function Jr(){bp.call(this)}Jr._configure=function(){Jr.alloc=Hn._Buffer_allocUnsafe,Jr.writeBytesBuffer=Hn.Buffer&&Hn.Buffer.prototype instanceof Uint8Array&&Hn.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Jr.writeBytesBuffer,r,e),this};function RT(t,e,r){t.length<40?Hn.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Jr.prototype.string=function(e){var r=Hn.Buffer.byteLength(e);return this.uint32(r),r&&this._push(RT,r,e),this};Jr._configure()});var Bl=b((Gq,Ip)=>{"use strict";Ip.exports=mt;var en=$n(),Tl,Sp=en.LongBits,BT=en.utf8;function Mr(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function mt(t){this.buf=t,this.pos=0,this.len=t.length}var xp=typeof Uint8Array!="undefined"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new mt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new mt(e);throw Error("illegal buffer")},Ap=function(){return en.Buffer?function(r){return(mt.create=function(i){return en.Buffer.isBuffer(i)?new Tl(i):xp(i)})(r)}:xp};mt.create=Ap();mt.prototype._slice=en.Array.prototype.subarray||en.Array.prototype.slice;mt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Mr(this,10);return e}}();mt.prototype.int32=function(){return this.uint32()|0};mt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Rl(){var t=new Sp(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Mr(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Mr(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}mt.prototype.bool=function(){return this.uint32()!==0};function uc(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}mt.prototype.fixed32=function(){if(this.pos+4>this.len)throw Mr(this,4);return uc(this.buf,this.pos+=4)};mt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Mr(this,4);return uc(this.buf,this.pos+=4)|0};function Cp(){if(this.pos+8>this.len)throw Mr(this,8);return new Sp(uc(this.buf,this.pos+=4),uc(this.buf,this.pos+=4))}mt.prototype.float=function(){if(this.pos+4>this.len)throw Mr(this,4);var e=en.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};mt.prototype.double=function(){if(this.pos+8>this.len)throw Mr(this,4);var e=en.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};mt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Mr(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};mt.prototype.string=function(){var e=this.bytes();return BT.read(e,0,e.length)};mt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while(this.buf[this.pos++]&128);return this};mt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!=4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};mt._configure=function(t){Tl=t,mt.create=Ap(),Tl._configure();var e=en.Long?"toLong":"toNumber";en.merge(mt.prototype,{int64:function(){return Rl.call(this)[e](!1)},uint64:function(){return Rl.call(this)[e](!0)},sint64:function(){return Rl.call(this).zzDecode()[e](!1)},fixed64:function(){return Cp.call(this)[e](!0)},sfixed64:function(){return Cp.call(this)[e](!1)}})}});var Pp=b((Wq,Bp)=>{"use strict";Bp.exports=Ri;var Tp=Bl();(Ri.prototype=Object.create(Tp.prototype)).constructor=Ri;var Rp=$n();function Ri(t){Tp.call(this,t)}Ri._configure=function(){Rp.Buffer&&(Ri.prototype._slice=Rp.Buffer.prototype.slice)};Ri.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ri._configure()});var Op=b((Yq,Np)=>{"use strict";Np.exports=$o;var Pl=$n();($o.prototype=Object.create(Pl.EventEmitter.prototype)).constructor=$o;function $o(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");Pl.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(r)}$o.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return Pl.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return o.emit("error",c,e),s(c);if(u===null){o.end(!0);return}if(!(u instanceof n))try{u=n[o.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return o.emit("error",l,e),s(l)}return o.emit("data",u,e),s(null,u)})}catch(a){o.emit("error",a,e),setTimeout(function(){s(a)},0);return}};$o.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Lp=b(Dp=>{"use strict";var PT=Dp;PT.Service=Op()});var qp=b((Xq,kp)=>{"use strict";kp.exports={}});var Fp=b(Mp=>{"use strict";var nr=Mp;nr.build="minimal";nr.Writer=Il();nr.BufferWriter=_p();nr.Reader=Bl();nr.BufferReader=Pp();nr.util=$n();nr.rpc=Lp();nr.roots=qp();nr.configure=Up;function Up(){nr.util._configure(),nr.Writer._configure(nr.BufferWriter),nr.Reader._configure(nr.BufferReader)}Up()});var Sn=b((Jq,Kp)=>{"use strict";Kp.exports=Fp()});var fc=b((eU,jp)=>{"use strict";var Bi=Sn(),lc=Bi.Reader,Vp=Bi.Writer,Mt=Bi.util,Er=Bi.roots["libp2p-crypto-keys"]||(Bi.roots["libp2p-crypto-keys"]={});Er.KeyType=function(){var t={},e=Object.create(t);return e[t[0]="RSA"]=0,e[t[1]="Ed25519"]=1,e[t[2]="Secp256k1"]=2,e}();Er.PublicKey=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.Type=r.int32();break;case 2:s.Data=r.bytes();break;default:r.skipType(o&7);break}}if(!s.hasOwnProperty("Type"))throw Mt.ProtocolError("missing required 'Type'",{instance:s});if(!s.hasOwnProperty("Data"))throw Mt.ProtocolError("missing required 'Data'",{instance:s});return s},t.fromObject=function(r){if(r instanceof Er.PublicKey)return r;var n=new Er.PublicKey;switch(r.Type){case"RSA":case 0:n.Type=0;break;case"Ed25519":case 1:n.Type=1;break;case"Secp256k1":case 2:n.Type=2;break}return r.Data!=null&&(typeof r.Data=="string"?Mt.base64.decode(r.Data,n.Data=Mt.newBuffer(Mt.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.Type=n.enums===String?"RSA":0,n.bytes===String?i.Data="":(i.Data=[],n.bytes!==Array&&(i.Data=Mt.newBuffer(i.Data)))),r.Type!=null&&r.hasOwnProperty("Type")&&(i.Type=n.enums===String?Er.KeyType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(i.Data=n.bytes===String?Mt.base64.encode(r.Data,0,r.Data.length):n.bytes===Array?Array.prototype.slice.call(r.Data):r.Data),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Bi.util.toJSONOptions)},t}();Er.PrivateKey=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.Type=r.int32();break;case 2:s.Data=r.bytes();break;default:r.skipType(o&7);break}}if(!s.hasOwnProperty("Type"))throw Mt.ProtocolError("missing required 'Type'",{instance:s});if(!s.hasOwnProperty("Data"))throw Mt.ProtocolError("missing required 'Data'",{instance:s});return s},t.fromObject=function(r){if(r instanceof Er.PrivateKey)return r;var n=new Er.PrivateKey;switch(r.Type){case"RSA":case 0:n.Type=0;break;case"Ed25519":case 1:n.Type=1;break;case"Secp256k1":case 2:n.Type=2;break}return r.Data!=null&&(typeof r.Data=="string"?Mt.base64.decode(r.Data,n.Data=Mt.newBuffer(Mt.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.Type=n.enums===String?"RSA":0,n.bytes===String?i.Data="":(i.Data=[],n.bytes!==Array&&(i.Data=Mt.newBuffer(i.Data)))),r.Type!=null&&r.hasOwnProperty("Type")&&(i.Type=n.enums===String?Er.KeyType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(i.Data=n.bytes===String?Mt.base64.encode(r.Data,0,r.Data.length):n.bytes===Array?Array.prototype.slice.call(r.Data):r.Data),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Bi.util.toJSONOptions)},t}();jp.exports=Er});var _e=b((tU,$p)=>{$p.exports={options:{usePureJavaScript:!1}}});var Gp=b((rU,zp)=>{var Nl={};zp.exports=Nl;var Hp={};Nl.encode=function(t,e,r){if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');if(r!==void 0&&typeof r!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(t instanceof Uint8Array))n=NT(t,e);else{var i=0,s=e.length,o=e.charAt(0),a=[0];for(i=0;i0;)a.push(u%s),u=u/s|0}for(i=0;t[i]===0&&i=0;--i)n+=e[a[i]]}if(r){var l=new RegExp(".{1,"+r+"}","g");n=n.match(l).join(`\r +`)}return n};Nl.decode=function(t,e){if(typeof t!="string")throw new TypeError('"input" must be a string.');if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');var r=Hp[e];if(!r){r=Hp[e]=[];for(var n=0;n>=8;for(;u>0;)o.push(u&255),u>>=8}for(var l=0;t[l]===s&&l0;)s.push(a%n),a=a/n|0}var c="";for(r=0;t.at(r)===0&&r=0;--r)c+=e[s[r]];return c}});var Qe=b((nU,Xp)=>{var Wp=_e(),Yp=Gp(),I=Xp.exports=Wp.util=Wp.util||{};(function(){if(typeof process!="undefined"&&process.nextTick&&!process.browser){I.nextTick=process.nextTick,typeof setImmediate=="function"?I.setImmediate=setImmediate:I.setImmediate=I.nextTick;return}if(typeof setImmediate=="function"){I.setImmediate=function(){return setImmediate.apply(void 0,arguments)},I.nextTick=function(a){return setImmediate(a)};return}if(I.setImmediate=function(a){setTimeout(a,0)},typeof window!="undefined"&&typeof window.postMessage=="function"){let a=function(c){if(c.source===window&&c.data===t){c.stopPropagation();var u=e.slice();e.length=0,u.forEach(function(l){l()})}};var o=a,t="forge.setImmediate",e=[];I.setImmediate=function(c){e.push(c),e.length===1&&window.postMessage(t,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver!="undefined"){var r=Date.now(),n=!0,i=document.createElement("div"),e=[];new MutationObserver(function(){var c=e.slice();e.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var s=I.setImmediate;I.setImmediate=function(c){Date.now()-r>15?(r=Date.now(),s(c)):(e.push(c),e.length===1&&i.setAttribute("a",n=!n))}}I.nextTick=I.setImmediate})();I.isNodejs=typeof process!="undefined"&&process.versions&&process.versions.node;I.globalScope=function(){return I.isNodejs?globalThis:typeof self=="undefined"?window:self}();I.isArray=Array.isArray||function(t){return Object.prototype.toString.call(t)==="[object Array]"};I.isArrayBuffer=function(t){return typeof ArrayBuffer!="undefined"&&t instanceof ArrayBuffer};I.isArrayBufferView=function(t){return t&&I.isArrayBuffer(t.buffer)&&t.byteLength!==void 0};function Ho(t){if(!(t===8||t===16||t===24||t===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+t)}I.ByteBuffer=Ol;function Ol(t){if(this.data="",this.read=0,typeof t=="string")this.data=t;else if(I.isArrayBuffer(t)||I.isArrayBufferView(t))if(typeof Buffer!="undefined"&&t instanceof Buffer)this.data=t.toString("binary");else{var e=new Uint8Array(t);try{this.data=String.fromCharCode.apply(null,e)}catch(n){for(var r=0;rOT&&(this.data.substr(0,1),this._constructedStringLength=0)};I.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};I.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};I.ByteStringBuffer.prototype.putByte=function(t){return this.putBytes(String.fromCharCode(t))};I.ByteStringBuffer.prototype.fillWithByte=function(t,e){t=String.fromCharCode(t);for(var r=this.data;e>0;)e&1&&(r+=t),e>>>=1,e>0&&(t+=t);return this.data=r,this._optimizeConstructedString(e),this};I.ByteStringBuffer.prototype.putBytes=function(t){return this.data+=t,this._optimizeConstructedString(t.length),this};I.ByteStringBuffer.prototype.putString=function(t){return this.putBytes(I.encodeUtf8(t))};I.ByteStringBuffer.prototype.putInt16=function(t){return this.putBytes(String.fromCharCode(t>>8&255)+String.fromCharCode(t&255))};I.ByteStringBuffer.prototype.putInt24=function(t){return this.putBytes(String.fromCharCode(t>>16&255)+String.fromCharCode(t>>8&255)+String.fromCharCode(t&255))};I.ByteStringBuffer.prototype.putInt32=function(t){return this.putBytes(String.fromCharCode(t>>24&255)+String.fromCharCode(t>>16&255)+String.fromCharCode(t>>8&255)+String.fromCharCode(t&255))};I.ByteStringBuffer.prototype.putInt16Le=function(t){return this.putBytes(String.fromCharCode(t&255)+String.fromCharCode(t>>8&255))};I.ByteStringBuffer.prototype.putInt24Le=function(t){return this.putBytes(String.fromCharCode(t&255)+String.fromCharCode(t>>8&255)+String.fromCharCode(t>>16&255))};I.ByteStringBuffer.prototype.putInt32Le=function(t){return this.putBytes(String.fromCharCode(t&255)+String.fromCharCode(t>>8&255)+String.fromCharCode(t>>16&255)+String.fromCharCode(t>>24&255))};I.ByteStringBuffer.prototype.putInt=function(t,e){Ho(e);var r="";do e-=8,r+=String.fromCharCode(t>>e&255);while(e>0);return this.putBytes(r)};I.ByteStringBuffer.prototype.putSignedInt=function(t,e){return t<0&&(t+=2<0);return e};I.ByteStringBuffer.prototype.getSignedInt=function(t){var e=this.getInt(t),r=2<=r&&(e-=r<<1),e};I.ByteStringBuffer.prototype.getBytes=function(t){var e;return t?(t=Math.min(this.length(),t),e=this.data.slice(this.read,this.read+t),this.read+=t):t===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};I.ByteStringBuffer.prototype.bytes=function(t){return typeof t=="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+t)};I.ByteStringBuffer.prototype.at=function(t){return this.data.charCodeAt(this.read+t)};I.ByteStringBuffer.prototype.setAt=function(t,e){return this.data=this.data.substr(0,this.read+t)+String.fromCharCode(e)+this.data.substr(this.read+t+1),this};I.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};I.ByteStringBuffer.prototype.copy=function(){var t=I.createBuffer(this.data);return t.read=this.read,t};I.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};I.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};I.ByteStringBuffer.prototype.truncate=function(t){var e=Math.max(0,this.length()-t);return this.data=this.data.substr(this.read,e),this.read=0,this};I.ByteStringBuffer.prototype.toHex=function(){for(var t="",e=this.read;e=t)return this;e=Math.max(e||this.growSize,t);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+e);return n.set(r),this.data=new DataView(n.buffer),this};I.DataBuffer.prototype.putByte=function(t){return this.accommodate(1),this.data.setUint8(this.write++,t),this};I.DataBuffer.prototype.fillWithByte=function(t,e){this.accommodate(e);for(var r=0;r>8&65535),this.data.setInt8(this.write,t>>16&255),this.write+=3,this};I.DataBuffer.prototype.putInt32=function(t){return this.accommodate(4),this.data.setInt32(this.write,t),this.write+=4,this};I.DataBuffer.prototype.putInt16Le=function(t){return this.accommodate(2),this.data.setInt16(this.write,t,!0),this.write+=2,this};I.DataBuffer.prototype.putInt24Le=function(t){return this.accommodate(3),this.data.setInt8(this.write,t>>16&255),this.data.setInt16(this.write,t>>8&65535,!0),this.write+=3,this};I.DataBuffer.prototype.putInt32Le=function(t){return this.accommodate(4),this.data.setInt32(this.write,t,!0),this.write+=4,this};I.DataBuffer.prototype.putInt=function(t,e){Ho(e),this.accommodate(e/8);do e-=8,this.data.setInt8(this.write++,t>>e&255);while(e>0);return this};I.DataBuffer.prototype.putSignedInt=function(t,e){return Ho(e),this.accommodate(e/8),t<0&&(t+=2<0);return e};I.DataBuffer.prototype.getSignedInt=function(t){var e=this.getInt(t),r=2<=r&&(e-=r<<1),e};I.DataBuffer.prototype.getBytes=function(t){var e;return t?(t=Math.min(this.length(),t),e=this.data.slice(this.read,this.read+t),this.read+=t):t===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};I.DataBuffer.prototype.bytes=function(t){return typeof t=="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+t)};I.DataBuffer.prototype.at=function(t){return this.data.getUint8(this.read+t)};I.DataBuffer.prototype.setAt=function(t,e){return this.data.setUint8(t,e),this};I.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};I.DataBuffer.prototype.copy=function(){return new I.DataBuffer(this)};I.DataBuffer.prototype.compact=function(){if(this.read>0){var t=new Uint8Array(this.data.buffer,this.read),e=new Uint8Array(t.byteLength);e.set(t),this.data=new DataView(e),this.write-=this.read,this.read=0}return this};I.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};I.DataBuffer.prototype.truncate=function(t){return this.write=Math.max(0,this.length()-t),this.read=Math.min(this.read,this.write),this};I.DataBuffer.prototype.toHex=function(){for(var t="",e=this.read;e0;)e&1&&(r+=t),e>>>=1,e>0&&(t+=t);return r};I.xorBytes=function(t,e,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=t.charCodeAt(o)^e.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s,n};I.hexToBytes=function(t){var e="",r=0;for(t.length&!0&&(r=1,e+=String.fromCharCode(parseInt(t[0],16)));r>24&255)+String.fromCharCode(t>>16&255)+String.fromCharCode(t>>8&255)+String.fromCharCode(t&255)};var zn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Gn=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Qp="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";I.encode64=function(t,e){for(var r="",n="",i,s,o,a=0;a>2),r+=zn.charAt((i&3)<<4|s>>4),isNaN(s)?r+="==":(r+=zn.charAt((s&15)<<2|o>>6),r+=isNaN(o)?"=":zn.charAt(o&63)),e&&r.length>e&&(n+=r.substr(0,e)+`\r +`,r=r.substr(e));return n+=r,n};I.decode64=function(t){t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var e="",r,n,i,s,o=0;o>4),i!==64&&(e+=String.fromCharCode((n&15)<<4|i>>2),s!==64&&(e+=String.fromCharCode((i&3)<<6|s)));return e};I.encodeUtf8=function(t){return unescape(encodeURIComponent(t))};I.decodeUtf8=function(t){return decodeURIComponent(escape(t))};I.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Yp.encode,decode:Yp.decode}};I.binary.raw.encode=function(t){return String.fromCharCode.apply(null,t)};I.binary.raw.decode=function(t,e,r){var n=e;n||(n=new Uint8Array(t.length)),r=r||0;for(var i=r,s=0;s>2),r+=zn.charAt((i&3)<<4|s>>4),isNaN(s)?r+="==":(r+=zn.charAt((s&15)<<2|o>>6),r+=isNaN(o)?"=":zn.charAt(o&63)),e&&r.length>e&&(n+=r.substr(0,e)+`\r +`,r=r.substr(e));return n+=r,n};I.binary.base64.decode=function(t,e,r){var n=e;n||(n=new Uint8Array(Math.ceil(t.length/4)*3)),t=t.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var i,s,o,a,c=0,u=r;c>4,o!==64&&(n[u++]=(s&15)<<4|o>>2,a!==64&&(n[u++]=(o&3)<<6|a));return e?u-r:n.subarray(0,u)};I.binary.base58.encode=function(t,e){return I.binary.baseN.encode(t,Qp,e)};I.binary.base58.decode=function(t,e){return I.binary.baseN.decode(t,Qp,e)};I.text={utf8:{},utf16:{}};I.text.utf8.encode=function(t,e,r){t=I.encodeUtf8(t);var n=e;n||(n=new Uint8Array(t.length)),r=r||0;for(var i=r,s=0;s0&&s.push(n),o=e.lastIndex;var a=r[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(t.substring(o)),s.join("")};I.formatNumber=function(t,e,r,n){var i=t,s=isNaN(e=Math.abs(e))?2:e,o=r===void 0?",":r,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(s?o+Math.abs(i-u).toFixed(s).slice(2):"")};I.formatSize=function(t){return t>=1073741824?t=I.formatNumber(t/1073741824,2,".","")+" GiB":t>=1048576?t=I.formatNumber(t/1048576,2,".","")+" MiB":t>=1024?t=I.formatNumber(t/1024,0)+" KiB":t=I.formatNumber(t,0)+" bytes",t};I.bytesFromIP=function(t){return t.indexOf(".")!==-1?I.bytesFromIPv4(t):t.indexOf(":")!==-1?I.bytesFromIPv6(t):null};I.bytesFromIPv4=function(t){if(t=t.split("."),t.length!==4)return null;for(var e=I.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1))}e.push(s)}if(r.length>0){var c=r[n];c.end-c.start>0&&(e.splice(c.start,c.end-c.start+1,""),c.start===0&&e.unshift(""),c.end===7&&e.push(""))}return e.join(":")};I.estimateCores=function(t,e){if(typeof t=="function"&&(e=t,t={}),t=t||{},"cores"in I&&!t.update)return e(null,I.cores);if(typeof navigator!="undefined"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return I.cores=navigator.hardwareConcurrency,e(null,I.cores);if(typeof Worker=="undefined")return I.cores=1,e(null,I.cores);if(typeof Blob=="undefined")return I.cores=2,e(null,I.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(o){for(var a=Date.now(),c=a+4;Date.now()p.st&&l.stl.st&&p.st{var zo=_e();zo.pki=zo.pki||{};var kl=Zp.exports=zo.pki.oids=zo.oids=zo.oids||{};function G(t,e){kl[t]=e,kl[e]=t}function Ke(t,e){kl[t]=e}G("1.2.840.113549.1.1.1","rsaEncryption");G("1.2.840.113549.1.1.4","md5WithRSAEncryption");G("1.2.840.113549.1.1.5","sha1WithRSAEncryption");G("1.2.840.113549.1.1.7","RSAES-OAEP");G("1.2.840.113549.1.1.8","mgf1");G("1.2.840.113549.1.1.9","pSpecified");G("1.2.840.113549.1.1.10","RSASSA-PSS");G("1.2.840.113549.1.1.11","sha256WithRSAEncryption");G("1.2.840.113549.1.1.12","sha384WithRSAEncryption");G("1.2.840.113549.1.1.13","sha512WithRSAEncryption");G("1.3.101.112","EdDSA25519");G("1.2.840.10040.4.3","dsa-with-sha1");G("1.3.14.3.2.7","desCBC");G("1.3.14.3.2.26","sha1");G("1.3.14.3.2.29","sha1WithRSASignature");G("2.16.840.1.101.3.4.2.1","sha256");G("2.16.840.1.101.3.4.2.2","sha384");G("2.16.840.1.101.3.4.2.3","sha512");G("2.16.840.1.101.3.4.2.4","sha224");G("2.16.840.1.101.3.4.2.5","sha512-224");G("2.16.840.1.101.3.4.2.6","sha512-256");G("1.2.840.113549.2.2","md2");G("1.2.840.113549.2.5","md5");G("1.2.840.113549.1.7.1","data");G("1.2.840.113549.1.7.2","signedData");G("1.2.840.113549.1.7.3","envelopedData");G("1.2.840.113549.1.7.4","signedAndEnvelopedData");G("1.2.840.113549.1.7.5","digestedData");G("1.2.840.113549.1.7.6","encryptedData");G("1.2.840.113549.1.9.1","emailAddress");G("1.2.840.113549.1.9.2","unstructuredName");G("1.2.840.113549.1.9.3","contentType");G("1.2.840.113549.1.9.4","messageDigest");G("1.2.840.113549.1.9.5","signingTime");G("1.2.840.113549.1.9.6","counterSignature");G("1.2.840.113549.1.9.7","challengePassword");G("1.2.840.113549.1.9.8","unstructuredAddress");G("1.2.840.113549.1.9.14","extensionRequest");G("1.2.840.113549.1.9.20","friendlyName");G("1.2.840.113549.1.9.21","localKeyId");G("1.2.840.113549.1.9.22.1","x509Certificate");G("1.2.840.113549.1.12.10.1.1","keyBag");G("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");G("1.2.840.113549.1.12.10.1.3","certBag");G("1.2.840.113549.1.12.10.1.4","crlBag");G("1.2.840.113549.1.12.10.1.5","secretBag");G("1.2.840.113549.1.12.10.1.6","safeContentsBag");G("1.2.840.113549.1.5.13","pkcs5PBES2");G("1.2.840.113549.1.5.12","pkcs5PBKDF2");G("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");G("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");G("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");G("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");G("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");G("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");G("1.2.840.113549.2.7","hmacWithSHA1");G("1.2.840.113549.2.8","hmacWithSHA224");G("1.2.840.113549.2.9","hmacWithSHA256");G("1.2.840.113549.2.10","hmacWithSHA384");G("1.2.840.113549.2.11","hmacWithSHA512");G("1.2.840.113549.3.7","des-EDE3-CBC");G("2.16.840.1.101.3.4.1.2","aes128-CBC");G("2.16.840.1.101.3.4.1.22","aes192-CBC");G("2.16.840.1.101.3.4.1.42","aes256-CBC");G("2.5.4.3","commonName");G("2.5.4.4","surname");G("2.5.4.5","serialNumber");G("2.5.4.6","countryName");G("2.5.4.7","localityName");G("2.5.4.8","stateOrProvinceName");G("2.5.4.9","streetAddress");G("2.5.4.10","organizationName");G("2.5.4.11","organizationalUnitName");G("2.5.4.12","title");G("2.5.4.13","description");G("2.5.4.15","businessCategory");G("2.5.4.17","postalCode");G("2.5.4.42","givenName");G("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");G("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");G("2.16.840.1.113730.1.1","nsCertType");G("2.16.840.1.113730.1.13","nsComment");Ke("2.5.29.1","authorityKeyIdentifier");Ke("2.5.29.2","keyAttributes");Ke("2.5.29.3","certificatePolicies");Ke("2.5.29.4","keyUsageRestriction");Ke("2.5.29.5","policyMapping");Ke("2.5.29.6","subtreesConstraint");Ke("2.5.29.7","subjectAltName");Ke("2.5.29.8","issuerAltName");Ke("2.5.29.9","subjectDirectoryAttributes");Ke("2.5.29.10","basicConstraints");Ke("2.5.29.11","nameConstraints");Ke("2.5.29.12","policyConstraints");Ke("2.5.29.13","basicConstraints");G("2.5.29.14","subjectKeyIdentifier");G("2.5.29.15","keyUsage");Ke("2.5.29.16","privateKeyUsagePeriod");G("2.5.29.17","subjectAltName");G("2.5.29.18","issuerAltName");G("2.5.29.19","basicConstraints");Ke("2.5.29.20","cRLNumber");Ke("2.5.29.21","cRLReason");Ke("2.5.29.22","expirationDate");Ke("2.5.29.23","instructionCode");Ke("2.5.29.24","invalidityDate");Ke("2.5.29.25","cRLDistributionPoints");Ke("2.5.29.26","issuingDistributionPoint");Ke("2.5.29.27","deltaCRLIndicator");Ke("2.5.29.28","issuingDistributionPoint");Ke("2.5.29.29","certificateIssuer");Ke("2.5.29.30","nameConstraints");G("2.5.29.31","cRLDistributionPoints");G("2.5.29.32","certificatePolicies");Ke("2.5.29.33","policyMappings");Ke("2.5.29.34","policyConstraints");G("2.5.29.35","authorityKeyIdentifier");Ke("2.5.29.36","policyConstraints");G("2.5.29.37","extKeyUsage");Ke("2.5.29.46","freshestCRL");Ke("2.5.29.54","inhibitAnyPolicy");G("1.3.6.1.4.1.11129.2.4.2","timestampList");G("1.3.6.1.5.5.7.1.1","authorityInfoAccess");G("1.3.6.1.5.5.7.3.1","serverAuth");G("1.3.6.1.5.5.7.3.2","clientAuth");G("1.3.6.1.5.5.7.3.3","codeSigning");G("1.3.6.1.5.5.7.3.4","emailProtection");G("1.3.6.1.5.5.7.3.8","timeStamping")});var Wn=b((sU,ey)=>{var et=_e();Qe();Cs();var Z=ey.exports=et.asn1=et.asn1||{};Z.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};Z.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};Z.create=function(t,e,r,n,i){if(et.util.isArray(n)){for(var s=[],o=0;oe){var n=new Error("Too few bytes to parse DER.");throw n.available=t.length(),n.remaining=e,n.requested=r,n}}var MT=function(t,e){var r=t.getByte();if(e--,r!==128){var n,i=r&128;if(!i)n=r;else{var s=r&127;Go(t,e,s),n=t.getInt(s<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};Z.fromDer=function(t,e){e===void 0&&(e={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof e=="boolean"&&(e={strict:e,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in e||(e.strict=!0),"parseAllBytes"in e||(e.parseAllBytes=!0),"decodeBitStrings"in e||(e.decodeBitStrings=!0),typeof t=="string"&&(t=et.util.createBuffer(t));var r=t.length(),n=hc(t,t.length(),0,e);if(e.parseAllBytes&&t.length()!==0){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=r,i.remaining=t.length(),i}return n};function hc(t,e,r,n){var i;Go(t,e,2);var s=t.getByte();e--;var o=s&192,a=s&31;i=t.length();var c=MT(t,e);if(e-=i-t.length(),c!==void 0&&c>e){if(n.strict){var u=new Error("Too few bytes to read ASN.1 value.");throw u.available=t.length(),u.remaining=e,u.requested=c,u}c=e}var l,f,d=(s&32)==32;if(d)if(l=[],c===void 0)for(;;){if(Go(t,e,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),e-=2;break}i=t.length(),l.push(hc(t,e,r+1,n)),e-=i-t.length()}else for(;c>0;)i=t.length(),l.push(hc(t,c,r+1,n)),e-=i-t.length(),c-=i-t.length();if(l===void 0&&o===Z.Class.UNIVERSAL&&a===Z.Type.BITSTRING&&(f=t.bytes(c)),l===void 0&&n.decodeBitStrings&&o===Z.Class.UNIVERSAL&&a===Z.Type.BITSTRING&&c>1){var p=t.read,h=e,g=0;if(a===Z.Type.BITSTRING&&(Go(t,e,1),g=t.getByte(),e--),g===0)try{i=t.length();var v={strict:!0,decodeBitStrings:!0},w=hc(t,e,r+1,v),C=i-t.length();e-=C,a==Z.Type.BITSTRING&&C++;var q=w.tagClass;C===c&&(q===Z.Class.UNIVERSAL||q===Z.Class.CONTEXT_SPECIFIC)&&(l=[w])}catch(F){}l===void 0&&(t.read=p,e=h)}if(l===void 0){if(c===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=e}if(a===Z.Type.BMPSTRING)for(l="";c>0;c-=2)Go(t,e,2),l+=String.fromCharCode(t.getInt16()),e-=2;else l=t.getBytes(c),e-=c}var W=f===void 0?null:{bitStringContents:f};return Z.create(o,a,d,l,W)}Z.toDer=function(t){var e=et.util.createBuffer(),r=t.tagClass|t.type,n=et.util.createBuffer(),i=!1;if("bitStringContents"in t&&(i=!0,t.original&&(i=Z.equals(t,t.original))),i)n.putBytes(t.bitStringContents);else if(t.composed){t.constructed?r|=32:n.putByte(0);for(var s=0;s1&&(t.value.charCodeAt(0)===0&&(t.value.charCodeAt(1)&128)==0||t.value.charCodeAt(0)===255&&(t.value.charCodeAt(1)&128)==128)?n.putBytes(t.value.substr(1)):n.putBytes(t.value);if(e.putByte(r),n.length()<=127)e.putByte(n.length()&127);else{var o=n.length(),a="";do a+=String.fromCharCode(o&255),o=o>>>8;while(o>0);e.putByte(a.length|128);for(var s=a.length-1;s>=0;--s)e.putByte(a.charCodeAt(s))}return e.putBuffer(n),e};Z.oidToDer=function(t){var e=t.split("."),r=et.util.createBuffer();r.putByte(40*parseInt(e[0],10)+parseInt(e[1],10));for(var n,i,s,o,a=2;a>>7,n||(o|=128),i.push(o),n=!1;while(s>0);for(var c=i.length-1;c>=0;--c)r.putByte(i[c])}return r};Z.derToOid=function(t){var e;typeof t=="string"&&(t=et.util.createBuffer(t));var r=t.getByte();e=Math.floor(r/40)+"."+r%40;for(var n=0;t.length()>0;)r=t.getByte(),n=n<<7,r&128?n+=r&127:(e+="."+(n+r),n=0);return e};Z.utcTimeToDate=function(t){var e=new Date,r=parseInt(t.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(t.substr(2,2),10)-1,i=parseInt(t.substr(4,2),10),s=parseInt(t.substr(6,2),10),o=parseInt(t.substr(8,2),10),a=0;if(t.length>11){var c=t.charAt(10),u=10;c!=="+"&&c!=="-"&&(a=parseInt(t.substr(10,2),10),u+=2)}if(e.setUTCFullYear(r,n,i),e.setUTCHours(s,o,a,0),u&&(c=t.charAt(u),c==="+"||c==="-")){var l=parseInt(t.substr(u+1,2),10),f=parseInt(t.substr(u+4,2),10),d=l*60+f;d*=6e4,c==="+"?e.setTime(+e-d):e.setTime(+e+d)}return e};Z.generalizedTimeToDate=function(t){var e=new Date,r=parseInt(t.substr(0,4),10),n=parseInt(t.substr(4,2),10)-1,i=parseInt(t.substr(6,2),10),s=parseInt(t.substr(8,2),10),o=parseInt(t.substr(10,2),10),a=parseInt(t.substr(12,2),10),c=0,u=0,l=!1;t.charAt(t.length-1)==="Z"&&(l=!0);var f=t.length-5,d=t.charAt(f);if(d==="+"||d==="-"){var p=parseInt(t.substr(f+1,2),10),h=parseInt(t.substr(f+4,2),10);u=p*60+h,u*=6e4,d==="+"&&(u*=-1),l=!0}return t.charAt(14)==="."&&(c=parseFloat(t.substr(14),10)*1e3),l?(e.setUTCFullYear(r,n,i),e.setUTCHours(s,o,a,c),e.setTime(+e+u)):(e.setFullYear(r,n,i),e.setHours(s,o,a,c)),e};Z.dateToUtcTime=function(t){if(typeof t=="string")return t;var e="",r=[];r.push((""+t.getUTCFullYear()).substr(2)),r.push(""+(t.getUTCMonth()+1)),r.push(""+t.getUTCDate()),r.push(""+t.getUTCHours()),r.push(""+t.getUTCMinutes()),r.push(""+t.getUTCSeconds());for(var n=0;n=-128&&t<128)return e.putSignedInt(t,8);if(t>=-32768&&t<32768)return e.putSignedInt(t,16);if(t>=-8388608&&t<8388608)return e.putSignedInt(t,24);if(t>=-2147483648&&t<2147483648)return e.putSignedInt(t,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=t,r};Z.derToInteger=function(t){typeof t=="string"&&(t=et.util.createBuffer(t));var e=t.length()*8;if(e>32)throw new Error("Integer too large; max is 32-bits.");return t.getSignedInt(e)};Z.validate=function(t,e,r,n){var i=!1;if((t.tagClass===e.tagClass||typeof e.tagClass=="undefined")&&(t.type===e.type||typeof e.type=="undefined"))if(t.constructed===e.constructed||typeof e.constructed=="undefined"){if(i=!0,e.value&&et.util.isArray(e.value))for(var s=0,o=0;i&&o0&&(n+=` +`);for(var i="",s=0;s1?n+="0x"+et.util.bytesToHex(t.value.slice(1)):n+="(none)",t.value.length>0){var u=t.value.charCodeAt(0);u==1?n+=" (1 unused bit shown)":u>1&&(n+=" ("+u+" unused bits shown)")}}else if(t.type===Z.Type.OCTETSTRING)Jp.test(t.value)||(n+="("+t.value+") "),n+="0x"+et.util.bytesToHex(t.value);else if(t.type===Z.Type.UTF8)try{n+=et.util.decodeUtf8(t.value)}catch(l){if(l.message==="URI malformed")n+="0x"+et.util.bytesToHex(t.value)+" (malformed UTF8)";else throw l}else t.type===Z.Type.PRINTABLESTRING||t.type===Z.Type.IA5String?n+=t.value:Jp.test(t.value)?n+="0x"+et.util.bytesToHex(t.value):t.value.length===0?n+="[null]":n+=t.value}return n}});var Ul=b((oU,ty)=>{var Tt=_e();Qe();ty.exports=Tt.cipher=Tt.cipher||{};Tt.cipher.algorithms=Tt.cipher.algorithms||{};Tt.cipher.createCipher=function(t,e){var r=t;if(typeof r=="string"&&(r=Tt.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+t);return new Tt.cipher.BlockCipher({algorithm:r,key:e,decrypt:!1})};Tt.cipher.createDecipher=function(t,e){var r=t;if(typeof r=="string"&&(r=Tt.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+t);return new Tt.cipher.BlockCipher({algorithm:r,key:e,decrypt:!0})};Tt.cipher.registerAlgorithm=function(t,e){t=t.toUpperCase(),Tt.cipher.algorithms[t]=e};Tt.cipher.getAlgorithm=function(t){return t=t.toUpperCase(),t in Tt.cipher.algorithms?Tt.cipher.algorithms[t]:null};var ql=Tt.cipher.BlockCipher=function(t){this.algorithm=t.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=t.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=t.decrypt,this.algorithm.initialize(t)};ql.prototype.start=function(t){t=t||{};var e={};for(var r in t)e[r]=t[r];e.decrypt=this._decrypt,this._finish=!1,this._input=Tt.util.createBuffer(),this.output=t.output||Tt.util.createBuffer(),this.mode.start(e)};ql.prototype.update=function(t){for(t&&this._input.putBuffer(t);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};ql.prototype.finish=function(t){t&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(r){return t(this.blockSize,r,!1)},this.mode.unpad=function(r){return t(this.blockSize,r,!0)});var e={};return e.decrypt=this._decrypt,e.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,e)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,e))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,e))}});var Fl=b((aU,ry)=>{var Rt=_e();Qe();Rt.cipher=Rt.cipher||{};var Se=ry.exports=Rt.cipher.modes=Rt.cipher.modes||{};Se.ecb=function(t){t=t||{},this.name="ECB",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Se.ecb.prototype.start=function(t){};Se.ecb.prototype.encrypt=function(t,e,r){if(t.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=t.length(),n=t.at(r-1);return n>this.blockSize<<2?!1:(t.truncate(n),!0)};Se.cbc=function(t){t=t||{},this.name="CBC",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Se.cbc.prototype.start=function(t){if(t.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in t)this._iv=pc(t.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Se.cbc.prototype.encrypt=function(t,e,r){if(t.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=t.length(),n=t.at(r-1);return n>this.blockSize<<2?!1:(t.truncate(n),!0)};Se.cfb=function(t){t=t||{},this.name="CFB",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=Rt.util.createBuffer(),this._partialBytes=0};Se.cfb.prototype.start=function(t){if(!("iv"in t))throw new Error("Invalid IV parameter.");this._iv=pc(t.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Se.cfb.prototype.encrypt=function(t,e,r){var n=t.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)t.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Se.cfb.prototype.decrypt=function(t,e,r){var n=t.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)t.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Se.ofb=function(t){t=t||{},this.name="OFB",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Rt.util.createBuffer(),this._partialBytes=0};Se.ofb.prototype.start=function(t){if(!("iv"in t))throw new Error("Invalid IV parameter.");this._iv=pc(t.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Se.ofb.prototype.encrypt=function(t,e,r){var n=t.length();if(t.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)t.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Se.ofb.prototype.decrypt=Se.ofb.prototype.encrypt;Se.ctr=function(t){t=t||{},this.name="CTR",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Rt.util.createBuffer(),this._partialBytes=0};Se.ctr.prototype.start=function(t){if(!("iv"in t))throw new Error("Invalid IV parameter.");this._iv=pc(t.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Se.ctr.prototype.encrypt=function(t,e,r){var n=t.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&(t.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}yc(this._inBlock)};Se.ctr.prototype.decrypt=Se.ctr.prototype.encrypt;Se.gcm=function(t){t=t||{},this.name="GCM",this.cipher=t.cipher,this.blockSize=t.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=Rt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Se.gcm.prototype.start=function(t){if(!("iv"in t))throw new Error("Invalid IV parameter.");var e=Rt.util.createBuffer(t.iv);this._cipherLength=0;var r;if("additionalData"in t?r=Rt.util.createBuffer(t.additionalData):r=Rt.util.createBuffer(),"tagLength"in t?this._tagLength=t.tagLength:this._tagLength=128,this._tag=null,t.decrypt&&(this._tag=Rt.util.createBuffer(t.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=e.length();if(n===12)this._j0=[e.getInt32(),e.getInt32(),e.getInt32(),1];else{for(this._j0=[0,0,0,0];e.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[e.getInt32(),e.getInt32(),e.getInt32(),e.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(Ml(n*8)))}this._inBlock=this._j0.slice(0),yc(this._inBlock),this._partialBytes=0,r=Rt.util.createBuffer(r),this._aDataLength=Ml(r.length()*8);var i=r.length()%this.blockSize;for(i&&r.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];r.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()])};Se.gcm.prototype.encrypt=function(t,e,r){var n=t.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.read-=this.blockSize,e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),yc(this._inBlock)};Se.gcm.prototype.decrypt=function(t,e,r){var n=t.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),yc(this._inBlock),this._hashBlock[0]=t.getInt32(),this._hashBlock[1]=t.getInt32(),this._hashBlock[2]=t.getInt32(),this._hashBlock[3]=t.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)e[n]=t[n]>>>1|(t[n-1]&1)<<31;e[0]=t[0]>>>1,r&&(e[0]^=this._R)};Se.gcm.prototype.tableMultiply=function(t){for(var e=[0,0,0,0],r=0;r<32;++r){var n=r/8|0,i=t[n]>>>(7-r%8)*4&15,s=this._m[r][i];e[0]^=s[0],e[1]^=s[1],e[2]^=s[2],e[3]^=s[3]}return e};Se.gcm.prototype.ghash=function(t,e,r){return e[0]^=r[0],e[1]^=r[1],e[2]^=r[2],e[3]^=r[3],this.tableMultiply(e)};Se.gcm.prototype.generateHashTable=function(t,e){for(var r=8/e,n=4*r,i=16*r,s=new Array(i),o=0;o>>1,i=new Array(r);i[n]=t.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s4){var r=t;t=Rt.util.createBuffer();for(var n=0;n{var Xe=_e();Ul();Fl();Qe();oy.exports=Xe.aes=Xe.aes||{};Xe.aes.startEncrypting=function(t,e,r,n){var i=gc({key:t,output:r,decrypt:!1,mode:n});return i.start(e),i};Xe.aes.createEncryptionCipher=function(t,e){return gc({key:t,output:null,decrypt:!1,mode:e})};Xe.aes.startDecrypting=function(t,e,r,n){var i=gc({key:t,output:r,decrypt:!0,mode:n});return i.start(e),i};Xe.aes.createDecryptionCipher=function(t,e){return gc({key:t,output:null,decrypt:!0,mode:e})};Xe.aes.Algorithm=function(t,e){Kl||iy();var r=this;r.name=t,r.mode=new e({blockSize:16,cipher:{encrypt:function(n,i){return jl(r._w,n,i,!1)},decrypt:function(n,i){return jl(r._w,n,i,!0)}}}),r._init=!1};Xe.aes.Algorithm.prototype.initialize=function(t){if(!this._init){var e=t.key,r;if(typeof e=="string"&&(e.length===16||e.length===24||e.length===32))e=Xe.util.createBuffer(e);else if(Xe.util.isArray(e)&&(e.length===16||e.length===24||e.length===32)){r=e,e=Xe.util.createBuffer();for(var n=0;n>>2;for(var n=0;n>8^a&255^99,Wt[r]=a,Vl[a]=r,c=t[a],i=t[r],s=t[i],o=t[s],u=c<<24^a<<16^a<<8^(a^c),l=(i^s^o)<<24^(r^o)<<16^(r^s^o)<<8^(r^i^o);for(var f=0;f<4;++f)Pi[f][r]=u,Fr[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;r===0?r=n=1:(r=i^t[t[t[i^o]]],n^=t[t[n]])}}function sy(t,e){for(var r=t.slice(0),n,i=1,s=r.length,o=s+6+1,a=Ts*o,c=s;c>>16&255]<<24^Wt[n>>>8&255]<<16^Wt[n&255]<<8^Wt[n>>>24]^ny[i]<<24,i++):s>6&&c%s==4&&(n=Wt[n>>>24]<<24^Wt[n>>>16&255]<<16^Wt[n>>>8&255]<<8^Wt[n&255]),r[c]=r[c-s]^n;if(e){var u,l=Fr[0],f=Fr[1],d=Fr[2],p=Fr[3],h=r.slice(0);a=r.length;for(var c=0,g=a-Ts;c>>24]]^f[Wt[u>>>16&255]]^d[Wt[u>>>8&255]]^p[Wt[u&255]];r=h}return r}function jl(t,e,r,n){var i=t.length/4-1,s,o,a,c,u;n?(s=Fr[0],o=Fr[1],a=Fr[2],c=Fr[3],u=Vl):(s=Pi[0],o=Pi[1],a=Pi[2],c=Pi[3],u=Wt);var l,f,d,p,h,g,v;l=e[0]^t[0],f=e[n?3:1]^t[1],d=e[2]^t[2],p=e[n?1:3]^t[3];for(var w=3,C=1;C>>24]^o[f>>>16&255]^a[d>>>8&255]^c[p&255]^t[++w],g=s[f>>>24]^o[d>>>16&255]^a[p>>>8&255]^c[l&255]^t[++w],v=s[d>>>24]^o[p>>>16&255]^a[l>>>8&255]^c[f&255]^t[++w],p=s[p>>>24]^o[l>>>16&255]^a[f>>>8&255]^c[d&255]^t[++w],l=h,f=g,d=v;r[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[d>>>8&255]<<8^u[p&255]^t[++w],r[n?3:1]=u[f>>>24]<<24^u[d>>>16&255]<<16^u[p>>>8&255]<<8^u[l&255]^t[++w],r[2]=u[d>>>24]<<24^u[p>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^t[++w],r[n?1:3]=u[p>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[d&255]^t[++w]}function gc(t){t=t||{};var e=(t.mode||"CBC").toUpperCase(),r="AES-"+e,n;t.decrypt?n=Xe.cipher.createDecipher(r,t.key):n=Xe.cipher.createCipher(r,t.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof Xe.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var vc=b((uU,cy)=>{var st=_e();Ul();Fl();Qe();cy.exports=st.des=st.des||{};st.des.startEncrypting=function(t,e,r,n){var i=mc({key:t,output:r,decrypt:!1,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};st.des.createEncryptionCipher=function(t,e){return mc({key:t,output:null,decrypt:!1,mode:e})};st.des.startDecrypting=function(t,e,r,n){var i=mc({key:t,output:r,decrypt:!0,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};st.des.createDecryptionCipher=function(t,e){return mc({key:t,output:null,decrypt:!0,mode:e})};st.des.Algorithm=function(t,e){var r=this;r.name=t,r.mode=new e({blockSize:8,cipher:{encrypt:function(n,i){return ay(r._keys,n,i,!1)},decrypt:function(n,i){return ay(r._keys,n,i,!0)}}}),r._init=!1};st.des.Algorithm.prototype.initialize=function(t){if(!this._init){var e=st.util.createBuffer(t.key);if(this.name.indexOf("3DES")===0&&e.length()!==24)throw new Error("Invalid Triple-DES key size: "+e.length()*8);this._keys=WT(e),this._init=!0}};tn("DES-ECB",st.cipher.modes.ecb);tn("DES-CBC",st.cipher.modes.cbc);tn("DES-CFB",st.cipher.modes.cfb);tn("DES-OFB",st.cipher.modes.ofb);tn("DES-CTR",st.cipher.modes.ctr);tn("3DES-ECB",st.cipher.modes.ecb);tn("3DES-CBC",st.cipher.modes.cbc);tn("3DES-CFB",st.cipher.modes.cfb);tn("3DES-OFB",st.cipher.modes.ofb);tn("3DES-CTR",st.cipher.modes.ctr);function tn(t,e){var r=function(){return new st.des.Algorithm(t,e)};st.cipher.registerAlgorithm(t,r)}var FT=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],KT=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],VT=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],jT=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],$T=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],HT=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],zT=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],GT=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function WT(t){for(var e=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],d=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],h=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=t.length()>8?3:1,v=[],w=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,q,W=0;W>>4^M)&252645135,M^=q,F^=q<<4,q=(M>>>-16^F)&65535,F^=q,M^=q<<-16,q=(F>>>2^M)&858993459,M^=q,F^=q<<2,q=(M>>>-16^F)&65535,F^=q,M^=q<<-16,q=(F>>>1^M)&1431655765,M^=q,F^=q<<1,q=(M>>>8^F)&16711935,F^=q,M^=q<<8,q=(F>>>1^M)&1431655765,M^=q,F^=q<<1,q=F<<8|M>>>20&240,F=M<<24|M<<8&16711680|M>>>8&65280|M>>>24&240,M=q;for(var re=0;re>>26,M=M<<2|M>>>26):(F=F<<1|F>>>27,M=M<<1|M>>>27),F&=-15,M&=-15;var ie=e[F>>>28]|r[F>>>24&15]|n[F>>>20&15]|i[F>>>16&15]|s[F>>>12&15]|o[F>>>8&15]|a[F>>>4&15],z=c[M>>>28]|u[M>>>24&15]|l[M>>>20&15]|f[M>>>16&15]|d[M>>>12&15]|p[M>>>8&15]|h[M>>>4&15];q=(z>>>16^ie)&65535,v[C++]=ie^q,v[C++]=z^q<<16}}return v}function ay(t,e,r,n){var i=t.length===32?3:9,s;i===3?s=n?[30,-2,-2]:[0,32,2]:s=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var o,a=e[0],c=e[1];o=(a>>>4^c)&252645135,c^=o,a^=o<<4,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u>>4|c<<28)^t[d+1];o=a,a=c,c=o^(KT[p>>>24&63]|jT[p>>>16&63]|HT[p>>>8&63]|GT[p&63]|FT[h>>>24&63]|VT[h>>>16&63]|$T[h>>>8&63]|zT[h&63])}o=a,a=c,c=o}a=a>>>1|a<<31,c=c>>>1|c<<31,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(a>>>4^c)&252645135,c^=o,a^=o<<4,r[0]=a,r[1]=c}function mc(t){t=t||{};var e=(t.mode||"CBC").toUpperCase(),r="DES-"+e,n;t.decrypt?n=st.cipher.createDecipher(r,t.key):n=st.cipher.createCipher(r,t.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof st.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var Yn=b((lU,uy)=>{var Ec=_e();uy.exports=Ec.md=Ec.md||{};Ec.md.algorithms=Ec.md.algorithms||{}});var fy=b((fU,ly)=>{var xn=_e();Yn();Qe();var YT=ly.exports=xn.hmac=xn.hmac||{};YT.create=function(){var t=null,e=null,r=null,n=null,i={};return i.start=function(s,o){if(s!==null)if(typeof s=="string")if(s=s.toLowerCase(),s in xn.md.algorithms)e=xn.md.algorithms[s].create();else throw new Error('Unknown hash algorithm "'+s+'"');else e=s;if(o===null)o=t;else{if(typeof o=="string")o=xn.util.createBuffer(o);else if(xn.util.isArray(o)){var a=o;o=xn.util.createBuffer();for(var c=0;ce.blockLength&&(e.start(),e.update(o.bytes()),o=e.digest()),r=xn.util.createBuffer(),n=xn.util.createBuffer(),u=o.length();for(var c=0;c{});var $l=b((pU,dy)=>{var Yt=_e();fy();Yn();Qe();var QT=Yt.pkcs5=Yt.pkcs5||{},An;Yt.util.isNodejs&&!Yt.options.usePureJavaScript&&(An=Bs());dy.exports=Yt.pbkdf2=QT.pbkdf2=function(t,e,r,n,i,s){if(typeof i=="function"&&(s=i,i=null),Yt.util.isNodejs&&!Yt.options.usePureJavaScript&&An.pbkdf2&&(i===null||typeof i!="object")&&(An.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),t=Buffer.from(t,"binary"),e=Buffer.from(e,"binary"),s?An.pbkdf2Sync.length===4?An.pbkdf2(t,e,r,n,function(q,W){if(q)return s(q);s(null,W.toString("binary"))}):An.pbkdf2(t,e,r,n,i,function(q,W){if(q)return s(q);s(null,W.toString("binary"))}):An.pbkdf2Sync.length===4?An.pbkdf2Sync(t,e,r,n).toString("binary"):An.pbkdf2Sync(t,e,r,n,i).toString("binary");if((typeof i=="undefined"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in Yt.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=Yt.md[i].create()}var o=i.digestLength;if(n>4294967295*o){var a=new Error("Derived key is too long.");if(s)return s(a);throw a}var c=Math.ceil(n/o),u=n-(c-1)*o,l=Yt.hmac.create();l.start(i,t);var f="",d,p,h;if(!s){for(var g=1;g<=c;++g){l.start(null,null),l.update(e),l.update(Yt.util.int32ToBytes(g)),d=h=l.digest().getBytes();for(var v=2;v<=r;++v)l.start(null,null),l.update(h),p=l.digest().getBytes(),d=Yt.util.xorBytes(d,p,o),h=p;f+=gc)return s(null,f);l.start(null,null),l.update(e),l.update(Yt.util.int32ToBytes(g)),d=h=l.digest().getBytes(),v=2,C()}function C(){if(v<=r)return l.start(null,null),l.update(h),p=l.digest().getBytes(),d=Yt.util.xorBytes(d,p,o),h=p,++v,Yt.util.setImmediate(C);f+=g{var bc=_e();Qe();var hy=py.exports=bc.pem=bc.pem||{};hy.encode=function(t,e){e=e||{};var r="-----BEGIN "+t.type+`-----\r +`,n;if(t.procType&&(n={name:"Proc-Type",values:[String(t.procType.version),t.procType.type]},r+=wc(n)),t.contentDomain&&(n={name:"Content-Domain",values:[t.contentDomain]},r+=wc(n)),t.dekInfo&&(n={name:"DEK-Info",values:[t.dekInfo.algorithm]},t.dekInfo.parameters&&n.values.push(t.dekInfo.parameters),r+=wc(n)),t.headers)for(var i=0;i65&&o!==-1){var a=e[o];a===","?(++o,e=e.substr(0,o)+`\r + `+e.substr(o)):e=e.substr(0,o)+`\r +`+a+e.substr(o+1),s=i-o-1,o=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(o=i);return e}function XT(t){return t.replace(/^\s+/,"")}});var by=b((gU,Ey)=>{var rn=_e();Yn();Qe();var yy=Ey.exports=rn.sha256=rn.sha256||{};rn.md.sha256=rn.md.algorithms.sha256=yy;yy.create=function(){gy||ZT();var t=null,e=rn.util.createBuffer(),r=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),vy(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=rn.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Hl.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4,h5:t.h5,h6:t.h6,h7:t.h7};vy(f,r,i);var d=rn.util.createBuffer();return d.putInt32(f.h0),d.putInt32(f.h1),d.putInt32(f.h2),d.putInt32(f.h3),d.putInt32(f.h4),d.putInt32(f.h5),d.putInt32(f.h6),d.putInt32(f.h7),d},n};var Hl=null,gy=!1,my=null;function ZT(){Hl=String.fromCharCode(128),Hl+=rn.util.fillString(String.fromCharCode(0),64),my=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],gy=!0}function vy(t,e,r){for(var n,i,s,o,a,c,u,l,f,d,p,h,g,v,w,C=r.length();C>=64;){for(u=0;u<16;++u)e[u]=r.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=t.h0,f=t.h1,d=t.h2,p=t.h3,h=t.h4,g=t.h5,v=t.h6,w=t.h7,u=0;u<64;++u)o=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),a=v^h&(g^v),s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|d&(l^f),n=w+o+a+my[u]+e[u],i=s+c,w=v,v=g,g=h,h=p+n>>>0,p=d,d=f,f=l,l=n+i>>>0;t.h0=t.h0+l|0,t.h1=t.h1+f|0,t.h2=t.h2+d|0,t.h3=t.h3+p|0,t.h4=t.h4+h|0,t.h5=t.h5+g|0,t.h6=t.h6+v|0,t.h7=t.h7+w|0,C-=64}}});var _y=b((mU,wy)=>{var nn=_e();Qe();var Sc=null;nn.util.isNodejs&&!nn.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Sc=Bs());var JT=wy.exports=nn.prng=nn.prng||{};JT.create=function(t){for(var e={plugin:t,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=t.md,n=new Array(32),i=0;i<32;++i)n[i]=r.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,d=e.plugin.increment,p=e.plugin.formatKey,h=e.plugin.formatSeed,g=nn.util.createBuffer();e.key=null,v();function v(w){if(w)return l(w);if(g.length()>=u)return l(null,g.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return nn.util.nextTick(function(){s(v)});var C=f(e.key,e.seed);e.generated+=C.length,g.putBytes(C),e.key=p(f(e.key,d(e.seed))),e.seed=h(f(e.key,e.seed)),nn.util.setImmediate(v)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed;e.key=null;for(var h=nn.util.createBuffer();h.length()1048575&&(e.key=null),e.key===null&&o();var g=l(e.key,e.seed);e.generated+=g.length,h.putBytes(g),e.key=d(l(e.key,f(e.seed))),e.seed=p(l(e.key,e.seed))}return h.getBytes(u)};function s(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,d){if(f)return u(f);e.collect(d),a(),u()})}function o(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l==0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var d=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(d),e.generated=0}function c(u){var l=null,f=nn.util.globalScope,d=f.crypto||f.msCrypto;d&&d.getRandomValues&&(l=function(F){return d.getRandomValues(F)});var p=nn.util.createBuffer();if(l)for(;p.length()>16),C+=(w&32767)<<16,C+=w>>15,C=(C&2147483647)+(C>>31),W=C&4294967295;for(var v=0;v<3;++v)q=W>>>(v<<3),q^=Math.floor(Math.random()*256),p.putByte(q&255)}return p.getBytes(u)}return Sc?(e.seedFile=function(u,l){Sc.randomBytes(u,function(f,d){if(f)return l(f);l(null,d.toString())})},e.seedFileSync=function(u){return Sc.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f>d&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,d){function p(h){var g=h.data;g.forge&&g.forge.prng&&(self.removeEventListener("message",p),d(g.forge.prng.err,g.forge.prng.bytes))}self.addEventListener("message",p),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var d=f.data;d.forge&&d.forge.prng&&e.seedFile(d.forge.prng.needed,function(p,h){u.postMessage({forge:{prng:{err:p,bytes:h}}})})};u.addEventListener("message",l)}},e}});var Ni=b((vU,zl)=>{var Bt=_e();Rs();by();_y();Qe();(function(){if(Bt.random&&Bt.random.getBytes){zl.exports=Bt.random;return}(function(t){var e={},r=new Array(4),n=Bt.util.createBuffer();e.formatKey=function(f){var d=Bt.util.createBuffer(f);return f=new Array(4),f[0]=d.getInt32(),f[1]=d.getInt32(),f[2]=d.getInt32(),f[3]=d.getInt32(),Bt.aes._expandKey(f,!1)},e.formatSeed=function(f){var d=Bt.util.createBuffer(f);return f=new Array(4),f[0]=d.getInt32(),f[1]=d.getInt32(),f[2]=d.getInt32(),f[3]=d.getInt32(),f},e.cipher=function(f,d){return Bt.aes._updateBlock(f,d,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=Bt.md.sha256;function i(){var f=Bt.prng.create(e);return f.getBytes=function(d,p){return f.generate(d,p)},f.getBytesSync=function(d){return f.generate(d)},f}var s=i(),o=null,a=Bt.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(o=function(f){return c.getRandomValues(f)}),Bt.options.usePureJavaScript||!Bt.util.isNodejs&&!o){if(typeof window=="undefined"||window.document===void 0,s.collectInt(+new Date,32),typeof navigator!="undefined"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch(f){}s.collect(u),u=null}t&&(t().mousemove(function(f){s.collectInt(f.clientX,16),s.collectInt(f.clientY,16)}),t().keypress(function(f){s.collectInt(f.charCode,8)}))}if(!Bt.random)Bt.random=s;else for(var l in s)Bt.random[l]=s[l];Bt.random.createInstance=i,zl.exports=Bt.random})(typeof jQuery!="undefined"?jQuery:null)})()});var Cy=b((EU,Ay)=>{var ir=_e();Qe();var Gl=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],Sy=[1,2,3,5],eR=function(t,e){return t<>16-e},tR=function(t,e){return(t&65535)>>e|t<<16-e&65535};Ay.exports=ir.rc2=ir.rc2||{};ir.rc2.expandKey=function(t,e){typeof t=="string"&&(t=ir.util.createBuffer(t)),e=e||128;var r=t,n=t.length(),i=e,s=Math.ceil(i/8),o=255>>(i&7),a;for(a=n;a<128;a++)r.putByte(Gl[r.at(a-1)+r.at(a-n)&255]);for(r.setAt(128-s,Gl[r.at(128-s)&o]),a=127-s;a>=0;a--)r.setAt(a,Gl[r.at(a+1)^r.at(a+s)]);return r};var xy=function(t,e,r){var n=!1,i=null,s=null,o=null,a,c,u,l,f=[];for(t=ir.rc2.expandKey(t,e),u=0;u<64;u++)f.push(t.getInt16Le());r?(a=function(h){for(u=0;u<4;u++)h[u]+=f[l]+(h[(u+3)%4]&h[(u+2)%4])+(~h[(u+3)%4]&h[(u+1)%4]),h[u]=eR(h[u],Sy[u]),l++},c=function(h){for(u=0;u<4;u++)h[u]+=f[h[(u+3)%4]&63]}):(a=function(h){for(u=3;u>=0;u--)h[u]=tR(h[u],Sy[u]),h[u]-=f[l]+(h[(u+3)%4]&h[(u+2)%4])+(~h[(u+3)%4]&h[(u+1)%4]),l--},c=function(h){for(u=3;u>=0;u--)h[u]-=f[h[(u+3)%4]&63]});var d=function(h){var g=[];for(u=0;u<4;u++){var v=i.getInt16Le();o!==null&&(r?v^=o.getInt16Le():o.putInt16Le(v)),g.push(v&65535)}l=r?0:63;for(var w=0;w=8;)d([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(h){var g=!0;if(r)if(h)g=h(8,i,!r);else{var v=i.length()===8?8:8-i.length();i.fillWithByte(v,v)}if(g&&(n=!0,p.update()),!r&&(g=i.length()===0,g))if(h)g=h(8,s,!r);else{var w=s.length(),C=s.at(w-1);C>w?g=!1:s.truncate(C)}return g}},p};ir.rc2.startEncrypting=function(t,e,r){var n=ir.rc2.createEncryptionCipher(t,128);return n.start(e,r),n};ir.rc2.createEncryptionCipher=function(t,e){return xy(t,e,!0)};ir.rc2.startDecrypting=function(t,e,r){var n=ir.rc2.createDecryptionCipher(t,128);return n.start(e,r),n};ir.rc2.createDecryptionCipher=function(t,e){return xy(t,e,!1)}});var Cc=b((bU,Dy)=>{var Wl=_e();Dy.exports=Wl.jsbn=Wl.jsbn||{};var Cn,rR=244837814094590,Iy=(rR&16777215)==15715070;function $(t,e,r){this.data=[],t!=null&&(typeof t=="number"?this.fromNumber(t,e,r):e==null&&typeof t!="string"?this.fromString(t,256):this.fromString(t,e))}Wl.jsbn.BigInteger=$;function Le(){return new $(null)}function nR(t,e,r,n,i,s){for(;--s>=0;){var o=e*this.data[t++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=o&67108863}return i}function iR(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this.data[t]&32767,u=this.data[t++]>>15,l=a*c+u*o;c=o*c+((l&32767)<<15)+r.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=c&1073741823}return i}function Ty(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this.data[t]&16383,u=this.data[t++]>>14,l=a*c+u*o;c=o*c+((l&16383)<<14)+r.data[n]+i,i=(c>>28)+(l>>14)+a*u,r.data[n++]=c&268435455}return i}typeof navigator=="undefined"?($.prototype.am=Ty,Cn=28):Iy&&navigator.appName=="Microsoft Internet Explorer"?($.prototype.am=iR,Cn=30):Iy&&navigator.appName!="Netscape"?($.prototype.am=nR,Cn=26):($.prototype.am=Ty,Cn=28);$.prototype.DB=Cn;$.prototype.DM=(1<=0;--e)t.data[e]=this.data[e];t.t=this.t,t.s=this.s}function aR(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0}function Qn(t){var e=Le();return e.fromInt(t),e}function cR(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==256)r=8;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else{this.fromRadix(t,e);return}this.t=0,this.s=0;for(var n=t.length,i=!1,s=0;--n>=0;){var o=r==8?t[n]&255:By(t,n);if(o<0){t.charAt(n)=="-"&&(i=!0);continue}i=!1,s==0?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB)}r==8&&(t[0]&128)!=0&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==t;)--this.t}function lR(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else return this.toRadix(t);var r=(1<0)for(a>a)>0&&(i=!0,s=Ry(n));o>=0;)a>(a+=this.DB-e)):(n=this.data[o]>>(a-=e)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=Ry(n));return i?s:"0"}function fR(){var t=Le();return $.ZERO.subTo(this,t),t}function dR(){return this.s<0?this.negate():this}function hR(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this.data[r]-t.data[r])!=0)return e;return 0}function Ac(t){var e=1,r;return(r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function pR(){return this.t<=0?0:this.DB*(this.t-1)+Ac(this.data[this.t-1]^this.s&this.DM)}function yR(t,e){var r;for(r=this.t-1;r>=0;--r)e.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)e.data[r]=0;e.t=this.t+t,e.s=this.s}function gR(t,e){for(var r=t;r=0;--a)e.data[a+s+1]=this.data[a]>>n|o,o=(this.data[a]&i)<=0;--a)e.data[a]=0;e.data[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp()}function vR(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<>n;for(var o=r+1;o>n;n>0&&(e.data[this.t-r-1]|=(this.s&s)<>=this.DB;if(t.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=t.s}e.s=n<0?-1:0,n<-1?e.data[r++]=this.DV+n:n>0&&(e.data[r++]=n),e.t=r,e.clamp()}function bR(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i=0;)t.data[r]=0;for(r=0;r=e.DV&&(t.data[r+e.t]-=e.DV,t.data[r+e.t+1]=1)}t.t>0&&(t.data[t.t-1]+=e.am(r,e.data[r],t,2*r,0,1)),t.s=0,t.clamp()}function _R(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var u=s.t,l=s.data[u-1];if(l!=0){var f=l*(1<1?s.data[u-2]>>this.F2:0),d=this.FV/f,p=(1<=0&&(r.data[r.t++]=1,r.subTo(w,r)),$.ONE.dlShiftTo(u,w),w.subTo(s,s);s.t=0;){var C=r.data[--g]==l?this.DM:Math.floor(r.data[g]*d+(r.data[g-1]+h)*p);if((r.data[g]+=s.am(0,C,r,v,0,u))0&&r.rShiftTo(c,r),o<0&&$.ZERO.subTo(r,r)}}}function SR(t){var e=Le();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo($.ZERO)>0&&t.subTo(e,e),e}function Oi(t){this.m=t}function xR(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function AR(t){return t}function CR(t){t.divRemTo(this.m,null,t)}function IR(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function TR(t,e){t.squareTo(e),this.reduce(e)}Oi.prototype.convert=xR;Oi.prototype.revert=AR;Oi.prototype.reduce=CR;Oi.prototype.mulTo=IR;Oi.prototype.sqrTo=TR;function RR(){if(this.t<1)return 0;var t=this.data[0];if((t&1)==0)return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Di(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(e,e),e}function PR(t){var e=Le();return t.copyTo(e),this.reduce(e),e}function NR(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t.data[r]+=this.m.am(0,n,t,e,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function OR(t,e){t.squareTo(e),this.reduce(e)}function DR(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Di.prototype.convert=BR;Di.prototype.revert=PR;Di.prototype.reduce=NR;Di.prototype.mulTo=DR;Di.prototype.sqrTo=OR;function LR(){return(this.t>0?this.data[0]&1:this.s)==0}function kR(t,e){if(t>4294967295||t<1)return $.ONE;var r=Le(),n=Le(),i=e.convert(this),s=Ac(t)-1;for(i.copyTo(r);--s>=0;)if(e.sqrTo(r,n),(t&1<0)e.mulTo(n,i,r);else{var o=r;r=n,n=o}return e.revert(r)}function qR(t,e){var r;return t<256||e.isEven()?r=new Oi(e):r=new Di(e),this.exp(t,r)}$.prototype.copyTo=oR;$.prototype.fromInt=aR;$.prototype.fromString=cR;$.prototype.clamp=uR;$.prototype.dlShiftTo=yR;$.prototype.drShiftTo=gR;$.prototype.lShiftTo=mR;$.prototype.rShiftTo=vR;$.prototype.subTo=ER;$.prototype.multiplyTo=bR;$.prototype.squareTo=wR;$.prototype.divRemTo=_R;$.prototype.invDigit=RR;$.prototype.isEven=LR;$.prototype.exp=kR;$.prototype.toString=lR;$.prototype.negate=fR;$.prototype.abs=dR;$.prototype.compareTo=hR;$.prototype.bitLength=pR;$.prototype.mod=SR;$.prototype.modPowInt=qR;$.ZERO=Qn(0);$.ONE=Qn(1);function UR(){var t=Le();return this.copyTo(t),t}function MR(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function KR(){return this.t==0?this.s:this.data[0]<<16>>16}function VR(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function jR(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function $R(t){if(t==null&&(t=10),this.signum()==0||t<2||t>36)return"0";var e=this.chunkSize(t),r=Math.pow(t,e),n=Qn(r),i=Le(),s=Le(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(t).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(t)+o}function HR(t,e){this.fromInt(0),e==null&&(e=10);for(var r=this.chunkSize(e),n=Math.pow(e,r),i=!1,s=0,o=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),i&&$.ZERO.subTo(this,this)}function zR(t,e,r){if(typeof e=="number")if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo($.ONE.shiftLeft(t-1),Ql,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo($.ONE.shiftLeft(t-1),this);else{var n=new Array,i=t&7;n.length=(t>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<0)for(r>r)!=(this.s&this.DM)>>r&&(e[i++]=n|this.s<=0;)r<8?(n=(this.data[t]&(1<>(r+=this.DB-8)):(n=this.data[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),(n&128)!=0&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function WR(t){return this.compareTo(t)==0}function YR(t){return this.compareTo(t)<0?this:t}function QR(t){return this.compareTo(t)>0?this:t}function XR(t,e,r){var n,i,s=Math.min(t.t,this.t);for(n=0;n>=16,e+=16),(t&255)==0&&(t>>=8,e+=8),(t&15)==0&&(t>>=4,e+=4),(t&3)==0&&(t>>=2,e+=2),(t&1)==0&&++e,e}function a4(){for(var t=0;t=this.t?this.s!=0:(this.data[e]&1<>=this.DB;if(t.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=t.s}e.s=n<0?-1:0,n>0?e.data[r++]=n:n<-1&&(e.data[r++]=this.DV+n),e.t=r,e.clamp()}function g4(t){var e=Le();return this.addTo(t,e),e}function m4(t){var e=Le();return this.subTo(t,e),e}function v4(t){var e=Le();return this.multiplyTo(t,e),e}function E4(t){var e=Le();return this.divRemTo(t,e,null),e}function b4(t){var e=Le();return this.divRemTo(t,null,e),e}function w4(t){var e=Le(),r=Le();return this.divRemTo(t,e,r),new Array(e,r)}function _4(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function S4(t,e){if(t!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=t;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function Wo(){}function Oy(t){return t}function x4(t,e,r){t.multiplyTo(e,r)}function A4(t,e){t.squareTo(e)}Wo.prototype.convert=Oy;Wo.prototype.revert=Oy;Wo.prototype.mulTo=x4;Wo.prototype.sqrTo=A4;function C4(t){return this.exp(t,new Wo)}function I4(t,e,r){var n=Math.min(this.t+t.t,e);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var i;for(i=r.t-this.t;n=0;)r.data[n]=0;for(n=Math.max(e-this.t,0);n2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=Le();return t.copyTo(e),this.reduce(e),e}function B4(t){return t}function P4(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function N4(t,e){t.squareTo(e),this.reduce(e)}function O4(t,e,r){t.multiplyTo(e,r),this.reduce(r)}Ns.prototype.convert=R4;Ns.prototype.revert=B4;Ns.prototype.reduce=P4;Ns.prototype.mulTo=O4;Ns.prototype.sqrTo=N4;function D4(t,e){var r=t.bitLength(),n,i=Qn(1),s;if(r<=0)return i;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?s=new Oi(e):e.isEven()?s=new Ns(e):s=new Di(e);var o=new Array,a=3,c=n-1,u=(1<1){var l=Le();for(s.sqrTo(o[1],l);a<=u;)o[a]=Le(),s.mulTo(l,o[a-2],o[a]),a+=2}var f=t.t-1,d,p=!0,h=Le(),g;for(r=Ac(t.data[f])-1;f>=0;){for(r>=c?d=t.data[f]>>r-c&u:(d=(t.data[f]&(1<0&&(d|=t.data[f-1]>>this.DB+r-c)),a=n;(d&1)==0;)d>>=1,--a;if((r-=a)<0&&(r+=this.DB,--f),p)o[d].copyTo(i),p=!1;else{for(;a>1;)s.sqrTo(i,h),s.sqrTo(h,i),a-=2;a>0?s.sqrTo(i,h):(g=i,i=h,h=g),s.mulTo(h,o[d],i)}for(;f>=0&&(t.data[f]&1<0&&(e.rShiftTo(s,e),r.rShiftTo(s,r));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),e.compareTo(r)>=0?(e.subTo(r,e),e.rShiftTo(1,e)):(r.subTo(e,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r}function k4(t){if(t<=0)return 0;var e=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(e==0)r=this.data[0]%t;else for(var n=this.t-1;n>=0;--n)r=(e*r+this.data[n])%t;return r}function q4(t){var e=t.isEven();if(this.isEven()&&e||t.signum()==0)return $.ZERO;for(var r=t.clone(),n=this.clone(),i=Qn(1),s=Qn(0),o=Qn(0),a=Qn(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),e?((!i.isEven()||!s.isEven())&&(i.addTo(this,i),s.subTo(t,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(t,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),e&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(r,n),e&&o.subTo(i,o),a.subTo(s,a))}if(n.compareTo($.ONE)!=0)return $.ZERO;if(a.compareTo(t)>=0)return a.subtract(t);if(a.signum()<0)a.addTo(t,a);else return a;return a.signum()<0?a.add(t):a}var Kr=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],U4=(1<<26)/Kr[Kr.length-1];function M4(t){var e,r=this.abs();if(r.t==1&&r.data[0]<=Kr[Kr.length-1]){for(e=0;e=0);var a=s.modPow(n,this);if(a.compareTo($.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++{var sn=_e();Yn();Qe();var Ly=Uy.exports=sn.sha1=sn.sha1||{};sn.md.sha1=sn.md.algorithms.sha1=Ly;Ly.create=function(){ky||V4();var t=null,e=sn.util.createBuffer(),r=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),qy(t,r,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=sn.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(Xl.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4};qy(f,r,i);var d=sn.util.createBuffer();return d.putInt32(f.h0),d.putInt32(f.h1),d.putInt32(f.h2),d.putInt32(f.h3),d.putInt32(f.h4),d},n};var Xl=null,ky=!1;function V4(){Xl=String.fromCharCode(128),Xl+=sn.util.fillString(String.fromCharCode(0),64),ky=!0}function qy(t,e,r){for(var n,i,s,o,a,c,u,l,f=r.length();f>=64;){for(i=t.h0,s=t.h1,o=t.h2,a=t.h3,c=t.h4,l=0;l<16;++l)n=r.getInt32(),e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s&o|a&(s^o),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;t.h0=t.h0+i|0,t.h1=t.h1+s|0,t.h2=t.h2+o|0,t.h3=t.h3+a|0,t.h4=t.h4+c|0,f-=64}}});var Vy=b((_U,Ky)=>{var on=_e();Qe();Ni();My();var Fy=Ky.exports=on.pkcs1=on.pkcs1||{};Fy.encode_rsa_oaep=function(t,e,r){var n,i,s,o;typeof r=="string"?(n=r,i=arguments[3]||void 0,s=arguments[4]||void 0):r&&(n=r.label||void 0,i=r.seed||void 0,s=r.md||void 0,r.mgf1&&r.mgf1.md&&(o=r.mgf1.md)),s?s.start():s=on.md.sha1.create(),o||(o=s);var a=Math.ceil(t.n.bitLength()/8),c=a-2*s.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),s.update(n,"raw");for(var l=s.digest(),f="",d=c-e.length,p=0;p>24&255,s>>16&255,s>>8&255,s&255);r.start(),r.update(t+o),n+=r.digest().getBytes()}return n.substring(0,e)}});var jy=b((SU,Zl)=>{var Xn=_e();Qe();Cc();Ni();(function(){if(Xn.prime){Zl.exports=Xn.prime;return}var t=Zl.exports=Xn.prime=Xn.prime||{},e=Xn.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,d){return f|d};t.generateProbablePrime=function(f,d,p){typeof d=="function"&&(p=d,d={}),d=d||{};var h=d.algorithm||"PRIMEINC";typeof h=="string"&&(h={name:h}),h.options=h.options||{};var g=d.prng||Xn.random,v={nextBytes:function(w){for(var C=g.getBytesSync(w.length),q=0;qd&&(f=u(d,p)),f.isProbablePrime(g))return w(null,f);f.dAddOffset(r[h++%8],0)}while(v<0||+new Date-Cf&&(g=u(f,d));var ft=g.toString(16);Ae.target.postMessage({hex:ft,workLoad:w}),g.dAddOffset(C,0)}}}}function u(f,d){var p=new e(f,d),h=f-1;return p.testBit(h)||p.bitwiseTo(e.ONE.shiftLeft(h),i,p),p.dAddOffset(31-p.mod(n).byteValue(),0),p}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var Yo=b((xU,Qy)=>{var le=_e();Wn();Cc();Cs();Vy();jy();Ni();Qe();typeof Be=="undefined"&&(Be=le.jsbn.BigInteger);var Be,Jl=le.util.isNodejs?Bs():null,N=le.asn1,wr=le.util;le.pki=le.pki||{};Qy.exports=le.pki.rsa=le.rsa=le.rsa||{};var me=le.pki,j4=[6,4,2,4,2,4,6,2],$4={name:"PrivateKeyInfo",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},H4={name:"RSAPrivateKey",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},z4={name:"RSAPublicKey",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},G4=le.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:N.Class.UNIVERSAL,type:N.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},W4={name:"DigestInfo",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:N.Class.UNIVERSAL,type:N.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Y4=function(t){var e;if(t.algorithm in me.oids)e=me.oids[t.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=t.algorithm,r}var n=N.oidToDer(e).getBytes(),i=N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[]),s=N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[]);s.value.push(N.create(N.Class.UNIVERSAL,N.Type.OID,!1,n)),s.value.push(N.create(N.Class.UNIVERSAL,N.Type.NULL,!1,""));var o=N.create(N.Class.UNIVERSAL,N.Type.OCTETSTRING,!1,t.digest().getBytes());return i.value.push(s),i.value.push(o),N.toDer(i).getBytes()},$y=function(t,e,r){if(r)return t.modPow(e.e,e.n);if(!e.p||!e.q)return t.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(Be.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(Be.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new Be(le.util.bytesToHex(le.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(Be.ONE));t=t.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=t.mod(e.p).modPow(e.dP,e.p),s=t.mod(e.q).modPow(e.dQ,e.q);i.compareTo(s)<0;)i=i.add(e.p);var o=i.subtract(s).multiply(e.qInv).mod(e.p).multiply(e.q).add(s);return o=o.multiply(n.modInverse(e.n)).mod(e.n),o};me.rsa.encrypt=function(t,e,r){var n=r,i,s=Math.ceil(e.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,i=Hy(t,e,r)):(i=le.util.createBuffer(),i.putBytes(t));for(var o=new Be(i.toHex(),16),a=$y(o,e,n),c=a.toString(16),u=le.util.createBuffer(),l=s-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(le.util.hexToBytes(c)),u.getBytes()};me.rsa.decrypt=function(t,e,r,n){var i=Math.ceil(e.n.bitLength()/8);if(t.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=t.length,s.expected=i,s}var o=new Be(le.util.createBuffer(t).toHex(),16);if(o.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=$y(o,e,r),c=a.toString(16),u=le.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(le.util.hexToBytes(c)),n!==!1?Tc(u.getBytes(),e,r):u.getBytes()};me.rsa.createKeyPairGenerationState=function(t,e,r){typeof t=="string"&&(t=parseInt(t,10)),t=t||2048,r=r||{};var n=r.prng||le.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u>1,pBits:t-(t>>1),pqState:0,num:null,keys:null},o.e.fromInt(o.eInt);else throw new Error("Invalid key generation algorithm: "+s);return o};me.rsa.stepKeyPairGenerationState=function(t,e){"algorithm"in t||(t.algorithm="PRIMEINC");var r=new Be(null);r.fromInt(30);for(var n=0,i=function(f,d){return f|d},s=+new Date,o,a=0;t.keys===null&&(e<=0||ac?t.pqState=0:t.num.isProbablePrime(X4(t.num.bitLength()))?++t.pqState:t.num.dAddOffset(j4[n++%8],0):t.pqState===2?t.pqState=t.num.subtract(Be.ONE).gcd(t.e).compareTo(Be.ONE)===0?3:0:t.pqState===3&&(t.pqState=0,t.p===null?t.p=t.num:t.q=t.num,t.p!==null&&t.q!==null&&++t.state,t.num=null)}else if(t.state===1)t.p.compareTo(t.q)<0&&(t.num=t.p,t.p=t.q,t.q=t.num),++t.state;else if(t.state===2)t.p1=t.p.subtract(Be.ONE),t.q1=t.q.subtract(Be.ONE),t.phi=t.p1.multiply(t.q1),++t.state;else if(t.state===3)t.phi.gcd(t.e).compareTo(Be.ONE)===0?++t.state:(t.p=null,t.q=null,t.state=0);else if(t.state===4)t.n=t.p.multiply(t.q),t.n.bitLength()===t.bits?++t.state:(t.q=null,t.state=0);else if(t.state===5){var l=t.e.modInverse(t.phi);t.keys={privateKey:me.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:me.rsa.setPublicKey(t.n,t.e)}}o=+new Date,a+=o-s,s=o}return t.keys!==null};me.rsa.generateKeyPair=function(t,e,r,n){if(arguments.length===1?typeof t=="object"?(r=t,t=void 0):typeof t=="function"&&(n=t,t=void 0):arguments.length===2?typeof t=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(r=e,e=void 0):(r=t,n=e,t=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=e,e=void 0)),r=r||{},t===void 0&&(t=r.bits||2048),e===void 0&&(e=r.e||65537),!le.options.usePureJavaScript&&!r.prng&&t>=256&&t<=16384&&(e===65537||e===3)){if(n){if(zy("generateKeyPair"))return Jl.generateKeyPair("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:me.privateKeyFromPem(u),publicKey:me.publicKeyFromPem(c)})});if(Gy("generateKey")&&Gy("exportKey"))return wr.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:Yy(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return wr.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=me.privateKeyFromAsn1(N.fromDer(le.util.createBuffer(a)));n(null,{privateKey:c,publicKey:me.setRsaPublicKey(c.n,c.e)})}});if(Wy("generateKey")&&Wy("exportKey")){var i=wr.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:Yy(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=wr.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,d=me.privateKeyFromAsn1(N.fromDer(le.util.createBuffer(f)));n(null,{privateKey:d,publicKey:me.setRsaPublicKey(d.n,d.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(zy("generateKeyPairSync")){var s=Jl.generateKeyPairSync("rsa",{modulusLength:t,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:me.privateKeyFromPem(s.privateKey),publicKey:me.publicKeyFromPem(s.publicKey)}}}var o=me.rsa.createKeyPairGenerationState(t,e,r);if(!n)return me.rsa.stepKeyPairGenerationState(o,0),o.keys;Q4(o,r,n)};me.setRsaPublicKey=me.rsa.setPublicKey=function(t,e){var r={n:t,e};return r.encrypt=function(n,i,s){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return Hy(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return le.pkcs1.encode_rsa_oaep(c,a,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var o=i.encode(n,r,!0);return me.rsa.encrypt(o,r,!0)},r.verify=function(n,i,s,o){typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSASSA-PKCS1-V1_5"),o===void 0&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),s==="RSASSA-PKCS1-V1_5"?s={verify:function(c,u){u=Tc(u,r,!0);var l=N.fromDer(u,{parseAllBytes:o._parseAllDigestBytes}),f={},d=[];if(!N.validate(l,W4,f,d)){var p=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw p.errors=d,p}var h=N.derToOid(f.algorithmIdentifier);if(!(h===le.oids.md2||h===le.oids.md5||h===le.oids.sha1||h===le.oids.sha224||h===le.oids.sha256||h===le.oids.sha384||h===le.oids.sha512||h===le.oids["sha512-224"]||h===le.oids["sha512-256"])){var p=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw p.oid=h,p}if((h===le.oids.md2||h===le.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(s==="NONE"||s==="NULL"||s===null)&&(s={verify:function(c,u){return u=Tc(u,r,!0),c===u}});var a=me.rsa.decrypt(i,r,!0,!1);return s.verify(n,a,r.n.bitLength())},r};me.setRsaPrivateKey=me.rsa.setPrivateKey=function(t,e,r,n,i,s,o,a){var c={n:t,e,d:r,p:n,q:i,dP:s,dQ:o,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var d=me.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Tc};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(p,h){return le.pkcs1.decode_rsa_oaep(h,p,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(p){return p}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(d,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:Y4},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var d=l.encode(u,c.n.bitLength());return me.rsa.encrypt(d,c,f)},c};me.wrapRsaPrivateKey=function(t){return N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,N.integerToDer(0).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(me.oids.rsaEncryption).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.NULL,!1,"")]),N.create(N.Class.UNIVERSAL,N.Type.OCTETSTRING,!1,N.toDer(t).getBytes())])};me.privateKeyFromAsn1=function(t){var e={},r=[];if(N.validate(t,$4,e,r)&&(t=N.fromDer(le.util.createBuffer(e.privateKey))),e={},r=[],!N.validate(t,H4,e,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var i,s,o,a,c,u,l,f;return i=le.util.createBuffer(e.privateKeyModulus).toHex(),s=le.util.createBuffer(e.privateKeyPublicExponent).toHex(),o=le.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=le.util.createBuffer(e.privateKeyPrime1).toHex(),c=le.util.createBuffer(e.privateKeyPrime2).toHex(),u=le.util.createBuffer(e.privateKeyExponent1).toHex(),l=le.util.createBuffer(e.privateKeyExponent2).toHex(),f=le.util.createBuffer(e.privateKeyCoefficient).toHex(),me.setRsaPrivateKey(new Be(i,16),new Be(s,16),new Be(o,16),new Be(a,16),new Be(c,16),new Be(u,16),new Be(l,16),new Be(f,16))};me.privateKeyToAsn1=me.privateKeyToRSAPrivateKey=function(t){return N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,N.integerToDer(0).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.n)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.e)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.d)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.p)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.q)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.dP)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.dQ)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.qInv))])};me.publicKeyFromAsn1=function(t){var e={},r=[];if(N.validate(t,G4,e,r)){var n=N.derToOid(e.publicKeyOid);if(n!==me.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}t=e.rsaPublicKey}if(r=[],!N.validate(t,z4,e,r)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=r,i}var s=le.util.createBuffer(e.publicKeyModulus).toHex(),o=le.util.createBuffer(e.publicKeyExponent).toHex();return me.setRsaPublicKey(new Be(s,16),new Be(o,16))};me.publicKeyToAsn1=me.publicKeyToSubjectPublicKeyInfo=function(t){return N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(me.oids.rsaEncryption).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.NULL,!1,"")]),N.create(N.Class.UNIVERSAL,N.Type.BITSTRING,!1,[me.publicKeyToRSAPublicKey(t)])])};me.publicKeyToRSAPublicKey=function(t){return N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.n)),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,an(t.e))])};function Hy(t,e,r){var n=le.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(t.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=t.length,s.max=i-11,s}n.putByte(0),n.putByte(r);var o=i-3-t.length,a;if(r===0||r===1){a=r===0?0:255;for(var c=0;c0;){for(var u=0,l=le.random.getBytes(o),c=0;c1;){if(s.getByte()!==255){--s.read;break}++c}else if(a===2)for(c=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++c}var l=s.getByte();if(l!==0||c!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function Q4(t,e,r){typeof e=="function"&&(r=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){s(t.pBits,function(a,c){if(a)return r(a);if(t.p=c,t.q!==null)return o(a,t.q);s(t.qBits,o)})}function s(a,c){le.prime.generateProbablePrime(a,n,c)}function o(a,c){if(a)return r(a);if(t.q=c,t.p.compareTo(t.q)<0){var u=t.p;t.p=t.q,t.q=u}if(t.p.subtract(Be.ONE).gcd(t.e).compareTo(Be.ONE)!==0){t.p=null,i();return}if(t.q.subtract(Be.ONE).gcd(t.e).compareTo(Be.ONE)!==0){t.q=null,s(t.qBits,o);return}if(t.p1=t.p.subtract(Be.ONE),t.q1=t.q.subtract(Be.ONE),t.phi=t.p1.multiply(t.q1),t.phi.gcd(t.e).compareTo(Be.ONE)!==0){t.p=t.q=null,i();return}if(t.n=t.p.multiply(t.q),t.n.bitLength()!==t.bits){t.q=null,s(t.qBits,o);return}var l=t.e.modInverse(t.phi);t.keys={privateKey:me.rsa.setPrivateKey(t.n,t.e,l,t.p,t.q,l.mod(t.p1),l.mod(t.q1),t.q.modInverse(t.p)),publicKey:me.rsa.setPublicKey(t.n,t.e)},r(null,t.keys)}}function an(t){var e=t.toString(16);e[0]>="8"&&(e="00"+e);var r=le.util.hexToBytes(e);return r.length>1&&(r.charCodeAt(0)===0&&(r.charCodeAt(1)&128)==0||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)==128)?r.substr(1):r}function X4(t){return t<=100?27:t<=150?18:t<=200?15:t<=250?12:t<=300?9:t<=350?8:t<=400?7:t<=500?6:t<=600?5:t<=800?4:t<=1250?3:2}function zy(t){return le.util.isNodejs&&typeof Jl[t]=="function"}function Gy(t){return typeof wr.globalScope!="undefined"&&typeof wr.globalScope.crypto=="object"&&typeof wr.globalScope.crypto.subtle=="object"&&typeof wr.globalScope.crypto.subtle[t]=="function"}function Wy(t){return typeof wr.globalScope!="undefined"&&typeof wr.globalScope.msCrypto=="object"&&typeof wr.globalScope.msCrypto.subtle=="object"&&typeof wr.globalScope.msCrypto.subtle[t]=="function"}function Yy(t){for(var e=le.util.hexToBytes(t.toString(16)),r=new Uint8Array(e.length),n=0;n{var te=_e();Rs();Wn();vc();Yn();Cs();$l();_c();Ni();Cy();Yo();Qe();typeof Xy=="undefined"&&(Xy=te.jsbn.BigInteger);var Xy,K=te.asn1,Ee=te.pki=te.pki||{};tg.exports=Ee.pbe=te.pbe=te.pbe||{};var Li=Ee.oids,Z4={name:"EncryptedPrivateKeyInfo",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:K.Class.UNIVERSAL,type:K.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:K.Class.UNIVERSAL,type:K.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},J4={name:"PBES2Algorithms",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:K.Class.UNIVERSAL,type:K.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:K.Class.UNIVERSAL,type:K.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:K.Class.UNIVERSAL,type:K.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:K.Class.UNIVERSAL,type:K.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:K.Class.UNIVERSAL,type:K.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:K.Class.UNIVERSAL,type:K.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:K.Class.UNIVERSAL,type:K.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},eB={name:"pkcs-12PbeParams",tagClass:K.Class.UNIVERSAL,type:K.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:K.Class.UNIVERSAL,type:K.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:K.Class.UNIVERSAL,type:K.Type.INTEGER,constructed:!1,capture:"iterations"}]};Ee.encryptPrivateKeyInfo=function(t,e,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var n=te.random.getBytesSync(r.saltSize),i=r.count,s=K.integerToDer(i),o,a,c;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var u,l,f;switch(r.algorithm){case"aes128":o=16,u=16,l=Li["aes128-CBC"],f=te.aes.createEncryptionCipher;break;case"aes192":o=24,u=16,l=Li["aes192-CBC"],f=te.aes.createEncryptionCipher;break;case"aes256":o=32,u=16,l=Li["aes256-CBC"],f=te.aes.createEncryptionCipher;break;case"des":o=8,u=8,l=Li.desCBC,f=te.des.createEncryptionCipher;break;default:var d=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw d.algorithm=r.algorithm,d}var p="hmacWith"+r.prfAlgorithm.toUpperCase(),h=eg(p),g=te.pkcs5.pbkdf2(e,n,i,o,h),v=te.random.getBytesSync(u),w=f(g);w.start(v),w.update(K.toDer(t)),w.finish(),c=w.output.getBytes();var C=tB(n,s,o,p);a=K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.OID,!1,K.oidToDer(Li.pkcs5PBES2).getBytes()),K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.OID,!1,K.oidToDer(Li.pkcs5PBKDF2).getBytes()),C]),K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.OID,!1,K.oidToDer(l).getBytes()),K.create(K.Class.UNIVERSAL,K.Type.OCTETSTRING,!1,v)])])])}else if(r.algorithm==="3des"){o=24;var q=new te.util.ByteBuffer(n),g=Ee.pbe.generatePkcs12Key(e,q,1,i,o),v=Ee.pbe.generatePkcs12Key(e,q,2,i,o),w=te.des.createEncryptionCipher(g);w.start(v),w.update(K.toDer(t)),w.finish(),c=w.output.getBytes(),a=K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.OID,!1,K.oidToDer(Li["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[K.create(K.Class.UNIVERSAL,K.Type.OCTETSTRING,!1,n),K.create(K.Class.UNIVERSAL,K.Type.INTEGER,!1,s.getBytes())])])}else{var d=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw d.algorithm=r.algorithm,d}var W=K.create(K.Class.UNIVERSAL,K.Type.SEQUENCE,!0,[a,K.create(K.Class.UNIVERSAL,K.Type.OCTETSTRING,!1,c)]);return W};Ee.decryptPrivateKeyInfo=function(t,e){var r=null,n={},i=[];if(!K.validate(t,Z4,n,i)){var s=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=K.derToOid(n.encryptionOid),a=Ee.pbe.getCipher(o,n.encryptionParams,e),c=te.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(r=K.fromDer(a.output)),r};Ee.encryptedPrivateKeyToPem=function(t,e){var r={type:"ENCRYPTED PRIVATE KEY",body:K.toDer(t).getBytes()};return te.pem.encode(r,{maxline:e})};Ee.encryptedPrivateKeyFromPem=function(t){var e=te.pem.decode(t)[0];if(e.type!=="ENCRYPTED PRIVATE KEY"){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return K.fromDer(e.body)};Ee.encryptRsaPrivateKey=function(t,e,r){if(r=r||{},!r.legacy){var n=Ee.wrapRsaPrivateKey(Ee.privateKeyToAsn1(t));return n=Ee.encryptPrivateKeyInfo(n,e,r),Ee.encryptedPrivateKeyToPem(n)}var i,s,o,a;switch(r.algorithm){case"aes128":i="AES-128-CBC",o=16,s=te.random.getBytesSync(16),a=te.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",o=24,s=te.random.getBytesSync(16),a=te.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",o=32,s=te.random.getBytesSync(16),a=te.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",o=24,s=te.random.getBytesSync(8),a=te.des.createEncryptionCipher;break;case"des":i="DES-CBC",o=8,s=te.random.getBytesSync(8),a=te.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw c.algorithm=r.algorithm,c}var u=te.pbe.opensslDeriveBytes(e,s.substr(0,8),o),l=a(u);l.start(s),l.update(K.toDer(Ee.privateKeyToAsn1(t))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:te.util.bytesToHex(s).toUpperCase()},body:l.output.getBytes()};return te.pem.encode(f)};Ee.decryptRsaPrivateKey=function(t,e){var r=null,n=te.pem.decode(t)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var s,o;switch(n.dekInfo.algorithm){case"DES-CBC":s=8,o=te.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,o=te.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,o=te.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,o=te.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,o=te.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,o=function(f){return te.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":s=8,o=function(f){return te.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":s=16,o=function(f){return te.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=te.util.hexToBytes(n.dekInfo.parameters),c=te.pbe.opensslDeriveBytes(e,a.substr(0,8),s),u=o(c);if(u.start(a),u.update(te.util.createBuffer(n.body)),u.finish())r=u.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=Ee.decryptPrivateKeyInfo(K.fromDer(r),e):r=K.fromDer(r),r!==null&&(r=Ee.privateKeyFromAsn1(r)),r};Ee.pbe.generatePkcs12Key=function(t,e,r,n,i,s){var o,a;if(typeof s=="undefined"||s===null){if(!("sha1"in te.md))throw new Error('"sha1" hash algorithm unavailable.');s=te.md.sha1.create()}var c=s.digestLength,u=s.blockLength,l=new te.util.ByteBuffer,f=new te.util.ByteBuffer;if(t!=null){for(a=0;a=0;a--)be=be>>8,be+=ie.at(a)+ye.at(a),ye.setAt(a,be&255);Ae.putBuffer(ye)}q=Ae,l.putBuffer(M)}return l.truncate(l.length()-i),l};Ee.pbe.getCipher=function(t,e,r){switch(t){case Ee.oids.pkcs5PBES2:return Ee.pbe.getCipherForPBES2(t,e,r);case Ee.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case Ee.oids["pbewithSHAAnd40BitRC2-CBC"]:return Ee.pbe.getCipherForPKCS12PBE(t,e,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=t,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};Ee.pbe.getCipherForPBES2=function(t,e,r){var n={},i=[];if(!K.validate(e,J4,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(t=K.derToOid(n.kdfOid),t!==Ee.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=t,s.supportedOids=["pkcs5PBKDF2"],s}if(t=K.derToOid(n.encOid),t!==Ee.oids["aes128-CBC"]&&t!==Ee.oids["aes192-CBC"]&&t!==Ee.oids["aes256-CBC"]&&t!==Ee.oids["des-EDE3-CBC"]&&t!==Ee.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=t,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var o=n.kdfSalt,a=te.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(Ee.oids[t]){case"aes128-CBC":c=16,u=te.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=te.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=te.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=te.des.createDecryptionCipher;break;case"desCBC":c=8,u=te.des.createDecryptionCipher;break}var l=Jy(n.prfOid),f=te.pkcs5.pbkdf2(r,o,a,c,l),d=n.encIv,p=u(f);return p.start(d),p};Ee.pbe.getCipherForPKCS12PBE=function(t,e,r){var n={},i=[];if(!K.validate(e,eB,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=te.util.createBuffer(n.salt),a=te.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(t){case Ee.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=te.des.startDecrypting;break;case Ee.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(g,v){var w=te.rc2.createDecryptionCipher(g,40);return w.start(v,null),w};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=t,s}var f=Jy(n.prfOid),d=Ee.pbe.generatePkcs12Key(r,o,1,a,c,f);f.start();var p=Ee.pbe.generatePkcs12Key(r,o,2,a,u,f);return l(d,p)};Ee.pbe.opensslDeriveBytes=function(t,e,r,n){if(typeof n=="undefined"||n===null){if(!("md5"in te.md))throw new Error('"md5" hash algorithm unavailable.');n=te.md.md5.create()}e===null&&(e="");for(var i=[Zy(n,t+e)],s=16,o=1;srB});var rB,rg=Te(()=>{Xr();Un();rB=tc({prefix:"\0",name:"identity",encode:t=>L0(t),decode:t=>D0(t)})});var rf={};_t(rf,{base2:()=>nB});var nB,ng=Te(()=>{Xr();nB=pt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var nf={};_t(nf,{base8:()=>iB});var iB,ig=Te(()=>{Xr();iB=pt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var sf={};_t(sf,{base10:()=>sB});var sB,sg=Te(()=>{Xr();sB=Fn({prefix:"9",name:"base10",alphabet:"0123456789"})});var of,og,af=Te(()=>{Ai();of=({name:t,code:e,encode:r})=>new og(t,e,r),og=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Mn(this.code,r):r.then(n=>Mn(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var Zn={};_t(Zn,{sha256:()=>oB,sha512:()=>aB});var cg,oB,aB,ki=Te(()=>{af();cg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),oB=of({name:"sha2-256",code:18,encode:cg("SHA-256")}),aB=of({name:"sha2-512",code:19,encode:cg("SHA-512")})});var Qo={};_t(Qo,{identity:()=>lB});var ug,cB,lg,uB,lB,Rc=Te(()=>{Un();Ai();ug=0,cB="identity",lg=_n,uB=t=>Mn(ug,lg(t)),lB={code:ug,name:cB,encode:lg,digest:uB}});var fg=Te(()=>{Un()});var kU,qU,dg=Te(()=>{kU=new TextEncoder,qU=new TextDecoder});var hg=Te(()=>{Ss();ec();Un();af();Ai()});var cf,KU,pg=Te(()=>{rg();ng();ig();sg();vl();Ii();ml();Vn();Ko();ki();Rc();fg();dg();hg();cf={...tf,...rf,...nf,...sf,...sc,...Ci,...ic,...Kn,...xs},KU={...Zn,...Qo}});function yg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var gg,uf,hB,Bc,lf=Te(()=>{pg();gg=yg("utf8","u",t=>{let e=new TextDecoder("utf8");return"u"+e.decode(t)},t=>new TextEncoder().encode(t.substring(1))),uf=yg("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=new Uint8Array(t.length);for(let r=0;rff});function ff(t,e="utf8"){let r=Bc[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}var Dt=Te(()=>{lf()});var Jn={};_t(Jn,{concat:()=>pB});function pB(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var ei=Te(()=>{});var Xo=b(mg=>{"use strict";mg.get=(t=globalThis)=>{let e=t.crypto;if(!e||!e.subtle)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}});var df=b((GU,Eg)=>{"use strict";var{concat:yB}=(ei(),Jn),{fromString:vg}=(Dt(),Ft),gB=Xo();function mB({algorithm:t="AES-GCM",nonceLength:e=12,keyLength:r=16,digest:n="SHA-256",saltLength:i=16,iterations:s=32767}={}){let o=gB.get();r*=8;async function a(u,l){let f=o.getRandomValues(new Uint8Array(i)),d=o.getRandomValues(new Uint8Array(e)),p={name:t,iv:d},h={name:"PBKDF2",salt:f,iterations:s,hash:{name:n}},g=await o.subtle.importKey("raw",vg(l),{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),v=await o.subtle.deriveKey(h,g,{name:t,length:r},!0,["encrypt"]),w=await o.subtle.encrypt(p,v,u);return yB([f,p.iv,new Uint8Array(w)])}async function c(u,l){let f=u.slice(0,i),d=u.slice(i,i+e),p=u.slice(i+e),h={name:t,iv:d},g={name:"PBKDF2",salt:f,iterations:s,hash:{name:n}},v=await o.subtle.importKey("raw",vg(l),{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),w=await o.subtle.deriveKey(g,v,{name:t,length:r},!0,["decrypt"]),C=await o.subtle.decrypt(h,w,p);return new Uint8Array(C)}return{encrypt:a,decrypt:c}}Eg.exports={create:mB}});var wg=b((WU,bg)=>{"use strict";var{base64:vB}=(Ko(),xs),EB=df();bg.exports={import:async function(t,e){let r=vB.decode(t);return await EB.create().decrypt(r,e)}}});var _r={};_t(_r,{equals:()=>bB});function bB(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{});var Kt={};_t(Kt,{toString:()=>hf});function hf(t,e="utf8"){let r=Bc[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Lt=Te(()=>{lf()});var gf=b((QU,Ag)=>{var tt=_e();Yn();Qe();var Zo=Ag.exports=tt.sha512=tt.sha512||{};tt.md.sha512=tt.md.algorithms.sha512=Zo;var _g=tt.sha384=tt.sha512.sha384=tt.sha512.sha384||{};_g.create=function(){return Zo.create("SHA-384")};tt.md.sha384=tt.md.algorithms.sha384=_g;tt.sha512.sha256=tt.sha512.sha256||{create:function(){return Zo.create("SHA-512/256")}};tt.md["sha512/256"]=tt.md.algorithms["sha512/256"]=tt.sha512.sha256;tt.sha512.sha224=tt.sha512.sha224||{create:function(){return Zo.create("SHA-512/224")}};tt.md["sha512/224"]=tt.md.algorithms["sha512/224"]=tt.sha512.sha224;Zo.create=function(t){if(Sg||wB(),typeof t=="undefined"&&(t="SHA-512"),!(t in qi))throw new Error("Invalid SHA-512 algorithm: "+t);for(var e=qi[t],r=null,n=tt.util.createBuffer(),i=new Array(80),s=0;s<80;++s)i[s]=new Array(2);var o=64;switch(t){case"SHA-384":o=48;break;case"SHA-512/256":o=32;break;case"SHA-512/224":o=28;break}var a={algorithm:t.replace("-","").toLowerCase(),blockLength:128,digestLength:o,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),xg(r,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=tt.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(pf.substr(0,a.blockLength-l));for(var f,d,p=a.fullMessageLength[0]*8,h=0;h>>0,p+=d,c.putInt32(p>>>0),p=f>>>0;c.putInt32(p);for(var g=new Array(r.length),h=0;h=128;){for(Fe=0;Fe<16;++Fe)e[Fe][0]=r.getInt32()>>>0,e[Fe][1]=r.getInt32()>>>0;for(;Fe<80;++Fe)Jt=e[Fe-2],$e=Jt[0],se=Jt[1],n=(($e>>>19|se<<13)^(se>>>29|$e<<3)^$e>>>6)>>>0,i=(($e<<13|se>>>19)^(se<<3|$e>>>29)^($e<<26|se>>>6))>>>0,wn=e[Fe-15],$e=wn[0],se=wn[1],s=(($e>>>1|se<<31)^($e>>>8|se<<24)^$e>>>7)>>>0,o=(($e<<31|se>>>1)^($e<<24|se>>>8)^($e<<25|se>>>7))>>>0,Ot=e[Fe-7],er=e[Fe-16],se=i+Ot[1]+o+er[1],e[Fe][0]=n+Ot[0]+s+er[0]+(se/4294967296>>>0)>>>0,e[Fe][1]=se>>>0;for(g=t[0][0],v=t[0][1],w=t[1][0],C=t[1][1],q=t[2][0],W=t[2][1],F=t[3][0],M=t[3][1],re=t[4][0],ie=t[4][1],z=t[5][0],Ae=t[5][1],ye=t[6][0],be=t[6][1],ft=t[7][0],bt=t[7][1],Fe=0;Fe<80;++Fe)u=((re>>>14|ie<<18)^(re>>>18|ie<<14)^(ie>>>9|re<<23))>>>0,l=((re<<18|ie>>>14)^(re<<14|ie>>>18)^(ie<<23|re>>>9))>>>0,f=(ye^re&(z^ye))>>>0,d=(be^ie&(Ae^be))>>>0,a=((g>>>28|v<<4)^(v>>>2|g<<30)^(v>>>7|g<<25))>>>0,c=((g<<4|v>>>28)^(v<<30|g>>>2)^(v<<25|g>>>7))>>>0,p=(g&w|q&(g^w))>>>0,h=(v&C|W&(v^C))>>>0,se=bt+l+d+yf[Fe][1]+e[Fe][1],n=ft+u+f+yf[Fe][0]+e[Fe][0]+(se/4294967296>>>0)>>>0,i=se>>>0,se=c+h,s=a+p+(se/4294967296>>>0)>>>0,o=se>>>0,ft=ye,bt=be,ye=z,be=Ae,z=re,Ae=ie,se=M+i,re=F+n+(se/4294967296>>>0)>>>0,ie=se>>>0,F=q,M=W,q=w,W=C,w=g,C=v,se=i+o,g=n+s+(se/4294967296>>>0)>>>0,v=se>>>0;se=t[0][1]+v,t[0][0]=t[0][0]+g+(se/4294967296>>>0)>>>0,t[0][1]=se>>>0,se=t[1][1]+C,t[1][0]=t[1][0]+w+(se/4294967296>>>0)>>>0,t[1][1]=se>>>0,se=t[2][1]+W,t[2][0]=t[2][0]+q+(se/4294967296>>>0)>>>0,t[2][1]=se>>>0,se=t[3][1]+M,t[3][0]=t[3][0]+F+(se/4294967296>>>0)>>>0,t[3][1]=se>>>0,se=t[4][1]+ie,t[4][0]=t[4][0]+re+(se/4294967296>>>0)>>>0,t[4][1]=se>>>0,se=t[5][1]+Ae,t[5][0]=t[5][0]+z+(se/4294967296>>>0)>>>0,t[5][1]=se>>>0,se=t[6][1]+be,t[6][0]=t[6][0]+ye+(se/4294967296>>>0)>>>0,t[6][1]=se>>>0,se=t[7][1]+bt,t[7][0]=t[7][0]+ft+(se/4294967296>>>0)>>>0,t[7][1]=se>>>0,Qr-=128}}});var Ig=b((XU,Cg)=>{"use strict";var Pc=65536;function _B(t){let e=new Uint8Array(t),r=0;if(t>0)if(t>Pc)for(;rt?(crypto.getRandomValues(e.subarray(r,r+(t-r))),r+=t-r):(crypto.getRandomValues(e.subarray(r,r+Pc)),r+=Pc);else crypto.getRandomValues(e);return e}Cg.exports=_B});var Nc=b((ZU,Tg)=>{"use strict";var SB=Ig(),xB=ge();Tg.exports=function(t){if(isNaN(t)||t<=0)throw xB(new Error("random bytes length must be a Number bigger than 0"),"ERR_INVALID_LENGTH");return SB(t)}});var Oc=b(Jo=>{"use strict";Qe();Cc();var AB=_e(),{fromString:CB}=(Dt(),Ft),{toString:Rg}=(Lt(),Kt),{concat:Bg}=(ei(),Jn);Jo.bigIntegerToUintBase64url=(t,e)=>{let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.slice(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Bg([new Uint8Array(e-r.length),r])}return Rg(r,"base64url")};Jo.base64urlToBigInteger=t=>{let e=Jo.base64urlToBuffer(t);return new AB.jsbn.BigInteger(Rg(e,"base16"),16)};Jo.base64urlToBuffer=(t,e)=>{let r=CB(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Bg([new Uint8Array(e-r.length),r])}return r}});var Og=b(ea=>{"use strict";Wn();Yo();var ti=_e(),{bigIntegerToUintBase64url:cn,base64urlToBigInteger:un}=Oc(),{fromString:Pg}=(Dt(),Ft),{toString:Ng}=(Lt(),Kt);ea.pkcs1ToJwk=function(t){let e=ti.asn1.fromDer(Ng(t,"ascii")),r=ti.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:cn(r.n),e:cn(r.e),d:cn(r.d),p:cn(r.p),q:cn(r.q),dp:cn(r.dP),dq:cn(r.dQ),qi:cn(r.qInv),alg:"RS256",kid:"2011-04-29"}};ea.jwkToPkcs1=function(t){let e=ti.pki.privateKeyToAsn1({n:un(t.n),e:un(t.e),d:un(t.d),p:un(t.p),q:un(t.q),dP:un(t.dp),dQ:un(t.dq),qInv:un(t.qi)});return Pg(ti.asn1.toDer(e).getBytes(),"ascii")};ea.pkixToJwk=function(t){let e=ti.asn1.fromDer(Ng(t,"ascii")),r=ti.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:cn(r.n),e:cn(r.e),alg:"RS256",kid:"2011-04-29"}};ea.jwkToPkix=function(t){let e=ti.pki.publicKeyToAsn1({n:un(t.n),e:un(t.e)});return Pg(ti.asn1.toDer(e).getBytes(),"ascii")}});var qg=b((tM,kg)=>{"use strict";Yo();var Dg=_e(),{base64urlToBigInteger:IB}=Oc();function Lg(t,e){return e.map(r=>IB(t[r]))}function TB(t){return Dg.pki.setRsaPrivateKey(...Lg(t,["n","e","d","p","q","dp","dq","qi"]))}function RB(t){return Dg.pki.setRsaPublicKey(...Lg(t,["n","e"]))}kg.exports={jwk2pub:RB,jwk2priv:TB}});var Fg=b(Tn=>{"use strict";var In=Xo(),BB=Nc(),{toString:PB}=(Lt(),Kt),{fromString:NB}=(Dt(),Ft);Tn.utils=Og();Tn.generateKey=async function(t){let e=await In.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Ug(e);return{privateKey:r[0],publicKey:r[1]}};Tn.unmarshalPrivateKey=async function(t){let r=[await In.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await OB(t)],n=await Ug({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}};Tn.getRandomValues=BB;Tn.hashAndSign=async function(t,e){let r=await In.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await In.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,n.byteOffset,n.byteLength)};Tn.hashAndVerify=async function(t,e,r){let n=await In.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return In.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)};function Ug(t){return Promise.all([In.get().subtle.exportKey("jwk",t.privateKey),In.get().subtle.exportKey("jwk",t.publicKey)])}function OB(t){return In.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}var{jwk2pub:DB,jwk2priv:LB}=qg();function Mg(t,e,r,n){let i=e?DB(t):LB(t),s=PB(Uint8Array.from(r),"ascii"),o=n(s,i);return NB(o,"ascii")}Tn.encrypt=function(t,e){return Mg(t,!0,e,(r,n)=>n.encrypt(r))};Tn.decrypt=function(t,e){return Mg(t,!1,e,(r,n)=>n.decrypt(r))}});var Dc=b((nM,Kg)=>{"use strict";var{base64:kB}=(Ko(),xs),qB=df();Kg.exports={export:async function(t,e){let n=await qB.create().encrypt(t,e);return kB.encode(n)}}});var zg=b((iM,Hg)=>{"use strict";var{sha256:Vg}=(ki(),Zn),jg=ge(),{equals:$g}=(Sr(),_r),{toString:UB}=(Lt(),Kt);gf();var Lc=_e(),xr=Fg(),kc=fc(),MB=Dc(),qc=class{constructor(e){this._key=e}async verify(e,r){return xr.hashAndVerify(this._key,r,e)}marshal(){return xr.utils.jwkToPkix(this._key)}get bytes(){return kc.PublicKey.encode({Type:kc.KeyType.RSA,Data:this.marshal()}).finish()}encrypt(e){return xr.encrypt(this._key,e)}equals(e){return $g(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Vg.digest(this.bytes);return e}},ta=class{constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return xr.getRandomValues(16)}async sign(e){return xr.hashAndSign(this._key,e)}get public(){if(!this._publicKey)throw jg(new Error("public key not provided"),"ERR_PUBKEY_NOT_PROVIDED");return new qc(this._publicKey)}decrypt(e){return xr.decrypt(this._key,e)}marshal(){return xr.utils.jwkToPkcs1(this._key)}get bytes(){return kc.PrivateKey.encode({Type:kc.KeyType.RSA,Data:this.marshal()}).finish()}equals(e){return $g(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Vg.digest(this.bytes);return e}async id(){let e=await this.public.hash();return UB(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new Lc.util.ByteBuffer(this.marshal()),i=Lc.asn1.fromDer(n),s=Lc.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Lc.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return MB.export(this.bytes,e);throw jg(new Error(`export format '${r}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}}};async function FB(t){let e=xr.utils.pkcs1ToJwk(t),r=await xr.unmarshalPrivateKey(e);return new ta(r.privateKey,r.publicKey)}function KB(t){let e=xr.utils.pkixToJwk(t);return new qc(e)}async function VB(t){let e=await xr.unmarshalPrivateKey(t);return new ta(e.privateKey,e.publicKey)}async function jB(t){let e=await xr.generateKey(t);return new ta(e.privateKey,e.publicKey)}Hg.exports={RsaPublicKey:qc,RsaPrivateKey:ta,unmarshalRsaPublicKey:KB,unmarshalRsaPrivateKey:FB,generateKeyPair:jB,fromJwk:VB}});var rm=b(qe=>{"use strict";var $B=qe&&qe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qe,"__esModule",{value:!0});qe.utils=qe.curve25519=qe.getSharedSecret=qe.verify=qe.sign=qe.getPublicKey=qe.Signature=qe.Point=qe.RistrettoPoint=qe.ExtendedPoint=qe.CURVE=void 0;var HB=$B(Bs()),dt=BigInt(0),xe=BigInt(1),kt=BigInt(2),Gg=BigInt(255),Wg=kt**BigInt(252)+BigInt("27742317777372353535851937790883648493"),Ge={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:kt**Gg-BigInt(19),l:Wg,n:Wg,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")};qe.CURVE=Ge;var Yg=kt**BigInt(256),ra=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),sM=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),zB=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),GB=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),WB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),YB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Pe=class{constructor(e,r,n,i){this.x=e,this.y=r,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof ot))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(ot.ZERO)?Pe.ZERO:new Pe(e.x,e.y,xe,j(e.x*e.y))}static toAffineBatch(e){let r=ZB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){Qg(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=j(r*a),u=j(s*i),l=j(n*a),f=j(o*i);return c===u&&l===f}negate(){return new Pe(j(-this.x),this.y,this.z,j(-this.t))}double(){let{x:e,y:r,z:n}=this,{a:i}=Ge,s=j(e**kt),o=j(r**kt),a=j(kt*j(n**kt)),c=j(i*s),u=j(j((e+r)**kt)-s-o),l=c+o,f=l-a,d=c-o,p=j(u*f),h=j(l*d),g=j(u*d),v=j(f*l);return new Pe(p,h,v,g)}add(e){Qg(e);let{x:r,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=j((n-r)*(a+o)),f=j((n+r)*(a-o)),d=j(f-l);if(d===dt)return this.double();let p=j(i*kt*u),h=j(s*kt*c),g=h+p,v=f+l,w=h-p,C=j(g*d),q=j(v*w),W=j(g*w),F=j(d*v);return new Pe(C,q,F,W)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let r=1+256/e,n=[],i=this,s=i;for(let o=0;o>=f,h>c&&(h-=l,e+=xe),h===0){let g=i[p];d%2&&(g=g.negate()),o=o.add(g)}else{let g=i[p+Math.abs(h)-1];h<0&&(g=g.negate()),s=s.add(g)}}return Pe.normalizeZ([s,o])[0]}multiply(e,r){return this.wNAF(Ds(e,Ge.l),r)}multiplyUnsafe(e){let r=Ds(e,Ge.l,!1),n=Pe.BASE,i=Pe.ZERO;if(r===dt)return i;if(this.equals(i)||r===xe)return this;if(this.equals(n))return this.wNAF(r);let s=i,o=this;for(;r>dt;)r&xe&&(s=s.add(o)),o=o.double(),r>>=xe;return s}isSmallOrder(){return this.multiplyUnsafe(Ge.h).equals(Pe.ZERO)}isTorsionFree(){return this.multiplyUnsafe(Ge.l).equals(Pe.ZERO)}toAffine(e=Uc(this.z)){let{x:r,y:n,z:i}=this,s=j(r*e),o=j(n*e);if(j(i*e)!==xe)throw new Error("invZ was invalid");return new ot(s,o)}fromRistrettoBytes(){vf()}toRistrettoBytes(){vf()}fromRistrettoHash(){vf()}};qe.ExtendedPoint=Pe;Pe.BASE=new Pe(Ge.Gx,Ge.Gy,xe,j(Ge.Gx*Ge.Gy));Pe.ZERO=new Pe(dt,xe,xe,dt);function Qg(t){if(!(t instanceof Pe))throw new TypeError("ExtendedPoint expected")}function mf(t){if(!(t instanceof sr))throw new TypeError("RistrettoPoint expected")}function vf(){throw new Error("Legacy method: switch to RistrettoPoint")}var sr=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:r}=Ge,n=j(ra*e*e),i=j((n+xe)*WB),s=BigInt(-1),o=j((s-r*n)*j(n+r)),{isValid:a,value:c}=wf(i,o),u=j(c*e);ri(u)||(u=j(-u)),a||(c=u),a||(s=n);let l=j(s*(n-xe)*YB-o),f=c*c,d=j((c+c)*o),p=j(l*zB),h=j(xe-f),g=j(xe+f);return new Pe(j(d*g),j(h*p),j(p*g),j(d*h))}static hashToCurve(e){e=ln(e,64);let r=bf(e.slice(0,32)),n=this.calcElligatorRistrettoMap(r),i=bf(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new sr(n.add(s))}static fromHex(e){e=ln(e,32);let{a:r,d:n}=Ge,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=bf(e);if(!JB(Os(s),e)||ri(s))throw new Error(i);let o=j(s*s),a=j(xe+r*o),c=j(xe-r*o),u=j(a*a),l=j(c*c),f=j(r*n*u-l),{isValid:d,value:p}=em(j(f*l)),h=j(p*c),g=j(p*h*f),v=j((s+s)*h);ri(v)&&(v=j(-v));let w=j(a*g),C=j(v*w);if(!d||ri(C)||w===dt)throw new Error(i);return new sr(new Pe(v,w,xe,C))}toRawBytes(){let{x:e,y:r,z:n,t:i}=this.ep,s=j(j(n+r)*j(n-r)),o=j(e*r),{value:a}=em(j(s*o**kt)),c=j(a*s),u=j(a*o),l=j(c*u*i),f;if(ri(i*l)){let p=j(r*ra),h=j(e*ra);e=p,r=h,f=j(c*GB)}else f=u;ri(e*l)&&(r=j(-r));let d=j((n-r)*f);return ri(d)&&(d=j(-d)),Os(d)}toHex(){return na(this.toRawBytes())}toString(){return this.toHex()}equals(e){mf(e);let r=this.ep,n=e.ep,i=j(r.x*n.y)===j(r.y*n.x),s=j(r.y*n.y)===j(r.x*n.x);return i||s}add(e){return mf(e),new sr(this.ep.add(e.ep))}subtract(e){return mf(e),new sr(this.ep.subtract(e.ep))}multiply(e){return new sr(this.ep.multiply(e))}multiplyUnsafe(e){return new sr(this.ep.multiplyUnsafe(e))}};qe.RistrettoPoint=sr;sr.BASE=new sr(Pe.BASE);sr.ZERO=new sr(Pe.ZERO);var Ef=new WeakMap,ot=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Ef.delete(this)}static fromHex(e,r=!0){let{d:n,P:i}=Ge;e=ln(e,32);let s=e.slice();s[31]=e[31]&~128;let o=ni(s);if(r&&o>=i)throw new Error("Expected 0 < hex < P");if(!r&&o>=Yg)throw new Error("Expected 0 < hex < 2**256");let a=j(o*o),c=j(a-xe),u=j(n*a+xe),{isValid:l,value:f}=wf(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let d=(f&xe)===xe;return(e[31]&128)!=0!==d&&(f=j(-f)),new ot(f,o)}static async fromPrivateKey(e){return(await ia(e)).point}toRawBytes(){let e=Os(this.y);return e[31]|=this.x&xe?128:0,e}toHex(){return na(this.toRawBytes())}toX25519(){let{y:e}=this,r=j((xe+e)*Uc(xe-e));return Os(r)}isTorsionFree(){return Pe.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new ot(j(-this.x),this.y)}add(e){return Pe.fromAffine(this).add(Pe.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Pe.fromAffine(this).multiply(e,this).toAffine()}};qe.Point=ot;ot.BASE=new ot(Ge.Gx,Ge.Gy);ot.ZERO=new ot(dt,xe);var Ui=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=ln(e,64),n=ot.fromHex(r.slice(0,32),!1),i=ni(r.slice(32,64));return new Ui(n,i)}assertValidity(){let{r:e,s:r}=this;if(!(e instanceof ot))throw new Error("Expected Point instance");return Ds(r,Ge.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Os(this.s),32),e}toHex(){return na(this.toRawBytes())}};qe.Signature=Ui;function QB(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function na(t){if(!(t instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let r=0;r=dt?r:e+r}function Uc(t,e=Ge.P){if(t===dt||e<=dt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=j(t,e),n=e,i=dt,s=xe,o=xe,a=dt;for(;r!==dt;){let u=n/r,l=n%r,f=i-o*u,d=s-a*u;n=r,r=l,i=o,s=a,o=f,a=d}if(n!==xe)throw new Error("invert: does not exist");return j(i,e)}function ZB(t,e=Ge.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===dt?s:(r[a]=s,j(s*o,e)),xe),i=Uc(n,e);return t.reduceRight((s,o,a)=>o===dt?s:(r[a]=j(s*r[a],e),j(s*o,e)),i),r}function Vr(t,e){let{P:r}=Ge,n=t;for(;e-- >dt;)n*=n,n%=r;return n}function Jg(t){let{P:e}=Ge,r=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=t*t%e*t%e,u=Vr(c,kt)*c%e,l=Vr(u,xe)*t%e,f=Vr(l,r)*l%e,d=Vr(f,n)*f%e,p=Vr(d,i)*d%e,h=Vr(p,s)*p%e,g=Vr(h,o)*h%e,v=Vr(g,o)*h%e,w=Vr(v,n)*f%e;return{pow_p_5_8:Vr(w,kt)*t%e,b2:c}}function wf(t,e){let r=j(e*e*e),n=j(r*r*e),i=Jg(t*n).pow_p_5_8,s=j(t*r*i),o=j(e*s*s),a=s,c=j(s*ra),u=o===t,l=o===j(-t),f=o===j(-t*ra);return u&&(s=a),(l||f)&&(s=c),ri(s)&&(s=j(-s)),{isValid:u||l,value:s}}function em(t){return wf(xe,t)}async function _f(...t){let e=await qe.utils.sha512(QB(...t)),r=ni(e);return j(r,Ge.l)}function JB(t,e){if(t.length!==e.length)return!1;for(let r=0;r=dt;v--){let w=i>>v&xe;f^=w,d=Mc(f,a,u),a=d[0],u=d[1],d=Mc(f,c,l),c=d[0],l=d[1],f=w;let C=a+c,q=j(C*C),W=a-c,F=j(W*W),M=q-F,re=u+l,ie=u-l,z=j(ie*C),Ae=j(re*W);u=j((z+Ae)**kt),l=j(o*(z-Ae)**kt),a=j(q*F),c=j(M*(q+j(s*M)))}d=Mc(f,a,u),a=d[0],u=d[1],d=Mc(f,c,l),c=d[0],l=d[1];let{pow_p_5_8:p,b2:h}=Jg(c),g=j(Vr(p,BigInt(3))*h);return j(a*g)}function o8(t){return Os(j(t,Ge.P))}function a8(t){let e=ln(t,32);return e[31]&=127,ni(e)}qe.curve25519={BASE_POINT_U:"0900000000000000000000000000000000000000000000000000000000000000",scalarMult(t,e){let r=a8(e),n=e8(t),i=s8(r,n);if(i===dt)throw new Error("Invalid private or public key received");return o8(i)},scalarMultBase(t){return qe.curve25519.scalarMult(t,qe.curve25519.BASE_POINT_U)}};var ii={node:HB.default,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};qe.utils={TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],bytesToHex:na,getExtendedPublicKey:ia,mod:j,invert:Uc,hashToPrivateScalar:t=>{if(t=ln(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");let e=j(ni(t),Ge.l);if(e===dt||e===xe)throw new Error("Invalid private key");return e},randomBytes:(t=32)=>{if(ii.web)return ii.web.getRandomValues(new Uint8Array(t));if(ii.node){let{randomBytes:e}=ii.node;return new Uint8Array(e(t).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>qe.utils.randomBytes(32),sha512:async t=>{if(ii.web){let e=await ii.web.subtle.digest("SHA-512",t.buffer);return new Uint8Array(e)}else{if(ii.node)return Uint8Array.from(ii.node.createHash("sha512").update(t).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(t=8,e=ot.BASE){let r=e.equals(ot.BASE)?e:new ot(e.x,e.y);return r._setWindowSize(t),r.multiply(kt),r}}});var im=b(si=>{"use strict";var sa=rm(),c8=32,u8=64,Fc=32;si.publicKeyLength=c8;si.privateKeyLength=u8;si.generateKey=async function(){let t=sa.utils.randomPrivateKey(),e=await sa.getPublicKey(t);return{privateKey:nm(t,e),publicKey:e}};si.generateKeyFromSeed=async function(t){if(t.length!==Fc)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=await sa.getPublicKey(e);return{privateKey:nm(e,r),publicKey:r}};si.hashAndSign=function(t,e){let r=t.slice(0,Fc);return sa.sign(e,r)};si.hashAndVerify=function(t,e,r){return sa.verify(e,r,t)};function nm(t,e){let r=new Uint8Array(si.privateKeyLength);for(let n=0;n{"use strict";var sm=ge(),{equals:om}=(Sr(),_r),{sha256:am}=(ki(),Zn),{base58btc:l8}=(Vn(),Kn),{identity:f8}=(Rc(),Qo),Vt=im(),Kc=fc(),d8=Dc(),Vc=class{constructor(e){this._key=ks(e,Vt.publicKeyLength)}async verify(e,r){return Vt.hashAndVerify(this._key,r,e)}marshal(){return this._key}get bytes(){return Kc.PublicKey.encode({Type:Kc.KeyType.Ed25519,Data:this.marshal()}).finish()}equals(e){return om(this.bytes,e.bytes)}async hash(){let{bytes:e}=await am.digest(this.bytes);return e}},Ls=class{constructor(e,r){this._key=ks(e,Vt.privateKeyLength),this._publicKey=ks(r,Vt.publicKeyLength)}async sign(e){return Vt.hashAndSign(this._key,e)}get public(){return new Vc(this._publicKey)}marshal(){return this._key}get bytes(){return Kc.PrivateKey.encode({Type:Kc.KeyType.Ed25519,Data:this.marshal()}).finish()}equals(e){return om(this.bytes,e.bytes)}async hash(){let{bytes:e}=await am.digest(this.bytes);return e}async id(){let e=await f8.digest(this.public.bytes);return l8.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return d8.export(this.bytes,e);throw sm(new Error(`export format '${r}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}};function h8(t){if(t.length>Vt.privateKeyLength){t=ks(t,Vt.privateKeyLength+Vt.publicKeyLength);let n=t.slice(0,Vt.privateKeyLength),i=t.slice(Vt.privateKeyLength,t.length);return new Ls(n,i)}t=ks(t,Vt.privateKeyLength);let e=t.slice(0,Vt.privateKeyLength),r=t.slice(Vt.publicKeyLength);return new Ls(e,r)}function p8(t){return t=ks(t,Vt.publicKeyLength),new Vc(t)}async function y8(){let{privateKey:t,publicKey:e}=await Vt.generateKey();return new Ls(t,e)}async function g8(t){let{privateKey:e,publicKey:r}=await Vt.generateKeyFromSeed(t);return new Ls(e,r)}function ks(t,e){if(t=Uint8Array.from(t||[]),t.length!==e)throw sm(new Error(`Key must be a Uint8Array of length ${e}, got ${t.length}`),"ERR_INVALID_KEY_TYPE");return t}cm.exports={Ed25519PublicKey:Vc,Ed25519PrivateKey:Ls,unmarshalEd25519PrivateKey:h8,unmarshalEd25519PublicKey:p8,generateKeyPair:y8,generateKeyPairFromSeed:g8}});var Cm=b(Re=>{"use strict";var m8=Re&&Re.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Re,"__esModule",{value:!0});Re.utils=Re.schnorr=Re.verify=Re.signSync=Re.sign=Re.getSharedSecret=Re.recoverPublicKey=Re.getPublicKey=Re.Signature=Re.Point=Re.CURVE=void 0;var v8=m8(Bs()),Ie=BigInt(0),rt=BigInt(1),vt=BigInt(2),oa=BigInt(3),E8=BigInt(8),Sf=vt**BigInt(256),We={a:Ie,b:BigInt(7),P:Sf-vt**BigInt(32)-BigInt(977),n:Sf-BigInt("432420386565659656852420866394968145599"),h:rt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")};Re.CURVE=We;function lm(t){let{a:e,b:r}=We,n=ee(t*t),i=ee(n*t);return ee(i+e*t+r)}var jc=We.a===Ie,Ue=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof Me))throw new TypeError("JacobianPoint#fromAffine: expected Point");return new Ue(e.x,e.y,rt)}static toAffineBatch(e){let r=S8(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return Ue.toAffineBatch(e).map(Ue.fromAffine)}equals(e){if(!(e instanceof Ue))throw new TypeError("JacobianPoint expected");let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=ee(i**vt),u=ee(a**vt),l=ee(r*u),f=ee(s*c),d=ee(ee(n*a)*u),p=ee(ee(o*i)*c);return l===f&&d===p}negate(){return new Ue(this.x,ee(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=ee(e**vt),s=ee(r**vt),o=ee(s**vt),a=ee(vt*(ee((e+s)**vt)-i-o)),c=ee(oa*i),u=ee(c**vt),l=ee(u-vt*a),f=ee(c*(a-l)-E8*o),d=ee(vt*r*n);return new Ue(l,f,d)}add(e){if(!(e instanceof Ue))throw new TypeError("JacobianPoint expected");let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Ie||o===Ie)return this;if(r===Ie||n===Ie)return e;let c=ee(i**vt),u=ee(a**vt),l=ee(r*u),f=ee(s*c),d=ee(ee(n*a)*u),p=ee(ee(o*i)*c),h=ee(f-l),g=ee(p-d);if(h===Ie)return g===Ie?this.double():Ue.ZERO;let v=ee(h**vt),w=ee(h*v),C=ee(l*v),q=ee(g**vt-w-vt*C),W=ee(g*(C-q)-d*w),F=ee(i*a*h);return new Ue(q,W,F)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=hm(e),n=Ue.BASE,i=Ue.ZERO;if(r===Ie)return i;if(r===rt)return this;if(!jc){let d=i,p=this;for(;r>Ie;)r&rt&&(d=d.add(p)),p=p.double(),r>>=rt;return d}let{k1neg:s,k1:o,k2neg:a,k2:c}=ym(r),u=i,l=i,f=this;for(;o>Ie||c>Ie;)o&rt&&(u=u.add(f)),c&rt&&(l=l.add(f)),f=f.double(),o>>=rt,c>>=rt;return s&&(u=u.negate()),a&&(l=l.negate()),l=new Ue(ee(l.x*We.beta),l.y,l.z),u.add(l)}precomputeWindow(e){let r=jc?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o>=f,h>c&&(h-=l,e+=rt),h===0){let g=i[p];d%2&&(g=g.negate()),o=o.add(g)}else{let g=i[p+Math.abs(h)-1];h<0&&(g=g.negate()),s=s.add(g)}}return{p:s,f:o}}multiply(e,r){let n=hm(e),i,s;if(jc){let{k1neg:o,k1:a,k2neg:c,k2:u}=ym(n),{p:l,f}=this.wNAF(a,r),{p:d,f:p}=this.wNAF(u,r);o&&(l=l.negate()),c&&(d=d.negate()),d=new Ue(ee(d.x*We.beta),d.y,d.z),i=l.add(d),s=f.add(p)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return Ue.normalizeZ([i,s])[0]}toAffine(e=ua(this.z)){let{x:r,y:n,z:i}=this,s=e,o=ee(s*s),a=ee(o*s),c=ee(r*o),u=ee(n*a);if(ee(i*s)!==rt)throw new Error("invZ was invalid");return new Me(c,u)}};Ue.BASE=new Ue(We.Gx,We.Gy,rt);Ue.ZERO=new Ue(Ie,rt,Ie);var xf=new WeakMap,Me=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,xf.delete(this)}static fromCompressedHex(e){let r=e.length===32,n=Ar(r?e:e.subarray(1));if(!zc(n))throw new Error("Point is not on curve");let i=lm(n),s=_8(i),o=(s&rt)===rt;r?o&&(s=ee(-s)):(e[0]&1)==1!==o&&(s=ee(-s));let a=new Me(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=Ar(e.subarray(1,33)),n=Ar(e.subarray(33,65)),i=new Me(r,n);return i.assertValidity(),i}static fromHex(e){let r=dn(e),n=r.length,i=r[0];if(n===32||n===33&&(i===2||i===3))return this.fromCompressedHex(r);if(n===65&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Me.BASE.multiply(Ms(e))}static fromSignature(e,r,n){e=dn(e);let i=gm(e),{r:s,s:o}=vm(r);if(n!==0&&n!==1)throw new Error("Cannot recover signature: invalid recovery bit");if(i===Ie)throw new Error("Cannot recover signature: msgHash cannot be 0");let a=n&1?"03":"02",c=Me.fromHex(a+Rn(s)),{n:u}=We,l=ua(s,u),f=ee(-i*l,u),d=ee(o*l,u),p=Me.BASE.multiplyAndAddUnsafe(c,f,d);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return oi(this.toHex(e))}toHex(e=!1){let r=Rn(this.x);return e?`${this.y&rt?"03":"02"}${r}`:`04${r}${Rn(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!zc(r)||!zc(n))throw new Error(e);let i=ee(n*n),s=lm(r);if(ee(i-s)!==Ie)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Me(this.x,ee(-this.y))}double(){return Ue.fromAffine(this).double().toAffine()}add(e){return Ue.fromAffine(this).add(Ue.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ue.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let s=Ue.fromAffine(this).multiply(r),o=Ue.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(Ue.ZERO)?void 0:a.toAffine()}};Re.Point=Me;Me.BASE=new Me(We.Gx,We.Gy);Me.ZERO=new Me(Ie,Ie);function fm(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function dm(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${qs(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Ar(r),left:t.subarray(e+2)}}function b8(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${qs(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=dm(t.subarray(2)),{data:n,left:i}=dm(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${qs(i)}`);return{r:e,s:n}}var fn=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=aa(e),n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?qs(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new fn($c(i.slice(0,64)),$c(i.slice(64,128)))}static fromDER(e){let r=aa(e);if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=b8(r?e:oi(e));return new fn(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!Us(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Us(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=We.n>>rt;return this.s>e}normalizeS(){return this.hasHighS()?new fn(this.r,We.n-this.s):this}toDERRawBytes(e=!1){return oi(this.toDERHex(e))}toDERHex(e=!1){let r=fm(ca(this.s));if(e)return r;let n=fm(ca(this.r)),i=ca(n.length/2),s=ca(r.length/2);return`30${ca(n.length/2+r.length/2+4)}02${i}${n}02${s}${r}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return oi(this.toCompactHex())}toCompactHex(){return Rn(this.r)+Rn(this.s)}};Re.Signature=fn;function Af(...t){if(!t.every(aa))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function qs(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;rSf)throw new Error("Expected number < 2^256");return t.toString(16).padStart(64,"0")}function Cf(t){return oi(Rn(t))}function ca(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function $c(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function oi(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r0)return BigInt(t);if(typeof t=="bigint"&&Us(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function ee(t,e=We.P){let r=t%e;return r>=Ie?r:e+r}function Cr(t,e){let{P:r}=We,n=t;for(;e-- >Ie;)n*=n,n%=r;return n}function _8(t){let{P:e}=We,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,l=Cr(u,oa)*u%e,f=Cr(l,oa)*u%e,d=Cr(f,vt)*c%e,p=Cr(d,n)*d%e,h=Cr(p,i)*p%e,g=Cr(h,o)*h%e,v=Cr(g,a)*g%e,w=Cr(v,o)*h%e,C=Cr(w,oa)*u%e,q=Cr(C,s)*p%e,W=Cr(q,r)*c%e;return Cr(W,vt)}function ua(t,e=We.P){if(t===Ie||e<=Ie)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=ee(t,e),n=e,i=Ie,s=rt,o=rt,a=Ie;for(;r!==Ie;){let u=n/r,l=n%r,f=i-o*u,d=s-a*u;n=r,r=l,i=o,s=a,o=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return ee(i,e)}function S8(t,e=We.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===Ie?s:(r[a]=s,ee(s*o,e)),rt),i=ua(n,e);return t.reduceRight((s,o,a)=>o===Ie?s:(r[a]=ee(s*r[a],e),ee(s*o,e)),i),r}var pm=(t,e)=>(t+e/vt)/e,Hc=vt**BigInt(128);function ym(t){let{n:e}=We,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-rt*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=pm(s*t,e),a=pm(-n*t,e),c=ee(t-o*r-a*i,e),u=ee(-o*n-a*s,e),l=c>Hc,f=u>Hc;if(l&&(c=e-c),f&&(u=e-u),c>Hc||u>Hc)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:l,k1:c,k2neg:f,k2:u}}function gm(t){let{n:e}=We,n=t.length*8-256,i=Ar(t);return n>0&&(i=i>>BigInt(n)),i>=e&&(i-=e),i}var If=class{constructor(){this.v=new Uint8Array(32).fill(1),this.k=new Uint8Array(32).fill(0),this.counter=0}hmac(...e){return Re.utils.hmacSha256(this.k,...e)}hmacSync(...e){if(typeof Re.utils.hmacSha256Sync!="function")throw new Error("utils.hmacSha256Sync is undefined, you need to set it");let r=Re.utils.hmacSha256Sync(this.k,...e);if(r instanceof Promise)throw new Error("To use sync sign(), ensure utils.hmacSha256 is sync");return r}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){return this.incr(),this.v=await this.hmac(this.v),this.v}generateSync(){return this.incr(),this.v=this.hmacSync(this.v),this.v}};function Us(t){return Ie0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==64)throw new Error("Expected 32 bytes of private key");e=$c(t)}else if(aa(t)){if(t.length!==32)throw new Error("Expected 32 bytes of private key");e=Ar(t)}else throw new TypeError("Expected valid private key");if(!Us(e))throw new Error("Expected private key: 0 < key < n");return e}function Tf(t){return t instanceof Me?(t.assertValidity(),t):Me.fromHex(t)}function vm(t){if(t instanceof fn)return t.assertValidity(),t;try{return fn.fromDER(t)}catch(e){return fn.fromCompact(t)}}function x8(t,e=!1){return Me.fromPrivateKey(t).toRawBytes(e)}Re.getPublicKey=x8;function A8(t,e,r,n=!1){return Me.fromSignature(t,e,r).toRawBytes(n)}Re.recoverPublicKey=A8;function Em(t){let e=aa(t),r=typeof t=="string",n=(e||r)&&t.length;return e?n===33||n===65:r?n===66||n===130:t instanceof Me}function C8(t,e,r=!1){if(Em(t))throw new TypeError("getSharedSecret: first arg must be private key");if(!Em(e))throw new TypeError("getSharedSecret: second arg must be public key");let n=Tf(e);return n.assertValidity(),n.multiply(Ms(t)).toRawBytes(r)}Re.getSharedSecret=C8;function bm(t){let e=t.length>32?t.slice(0,32):t;return Ar(e)}function I8(t){let e=bm(t),r=ee(e,We.n);return wm(rs.charCodeAt(0))),n=await Re.utils.sha256(r),i=await Re.utils.sha256(Af(n,n,...e));return Ar(i)}async function xm(t,e,r){let n=Cf(t),i=await Rf("BIP0340/challenge",n,e.toRawX(),r);return ee(i,We.n)}function Bf(t){return(t.y&rt)===Ie}var Mi=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=dn(e);if(r.length!==64)throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${r.length}`);let n=Ar(r.subarray(0,32)),i=Ar(r.subarray(32,64));return new Mi(n,i)}assertValidity(){let{r:e,s:r}=this;if(!zc(e)||!Us(r))throw new Error("Invalid signature")}toHex(){return Rn(this.r)+Rn(this.s)}toRawBytes(){return oi(this.toHex())}};function N8(t){return Me.fromPrivateKey(t).toRawX()}async function O8(t,e,r=Re.utils.randomBytes()){if(t==null)throw new TypeError(`sign: Expected valid message, not "${t}"`);let{n}=We,i=dn(t),s=Ms(e),o=dn(r);if(o.length!==32)throw new TypeError("sign: Expected 32 bytes of aux randomness");let a=Me.fromPrivateKey(s),c=Bf(a)?s:n-s,u=await Rf("BIP0340/aux",o),l=c^u,f=await Rf("BIP0340/nonce",Cf(l),a.toRawX(),i),d=ee(f,n);if(d===Ie)throw new Error("sign: Creation of signature failed. k is zero");let p=Me.fromPrivateKey(d),h=Bf(p)?d:n-d,g=await xm(p.x,a,i),v=new Mi(p.x,ee(h+g*c,n)).toRawBytes();if(!await Am(v,i,a.toRawX()))throw new Error("sign: Invalid signature produced");return v}async function Am(t,e,r){let n=t instanceof Mi,i;try{i=n?t:Mi.fromHex(t),n&&i.assertValidity()}catch(f){return!1}let{r:s,s:o}=i,a=dn(e),c;try{c=Tf(r)}catch(f){return!1}let u=await xm(s,c,a),l=Me.BASE.multiplyAndAddUnsafe(c,Ms(o),ee(-u,We.n));return!(!l||!Bf(l)||l.x!==s)}Re.schnorr={Signature:Mi,getPublicKey:N8,sign:O8,verify:Am};Me.BASE._setWindowSize(8);var lr={node:v8.default,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};Re.utils={isValidPrivateKey(t){try{return Ms(t),!0}catch(e){return!1}},hashToPrivateKey:t=>{if(t=dn(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");let e=ee(Ar(t),We.n);if(e===Ie||e===rt)throw new Error("Invalid private key");return Cf(e)},randomBytes:(t=32)=>{if(lr.web)return lr.web.getRandomValues(new Uint8Array(t));if(lr.node){let{randomBytes:e}=lr.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Re.utils.hashToPrivateKey(Re.utils.randomBytes(40)),bytesToHex:qs,mod:ee,sha256:async t=>{if(lr.web){let e=await lr.web.subtle.digest("SHA-256",t.buffer);return new Uint8Array(e)}else if(lr.node){let{createHash:e}=lr.node;return Uint8Array.from(e("sha256").update(t).digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(lr.web){let r=await lr.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Af(...e),i=await lr.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(lr.node){let{createHmac:r}=lr.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,precompute(t=8,e=Me.BASE){let r=e===Me.BASE?e:new Me(e.x,e.y);return r._setWindowSize(t),r.multiply(oa),r}}});var Rm=b((lM,Tm)=>{"use strict";var la=ge(),ai=Cm(),{sha256:Im}=(ki(),Zn);Tm.exports=()=>{let t=32;function e(){return ai.utils.randomPrivateKey()}async function r(u,l){let{digest:f}=await Im.digest(l);try{return await ai.sign(f,u)}catch(d){throw la(d,"ERR_INVALID_INPUT")}}async function n(u,l,f){try{let{digest:d}=await Im.digest(f);return ai.verify(l,d,u)}catch(d){throw la(d,"ERR_INVALID_INPUT")}}function i(u){return ai.Point.fromHex(u).toRawBytes(!0)}function s(u){return ai.Point.fromHex(u).toRawBytes(!1)}function o(u){try{ai.getPublicKey(u,!0)}catch(l){throw la(l,"ERR_INVALID_PRIVATE_KEY")}}function a(u){try{ai.Point.fromHex(u)}catch(l){throw la(l,"ERR_INVALID_PUBLIC_KEY")}}function c(u){try{return ai.getPublicKey(u,!0)}catch(l){throw la(l,"ERR_INVALID_PRIVATE_KEY")}}return{generateKey:e,privateKeyLength:t,hashAndSign:r,hashAndVerify:n,compressPublicKey:i,decompressPublicKey:s,validatePrivateKey:o,validatePublicKey:a,computePublicKey:c}}});var Om=b((fM,Nm)=>{"use strict";var{sha256:Bm}=(ki(),Zn),D8=ge(),{equals:Pm}=(Sr(),_r),{toString:L8}=(Lt(),Kt),k8=Dc();Nm.exports=(t,e,r)=>{r=r||Rm()();class n{constructor(u){r.validatePublicKey(u),this._key=u}verify(u,l){return r.hashAndVerify(this._key,l,u)}marshal(){return r.compressPublicKey(this._key)}get bytes(){return t.PublicKey.encode({Type:t.KeyType.Secp256k1,Data:this.marshal()}).finish()}equals(u){return Pm(this.bytes,u.bytes)}async hash(){let{bytes:u}=await Bm.digest(this.bytes);return u}}class i{constructor(u,l){this._key=u,this._publicKey=l||r.computePublicKey(u),r.validatePrivateKey(this._key),r.validatePublicKey(this._publicKey)}sign(u){return r.hashAndSign(this._key,u)}get public(){return new n(this._publicKey)}marshal(){return this._key}get bytes(){return t.PrivateKey.encode({Type:t.KeyType.Secp256k1,Data:this.marshal()}).finish()}equals(u){return Pm(this.bytes,u.bytes)}async hash(){let{bytes:u}=await Bm.digest(this.bytes);return u}async id(){let u=await this.public.hash();return L8(u,"base58btc")}async export(u,l="libp2p-key"){if(l==="libp2p-key")return k8.export(this.bytes,u);throw D8(new Error(`export format '${l}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}}function s(c){return new i(c)}function o(c){return new n(c)}async function a(){let c=await r.generateKey();return new i(c)}return{Secp256k1PublicKey:n,Secp256k1PrivateKey:i,unmarshalSecp256k1PrivateKey:s,unmarshalSecp256k1PublicKey:o,generateKeyPair:a}}});var Lm=b((dM,Dm)=>{"use strict";Dm.exports={SHA1:20,SHA256:32,SHA512:64}});var Pf=b(qm=>{"use strict";var km=Xo(),q8=Lm(),U8={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},M8=async(t,e)=>{let r=await km.get().subtle.sign({name:"HMAC"},t,e);return new Uint8Array(r,r.byteOffset,r.byteLength)};qm.create=async function(t,e){let r=U8[t],n=await km.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:r}},!1,["sign"]);return{async digest(i){return M8(n,i)},length:q8[t]}}});var Vm=b((pM,Km)=>{"use strict";var Um=ge(),{concat:Mm}=(ei(),Jn),{fromString:F8}=(Dt(),Ft),K8=Pf(),Fm={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,cipherKeySize:32}};Km.exports=async(t,e,r)=>{let n=Fm[t];if(!n){let C=Object.keys(Fm).join(" / ");throw Um(new Error(`unknown cipher type '${t}'. Must be ${C}`),"ERR_INVALID_CIPHER_TYPE")}if(!e)throw Um(new Error("missing hash type"),"ERR_MISSING_HASH_TYPE");let i=n.keySize,s=n.ivSize,o=20,a=F8("key expansion"),c=2*(s+i+o),u=await K8.create(e,r),l=await u.digest(a),f=[],d=0;for(;dc&&(q=c-d),f.push(C),d+=q,l=await u.digest(l)}let p=c/2,h=Mm(f),g=h.slice(0,p),v=h.slice(p,c),w=C=>({iv:C.slice(0,s),cipherKey:C.slice(s,s+i),macKey:C.slice(s+i)});return{k1:w(g),k2:w(v)}}});var $m=b((yM,jm)=>{"use strict";var V8=ge();jm.exports=function(t,e){if(!t.includes(e)){let r=t.join(" / ");throw V8(new Error(`Unknown curve: ${e}. Must be ${r}`),"ERR_INVALID_CURVE")}}});var Qm=b(Ym=>{"use strict";var j8=ge(),fa=Xo(),{base64urlToBuffer:Hm}=Oc(),$8=$m(),{toString:Nf}=(Lt(),Kt),{concat:H8}=(ei(),Jn),{equals:z8}=(Sr(),_r),zm={"P-256":256,"P-384":384,"P-521":521};Ym.generateEphmeralKeyPair=async function(t){$8(Object.keys(zm),t);let e=await fa.get().subtle.generateKey({name:"ECDH",namedCurve:t},!0,["deriveBits"]),r=async(i,s)=>{let o;s?o=await fa.get().subtle.importKey("jwk",W8(t,s),{name:"ECDH",namedCurve:t},!1,["deriveBits"]):o=e.privateKey;let a=[await fa.get().subtle.importKey("jwk",Wm(t,i),{name:"ECDH",namedCurve:t},!1,[]),o],c=await fa.get().subtle.deriveBits({name:"ECDH",namedCurve:t,public:a[0]},a[1],zm[t]);return new Uint8Array(c,c.byteOffset,c.byteLength)},n=await fa.get().subtle.exportKey("jwk",e.publicKey);return{key:G8(n),genSharedKey:r}};var Gm={"P-256":32,"P-384":48,"P-521":66};function G8(t){let e=Gm[t.crv];return H8([Uint8Array.from([4]),Hm(t.x,e),Hm(t.y,e)],1+e*2)}function Wm(t,e){let r=Gm[t];if(z8(!e.slice(0,1),Uint8Array.from([4])))throw j8(new Error("Cannot unmarshal public key - invalid key format"),"ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:t,x:Nf(e.slice(1,r+1),"base64url"),y:Nf(e.slice(1+r),"base64url"),ext:!0}}var W8=(t,e)=>({...Wm(t,e.public),d:Nf(e.private,"base64url")})});var Zm=b((mM,Xm)=>{"use strict";var Y8=Qm();Xm.exports=async t=>Y8.generateEphmeralKeyPair(t)});var Wc=b((vM,ev)=>{"use strict";var hn=fc();Wn();ef();var Of=_e(),da=ge(),{fromString:Q8}=(Dt(),Ft),X8=wg(),Ir={rsa:zg(),ed25519:um(),secp256k1:Om()(hn,Nc())},Gc={message:"secp256k1 support requires libp2p-crypto-secp256k1 package",code:"ERR_MISSING_PACKAGE"};function Fs(t){let e=Ir[t.toLowerCase()];if(!e){let r=Object.keys(Ir).join(" / ");throw da(new Error(`invalid or unsupported key type ${t}. Must be ${r}`),"ERR_UNSUPPORTED_KEY_TYPE")}return e}var Z8=async(t,e)=>Fs(t).generateKeyPair(e),J8=async(t,e,r)=>{let n=Fs(t);if(t.toLowerCase()!=="ed25519")throw da(new Error("Seed key derivation is unimplemented for RSA or secp256k1"),"ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return n.generateKeyPairFromSeed(e,r)},eP=t=>{let e=hn.PublicKey.decode(t),r=e.Data;switch(e.Type){case hn.KeyType.RSA:return Ir.rsa.unmarshalRsaPublicKey(r);case hn.KeyType.Ed25519:return Ir.ed25519.unmarshalEd25519PublicKey(r);case hn.KeyType.Secp256k1:if(Ir.secp256k1)return Ir.secp256k1.unmarshalSecp256k1PublicKey(r);throw da(new Error(Gc.message),Gc.code);default:Fs(e.Type)}},tP=(t,e)=>(e=(e||"rsa").toLowerCase(),Fs(e),t.bytes),Jm=async t=>{let e=hn.PrivateKey.decode(t),r=e.Data;switch(e.Type){case hn.KeyType.RSA:return Ir.rsa.unmarshalRsaPrivateKey(r);case hn.KeyType.Ed25519:return Ir.ed25519.unmarshalEd25519PrivateKey(r);case hn.KeyType.Secp256k1:if(Ir.secp256k1)return Ir.secp256k1.unmarshalSecp256k1PrivateKey(r);throw da(new Error(Gc.message),Gc.code);default:Fs(e.Type)}},rP=(t,e)=>(e=(e||"rsa").toLowerCase(),Fs(e),t.bytes),nP=async(t,e)=>{try{let i=await X8.import(t,e);return Jm(i)}catch(i){}let r=Of.pki.decryptRsaPrivateKey(t,e);if(r===null)throw da(new Error("Cannot read the key, most likely the password is wrong or not a RSA key"),"ERR_CANNOT_DECRYPT_PEM");let n=Of.asn1.toDer(Of.pki.privateKeyToAsn1(r));return n=Q8(n.getBytes(),"ascii"),Ir.rsa.unmarshalRsaPrivateKey(n)};ev.exports={supportedKeys:Ir,keysPBM:hn,keyStretcher:Vm(),generateEphemeralKeyPair:Zm(),generateKeyPair:Z8,generateKeyPairFromSeed:J8,unmarshalPublicKey:eP,marshalPublicKey:tP,unmarshalPrivateKey:Jm,marshalPrivateKey:rP,import:nP}});var tv=b((EM,Df)=>{"use strict";function iP(t,{className:e,symbolName:r}){let n=Symbol.for(r),i={[e]:class extends t{constructor(...s){super(...s);Object.defineProperty(this,n,{value:!0})}get[Symbol.toStringTag](){return e}}}[e];return i[`is${e}`]=s=>!!(s&&s[n]),i}function sP(t,{className:e,symbolName:r,withoutNew:n}){let i=Symbol.for(r),s={[e]:function(...o){if(n&&!(this instanceof s))return new s(...o);let a=t.call(this,...o)||this;return a&&!a[i]&&Object.defineProperty(a,i,{value:!0}),a}}[e];return s.prototype=Object.create(t.prototype),s.prototype.constructor=s,Object.defineProperty(s.prototype,Symbol.toStringTag,{get(){return e}}),s[`is${e}`]=o=>!!(o&&o[i]),s}Df.exports=iP;Df.exports.proto=sP});var iv=b((bM,nv)=>{"use strict";var Ks=Sn(),rv=Ks.Reader,oP=Ks.Writer,Ct=Ks.util,ha=Ks.roots["libp2p-peer-id"]||(Ks.roots["libp2p-peer-id"]={});ha.PeerIdProto=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.id=r.bytes();break;case 2:s.pubKey=r.bytes();break;case 3:s.privKey=r.bytes();break;default:r.skipType(o&7);break}}if(!s.hasOwnProperty("id"))throw Ct.ProtocolError("missing required 'id'",{instance:s});return s},t.fromObject=function(r){if(r instanceof ha.PeerIdProto)return r;var n=new ha.PeerIdProto;return r.id!=null&&(typeof r.id=="string"?Ct.base64.decode(r.id,n.id=Ct.newBuffer(Ct.base64.length(r.id)),0):r.id.length&&(n.id=r.id)),r.pubKey!=null&&(typeof r.pubKey=="string"?Ct.base64.decode(r.pubKey,n.pubKey=Ct.newBuffer(Ct.base64.length(r.pubKey)),0):r.pubKey.length&&(n.pubKey=r.pubKey)),r.privKey!=null&&(typeof r.privKey=="string"?Ct.base64.decode(r.privKey,n.privKey=Ct.newBuffer(Ct.base64.length(r.privKey)),0):r.privKey.length&&(n.privKey=r.privKey)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.id="":(i.id=[],n.bytes!==Array&&(i.id=Ct.newBuffer(i.id))),n.bytes===String?i.pubKey="":(i.pubKey=[],n.bytes!==Array&&(i.pubKey=Ct.newBuffer(i.pubKey))),n.bytes===String?i.privKey="":(i.privKey=[],n.bytes!==Array&&(i.privKey=Ct.newBuffer(i.privKey)))),r.id!=null&&r.hasOwnProperty("id")&&(i.id=n.bytes===String?Ct.base64.encode(r.id,0,r.id.length):n.bytes===Array?Array.prototype.slice.call(r.id):r.id),r.pubKey!=null&&r.hasOwnProperty("pubKey")&&(i.pubKey=n.bytes===String?Ct.base64.encode(r.pubKey,0,r.pubKey.length):n.bytes===Array?Array.prototype.slice.call(r.pubKey):r.pubKey),r.privKey!=null&&r.hasOwnProperty("privKey")&&(i.privKey=n.bytes===String?Ct.base64.encode(r.privKey,0,r.privKey.length):n.bytes===Array?Array.prototype.slice.call(r.privKey):r.privKey),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Ks.util.toJSONOptions)},t}();nv.exports=ha});var qt=b((jt,dv)=>{"use strict";var{CID:Lf}=(Ss(),Fo),aP=(Ii(),Ci),cP=(ml(),ic),uP=(Vn(),Kn),lP=(Ko(),xs),{base58btc:kf}=(Vn(),Kn),{base32:fP}=(Ii(),Ci),{base16:sv}=(vl(),sc),pa=(Ai(),Uo),pn=Wc(),dP=tv(),{PeerIdProto:ov}=iv(),{equals:Fi}=(Sr(),_r),{fromString:ya}=(Dt(),Ft),{toString:hP}=(Lt(),Kt),{identity:Yc}=(Rc(),Qo),av={...aP,...cP,...uP,...lP},pP=Object.keys(av).reduce((t,e)=>t.or(av[e]),fP.decoder),yP=112,cv=114,uv=class{constructor(e,r,n){if(!(e instanceof Uint8Array))throw new Error("invalid id provided");if(r&&n&&!Fi(r.public.bytes,n.bytes))throw new Error("inconsistent arguments");this._id=e,this._idB58String=kf.encode(this.id).substring(1),this._privKey=r,this._pubKey=n}get id(){return this._id}set id(e){throw new Error("Id is immutable")}get privKey(){return this._privKey}set privKey(e){this._privKey=e}get pubKey(){if(this._pubKey)return this._pubKey;if(this._privKey)return this._privKey.public;try{let e=pa.decode(this.id);e.code===Yc.code&&(this._pubKey=pn.unmarshalPublicKey(e.digest))}catch(e){}return this._pubKey}set pubKey(e){this._pubKey=e}marshalPubKey(){if(this.pubKey)return pn.marshalPublicKey(this.pubKey)}marshalPrivKey(){if(this.privKey)return pn.marshalPrivateKey(this.privKey)}marshal(e){return ov.encode({id:this.toBytes(),pubKey:this.marshalPubKey(),privKey:e?null:this.marshalPrivKey()}).finish()}toPrint(){let e=this.toB58String();e.startsWith("Qm")&&(e=e.slice(2));let r=6;return e.length"}toJSON(){return{id:this.toB58String(),privKey:fv(this.marshalPrivKey()),pubKey:fv(this.marshalPubKey())}}toHexString(){return sv.encode(this.id).substring(1)}toBytes(){return this.id}toB58String(){return this._idB58String}toString(){if(!this._idCIDString){let e=Lf.createV1(cv,pa.decode(this.id));Object.defineProperty(this,"_idCIDString",{value:e.toString(),enumerable:!1})}return this._idCIDString}equals(e){if(e instanceof Uint8Array)return Fi(this.id,e);if(e.id)return Fi(this.id,e.id);throw new Error("not valid Id")}isEqual(e){return this.equals(e)}isValid(){return Boolean(this.privKey&&this.privKey.public&&this.privKey.public.bytes&&this.pubKey.bytes instanceof Uint8Array&&Fi(this.privKey.public.bytes,this.pubKey.bytes))}hasInlinePublicKey(){try{if(pa.decode(this.id).code===Yc.code)return!0}catch(e){}return!1}},yn=dP(uv,{className:"PeerId",symbolName:"@libp2p/js-peer-id/PeerId"});jt=dv.exports=yn;var ga=t=>t.bytes.length<=42?pa.create(Yc.code,t.bytes).bytes:t.hash(),qf=async(t,e)=>{let r=await ga(e);return new yn(r,t,e)};jt.create=async t=>{t=t||{},t.bits=t.bits||2048,t.keyType=t.keyType||"RSA";let e=await pn.generateKeyPair(t.keyType,t.bits);return qf(e,e.public)};jt.createFromHexString=t=>new yn(sv.decode("f"+t));jt.createFromBytes=t=>{try{let e=Lf.decode(t);if(!lv(e))throw new Error("Supplied PeerID CID is invalid");return jt.createFromCID(e)}catch{if(pa.decode(t).code!==Yc.code)throw new Error("Supplied PeerID CID is invalid");return new yn(t)}};jt.createFromB58String=t=>jt.createFromBytes(kf.decode("z"+t));var lv=t=>t.code===cv||t.code===yP;jt.createFromCID=t=>{if(t=Lf.asCID(t),!t||!lv(t))throw new Error("Supplied PeerID CID is invalid");return new yn(t.multihash.bytes)};jt.createFromPubKey=async t=>{let e=t;if(typeof e=="string"&&(e=ya(t,"base64pad")),!(e instanceof Uint8Array))throw new Error("Supplied key is neither a base64 string nor a Uint8Array");let r=await pn.unmarshalPublicKey(e);return qf(void 0,r)};jt.createFromPrivKey=async t=>{if(typeof t=="string"&&(t=ya(t,"base64pad")),!(t instanceof Uint8Array))throw new Error("Supplied key is neither a base64 string nor a Uint8Array");let e=await pn.unmarshalPrivateKey(t);return qf(e,e.public)};jt.createFromJSON=async t=>{let e=kf.decode("z"+t.id),r=t.privKey&&ya(t.privKey,"base64pad"),n=t.pubKey&&ya(t.pubKey,"base64pad"),i=n&&await pn.unmarshalPublicKey(n);if(!r)return new yn(e,void 0,i);let s=await pn.unmarshalPrivateKey(r),o=await ga(s.public),a;if(i&&(a=await ga(i)),i&&!Fi(o,a))throw new Error("Public and private key do not match");if(e&&!Fi(o,e))throw new Error("Id and private key do not match");return new yn(e,s,i)};jt.createFromProtobuf=async t=>{typeof t=="string"&&(t=ya(t,"base16"));let{id:e,privKey:r,pubKey:n}=ov.decode(t);r=r?await pn.unmarshalPrivateKey(r):!1,n=n?await pn.unmarshalPublicKey(n):!1;let i,s;if(r&&(s=await ga(r.public)),n&&(i=await ga(n)),r){if(n&&!Fi(s,i))throw new Error("Public and private key do not match");return new yn(s,r,r.public)}if(n)return new yn(i,void 0,n);if(e)return new yn(e);throw new Error("Protobuf did not contain any usable key material")};jt.parse=t=>((t.charAt(0)==="1"||t.charAt(0)==="Q")&&(t=`z${t}`),jt.createFromBytes(pP.decode(t)));jt.isPeerId=t=>Boolean(typeof t=="object"&&t._id&&t._idB58String);function fv(t){if(t)return hP(t,"base64pad")}});var Mf=b((wM,pv)=>{"use strict";var hv="[a-fA-F\\d:]",ci=t=>t&&t.includeBoundaries?`(?:(?<=\\s|^)(?=${hv})|(?<=${hv})(?=\\s|$))`:"",jr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",St="[a-fA-F\\d]{1,4}",Qc=` +(?: +(?:${St}:){7}(?:${St}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 +(?:${St}:){6}(?:${jr}|:${St}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 +(?:${St}:){5}(?::${jr}|(?::${St}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 +(?:${St}:){4}(?:(?::${St}){0,1}:${jr}|(?::${St}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 +(?:${St}:){3}(?:(?::${St}){0,2}:${jr}|(?::${St}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 +(?:${St}:){2}(?:(?::${St}){0,3}:${jr}|(?::${St}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 +(?:${St}:){1}(?:(?::${St}){0,4}:${jr}|(?::${St}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 +(?::(?:(?::${St}){0,5}:${jr}|(?::${St}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 +)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 +`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),gP=new RegExp(`(?:^${jr}$)|(?:^${Qc}$)`),mP=new RegExp(`^${jr}$`),vP=new RegExp(`^${Qc}$`),Uf=t=>t&&t.exact?gP:new RegExp(`(?:${ci(t)}${jr}${ci(t)})|(?:${ci(t)}${Qc}${ci(t)})`,"g");Uf.v4=t=>t&&t.exact?mP:new RegExp(`${ci(t)}${jr}${ci(t)}`,"g");Uf.v6=t=>t&&t.exact?vP:new RegExp(`${ci(t)}${Qc}${ci(t)}`,"g");pv.exports=Uf});var Kf=b((_M,yv)=>{"use strict";var Ff=Mf(),Vs=t=>Ff({exact:!0}).test(t);Vs.v4=t=>Ff.v4({exact:!0}).test(t);Vs.v6=t=>Ff.v6({exact:!0}).test(t);Vs.version=t=>Vs(t)?Vs.v4(t)?4:6:void 0;yv.exports=Vs});var bv=b((SM,Ev)=>{"use strict";var Vf=Kf(),{toString:gv}=(Lt(),Kt),EP=Vf,jf=Vf.v4,mv=Vf.v6,vv=function(t,e,r){r=~~r;let n;if(jf(t))n=e||new Uint8Array(r+4),t.split(/\./g).map(function(i){n[r++]=parseInt(i,10)&255});else if(mv(t)){let i=t.split(":",8),s;for(s=0;s0;s--)o.push("0");i.splice.apply(i,o)}for(n=e||new Uint8Array(r+16),s=0;s>8&255,n[r++]=o&255}}if(!n)throw Error("Invalid ip address: "+t);return n},bP=function(t,e,r){e=~~e,r=r||t.length-e;let n=[],i,s=new DataView(t.buffer);if(r===4){for(let o=0;o{"use strict";function or(t){if(typeof t=="number"){if(or.codes[t])return or.codes[t];throw new Error("no protocol with code: "+t)}else if(typeof t=="string"){if(or.names[t])return or.names[t];throw new Error("no protocol with name: "+t)}throw new Error("invalid protocol id type: "+t)}var Tr=-1;or.lengthPrefixedVarSize=Tr;or.V=Tr;or.table=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Tr,"ip6zone"],[53,Tr,"dns","resolvable"],[54,Tr,"dns4","resolvable"],[55,Tr,"dns6","resolvable"],[56,Tr,"dnsaddr","resolvable"],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,Tr,"unix",!1,"path"],[421,Tr,"ipfs"],[421,Tr,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Tr,"garlic64"],[460,0,"quic"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,Tr,"memory"]];or.names={};or.codes={};or.table.map(t=>{let e=wv.apply(null,t);return or.codes[e.code]=e,or.names[e.name]=e,null});or.object=wv;function wv(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:Boolean(n),path:Boolean(i)}}_v.exports=or});var Av=b((AM,xv)=>{xv.exports=$f;var Sv=128,wP=127,_P=~wP,SP=Math.pow(2,31);function $f(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw $f.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=SP;)e[r++]=t&255|Sv,t/=128;for(;t&_P;)e[r++]=t&255|Sv,t>>>=7;return e[r]=t|0,$f.bytes=r-n+1,e}});var Tv=b((CM,Iv)=>{Iv.exports=Hf;var xP=128,Cv=127;function Hf(t,e){var r=0,e=e||0,n=0,i=e,s,o=t.length;do{if(i>=o||n>49)throw Hf.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=n<28?(s&Cv)<=xP);return Hf.bytes=i-e,r}});var Bv=b((IM,Rv)=>{var AP=Math.pow(2,7),CP=Math.pow(2,14),IP=Math.pow(2,21),TP=Math.pow(2,28),RP=Math.pow(2,35),BP=Math.pow(2,42),PP=Math.pow(2,49),NP=Math.pow(2,56),OP=Math.pow(2,63);Rv.exports=function(t){return t{Pv.exports={encode:Av(),decode:Tv(),encodingLength:Bv()}});var Mv=b((RM,Uv)=>{"use strict";var Xc=bv(),Nv=ma(),{CID:DP}=(Ss(),Fo),{base32:Ov}=(Ii(),Ci),{base58btc:LP}=(Vn(),Kn),kP=(Ai(),Uo),js=Ki(),{toString:Zc}=(Lt(),Kt),{fromString:Dv}=(Dt(),Ft),{concat:Jc}=(ei(),Jn);Uv.exports=va;function va(t,e){return e instanceof Uint8Array?va.toString(t,e):va.toBytes(t,e)}va.toString=function(e,r){switch(Nv(e).code){case 4:case 41:return qP(r);case 6:case 273:case 33:case 132:return kv(r).toString();case 53:case 54:case 55:case 56:case 400:case 777:return MP(r);case 421:return KP(r);case 444:return qv(r);case 445:return qv(r);default:return Zc(r,"base16")}};va.toBytes=function(e,r){switch(Nv(e).code){case 4:return Lv(r);case 41:return Lv(r);case 6:case 273:case 33:case 132:return zf(parseInt(r,10));case 53:case 54:case 55:case 56:case 400:case 777:return UP(r);case 421:return FP(r);case 444:return VP(r);case 445:return jP(r);default:return Dv(r,"base16")}};function Lv(t){if(!Xc.isIP(t))throw new Error("invalid ip address");return Xc.toBytes(t)}function qP(t){let e=Xc.toString(t);if(!e||!Xc.isIP(e))throw new Error("invalid ip address");return e}function zf(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function kv(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function UP(t){let e=Dv(t),r=Uint8Array.from(js.encode(e.length));return Jc([r,e],r.length+e.length)}function MP(t){let e=js.decode(t);if(t=t.slice(js.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return Zc(t)}function FP(t){let e;t[0]==="Q"||t[0]==="1"?e=kP.decode(LP.decode(`z${t}`)).bytes:e=DP.parse(t).multihash.bytes;let r=Uint8Array.from(js.encode(e.length));return Jc([r,e],r.length+e.length)}function KP(t){let e=js.decode(t),r=t.slice(js.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return Zc(r,"base58btc")}function VP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" does not contain a port number");if(e[0].length!==16)throw new Error("failed to parse onion addr: "+e[0]+" not a Tor onion address.");let r=Ov.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=zf(n);return Jc([r,i],r.length+i.length)}function jP(t){let e=t.split(":");if(e.length!==2)throw new Error("failed to parse onion addr: "+e+" does not contain a port number");if(e[0].length!==56)throw new Error("failed to parse onion addr: "+e[0]+" not a Tor onion3 address.");let r=Ov.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=zf(n);return Jc([r,i],r.length+i.length)}function qv(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=Zc(e,"base32"),i=kv(r);return n+":"+i}});var Xv=b((BM,Qv)=>{"use strict";var Fv=Mv(),Gf=ma(),Ea=Ki(),{concat:Kv}=(ei(),Jn),{toString:$P}=(Lt(),Kt);Qv.exports={stringToStringTuples:Vv,stringTuplesToString:jv,tuplesToStringTuples:Hv,stringTuplesToTuples:$v,bytesToTuples:Wf,tuplesToBytes:zv,bytesToString:HP,stringToBytes:Wv,fromString:zP,fromBytes:Yv,validateBytes:Yf,isValidBytes:GP,cleanPath:eu,ParseError:Qf,protoFromTuple:ba,sizeForAddr:Gv};function Vv(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n=r.length)throw Qf("invalid address: "+t);if(s.path){e.push([i,eu(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function jv(t){let e=[];return t.map(r=>{let n=ba(r);return e.push(n.name),r.length>1&&e.push(r[1]),null}),eu(e.join("/"))}function $v(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=ba(e);return e.length>1?[r.code,Fv.toBytes(r.code,e[1])]:[r.code]})}function Hv(t){return t.map(e=>{let r=ba(e);return e[1]?[r.code,Fv.toString(r.code,e[1])]:[r.code]})}function zv(t){return Yv(Kv(t.map(e=>{let r=ba(e),n=Uint8Array.from(Ea.encode(r.code));return e.length>1&&(n=Kv([n,e[1]])),n})))}function Gv(t,e){return t.size>0?t.size/8:t.size===0?0:Ea.decode(e)+Ea.decode.bytes}function Wf(t){let e=[],r=0;for(;rt.length)throw Qf("Invalid address Uint8Array: "+$P(t,"base16"));e.push([n,a])}return e}function HP(t){let e=Wf(t),r=Hv(e);return jv(r)}function Wv(t){t=eu(t);let e=Vv(t),r=$v(e);return zv(r)}function zP(t){return Wv(t)}function Yv(t){let e=Yf(t);if(e)throw e;return Uint8Array.from(t)}function Yf(t){try{Wf(t)}catch(e){return e}}function GP(t){return Yf(t)===void 0}function eu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function Qf(t){return new Error("Error parsing address: "+t)}function ba(t){return Gf(t[0])}});var $t=b((PM,e1)=>{"use strict";var $r=Xv(),$s=ma(),Zv=Ki(),{CID:WP}=(Ss(),Fo),{base58btc:YP}=(Vn(),Kn),QP=ge(),XP=Symbol.for("nodejs.util.inspect.custom"),{toString:tu}=(Lt(),Kt),{equals:ZP}=(Sr(),_r),Xf=new Map,Jv=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Qt=class{constructor(e){if(e==null&&(e=""),Object.defineProperty(this,Jv,{value:!0}),e instanceof Uint8Array)this.bytes=$r.fromBytes(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=$r.fromString(e)}else if(Qt.isMultiaddr(e))this.bytes=$r.fromBytes(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return $r.bytesToString(this.bytes)}toJSON(){return this.toString()}toOptions(){let e={},r=this.toString().split("/");return e.family=r[1]==="ip4"?4:6,e.host=r[2],e.transport=r[3],e.port=parseInt(r[4]),e}protos(){return this.protoCodes().map(e=>Object.assign({},$s(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;ne.name)}tuples(){return $r.bytesToTuples(this.bytes)}stringTuples(){let e=$r.bytesToTuples(this.bytes);return $r.tuplesToStringTuples(e)}encapsulate(e){return e=new Qt(e),new Qt(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error("Address "+this+" does not contain subaddress: "+e);return new Qt(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new Qt($r.tuplesToBytes(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===$s.names.ipfs.code).pop();if(r&&r[1]){let n=r[1];return n[0]==="Q"||n[0]==="1"?tu(YP.decode(`z${n}`),"base58btc"):tu(WP.parse(n).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){let e=null;try{e=this.stringTuples().filter(r=>!!$s(r[0]).path)[0][1],e||(e=null)}catch(r){e=null}return e}equals(e){return ZP(this.bytes,e.bytes)}async resolve(){let e=this.protos().find(i=>i.resolvable);if(!e)return[this];let r=Xf.get(e.name);if(!r)throw QP(new Error(`no available resolver for ${e.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(await r(this)).map(i=>new Qt(i))}nodeAddress(){let e=this.protoCodes(),r=this.protoNames(),n=this.toString().split("/").slice(1);if(n.length<4)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6}/{address}/{tcp, udp}/{port}".');if(e[0]!==4&&e[0]!==41&&e[0]!==54&&e[0]!==55)throw new Error(`no protocol with name: "'${r[0]}'". Must have a valid family name: "{ip4, ip6, dns4, dns6}".`);if(n[2]!=="tcp"&&n[2]!=="udp")throw new Error(`no protocol with name: "'${r[1]}'". Must have a valid transport protocol: "{tcp, udp}".`);return{family:e[0]===41||e[0]===55?6:4,address:n[1],port:parseInt(n[3])}}isThinWaistAddress(e){let r=(e||this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}static fromNodeAddress(e,r){if(!e)throw new Error("requires node address object");if(!r)throw new Error("requires transport protocol");let n;switch(e.family){case 4:n="ip4";break;case 6:n="ip6";break;default:throw Error(`Invalid addr family. Got '${e.family}' instead of 4 or 6`)}return new Qt("/"+[n,e.address,r,e.port].join("/"))}static isName(e){return Qt.isMultiaddr(e)?e.protos().some(r=>r.resolvable):!1}static isMultiaddr(e){return e instanceof Qt||Boolean(e&&e[Jv])}[XP](){return""}inspect(){return""}};Qt.protocols=$s;Qt.resolvers=Xf;function JP(t){return new Qt(t)}e1.exports={Multiaddr:Qt,multiaddr:JP,protocols:$s,resolvers:Xf}});var Vi=b((NM,t1)=>{"use strict";var eN=async t=>{let e=[];for await(let r of t)e.push(r);return e};t1.exports=eN});var r1,Zf,n1=Te(()=>{r1=Lo(Vi()),Zf=(t,e)=>async function*(){yield*(await(0,r1.default)(t)).sort(e)}()});var wa=b((DM,i1)=>{"use strict";var tN=async t=>{for await(let e of t);};i1.exports=tN});var ji=b((LM,s1)=>{"use strict";var rN=async function*(t,e){for await(let r of t)await e(r)&&(yield r)};s1.exports=rN});var Jf=b((kM,o1)=>{"use strict";var nN=async function*(t,e){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}};o1.exports=nN});var ed,$i,td,rd,a1=Te(()=>{n1();ed=Lo(wa()),$i=Lo(ji()),td=Lo(Jf()),rd=class{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield{key:n,value:i}}async*getMany(e,r={}){for await(let n of e)yield this.get(n,r)}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await(0,ed.default)(this.putMany(e,n)),e=[],await(0,ed.default)(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null&&(n=(0,$i.default)(n,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,$i.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Zf(i,s),n)),e.offset!=null){let i=0;n=(0,$i.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,td.default)(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null&&(n=(0,$i.default)(n,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>(0,$i.default)(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Zf(i,s),n)),e.offset!=null){let i=0;n=(0,$i.default)(n,()=>i++>=e.offset)}return e.limit!=null&&(n=(0,td.default)(n,e.limit)),n}}});var c1,u1=Te(()=>{c1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});var id={};_t(id,{customAlphabet:()=>iN,customRandom:()=>f1,nanoid:()=>nd,random:()=>l1,urlAlphabet:()=>c1});var l1,f1,iN,nd,ru=Te(()=>{u1();l1=t=>crypto.getRandomValues(new Uint8Array(t)),f1=(t,e,r)=>{let n=(2<{let o="";for(;;){let a=r(i),c=i;for(;c--;)if(o+=t[a[c]&n]||"",o.length===s)return o}}},iN=(t,e=21)=>f1(t,e,l1),nd=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=r[t]&63;n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n<63?e+="_":e+="-"}return e}});var sd={};_t(sd,{Key:()=>Ut});function sN(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function oN(t){let e=t.split(":");return e[e.length-1]}function aN(t){return[].concat(...t)}var Bn,d1,nu,Ut,iu=Te(()=>{ru();Lt();Dt();Bn="/",d1=new TextEncoder().encode(Bn),nu=d1[0],Ut=class{constructor(e,r){if(typeof e=="string")this._buf=ff(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==nu)throw new Error("Invalid key")}toString(e="utf8"){return hf(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Ut(e.join(Bn))}static random(){return new Ut(nd().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new Ut(e):e.uint8Array?new Ut(e.uint8Array()):null}clean(){if((!this._buf||this._buf.byteLength===0)&&(this._buf=d1),this._buf[0]!==nu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(nu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===nu;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;io)return!1}return r.lengthr.namespaces()))])}}});function p1(t){return t=t||new Error("Not Found"),(0,h1.default)(t,"ERR_NOT_FOUND")}var h1,y1=Te(()=>{h1=Lo(ge())});var m1={};_t(m1,{MemoryDatastore:()=>g1});var g1,v1=Te(()=>{a1();iu();y1();g1=class extends rd{constructor(){super();this.data={}}open(){return Promise.resolve()}close(){return Promise.resolve()}async put(e,r){this.data[e.toString()]=r}async get(e){if(!await this.has(e))throw p1();return this.data[e.toString()]}async has(e){return this.data[e.toString()]!==void 0}async delete(e){delete this.data[e.toString()]}async*_all(){yield*Object.entries(this.data).map(([e,r])=>({key:new Ut(e),value:r}))}async*_allKeys(){yield*Object.entries(this.data).map(([e])=>new Ut(e))}}});var Ye=b(od=>{"use strict";od.messages={NOT_STARTED_YET:"The libp2p node is not started yet",DHT_DISABLED:"DHT is not available",CONN_ENCRYPTION_REQUIRED:"At least one connection encryption module is required",NOT_FOUND:"Not found"};od.codes={DHT_DISABLED:"ERR_DHT_DISABLED",PUBSUB_NOT_STARTED:"ERR_PUBSUB_NOT_STARTED",DHT_NOT_STARTED:"ERR_DHT_NOT_STARTED",CONN_ENCRYPTION_REQUIRED:"ERR_CONN_ENCRYPTION_REQUIRED",ERR_PEER_DIAL_INTERCEPTED:"ERR_PEER_DIAL_INTERCEPTED",ERR_CONNECTION_INTERCEPTED:"ERR_CONNECTION_INTERCEPTED",ERR_INVALID_PROTOCOLS_FOR_STREAM:"ERR_INVALID_PROTOCOLS_FOR_STREAM",ERR_CONNECTION_ENDED:"ERR_CONNECTION_ENDED",ERR_CONNECTION_FAILED:"ERR_CONNECTION_FAILED",ERR_NODE_NOT_STARTED:"ERR_NODE_NOT_STARTED",ERR_ALREADY_ABORTED:"ERR_ALREADY_ABORTED",ERR_TOO_MANY_ADDRESSES:"ERR_TOO_MANY_ADDRESSES",ERR_NO_VALID_ADDRESSES:"ERR_NO_VALID_ADDRESSES",ERR_RELAYED_DIAL:"ERR_RELAYED_DIAL",ERR_DIALED_SELF:"ERR_DIALED_SELF",ERR_DISCOVERED_SELF:"ERR_DISCOVERED_SELF",ERR_DUPLICATE_TRANSPORT:"ERR_DUPLICATE_TRANSPORT",ERR_ENCRYPTION_FAILED:"ERR_ENCRYPTION_FAILED",ERR_HOP_REQUEST_FAILED:"ERR_HOP_REQUEST_FAILED",ERR_INVALID_KEY:"ERR_INVALID_KEY",ERR_INVALID_MESSAGE:"ERR_INVALID_MESSAGE",ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_INVALID_PEER:"ERR_INVALID_PEER",ERR_MUXER_UNAVAILABLE:"ERR_MUXER_UNAVAILABLE",ERR_NOT_FOUND:"ERR_NOT_FOUND",ERR_TIMEOUT:"ERR_TIMEOUT",ERR_TRANSPORT_UNAVAILABLE:"ERR_TRANSPORT_UNAVAILABLE",ERR_TRANSPORT_DIAL_FAILED:"ERR_TRANSPORT_DIAL_FAILED",ERR_UNSUPPORTED_PROTOCOL:"ERR_UNSUPPORTED_PROTOCOL",ERR_INVALID_MULTIADDR:"ERR_INVALID_MULTIADDR",ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID",ERR_FIND_SELF:"ERR_FIND_SELF",ERR_NO_ROUTERS_AVAILABLE:"ERR_NO_ROUTERS_AVAILABLE",ERR_CONNECTION_NOT_MULTIPLEXED:"ERR_CONNECTION_NOT_MULTIPLEXED",ERR_NO_DIAL_TOKENS:"ERR_NO_DIAL_TOKENS",ERR_KEYCHAIN_REQUIRED:"ERR_KEYCHAIN_REQUIRED",ERR_INVALID_CMS:"ERR_INVALID_CMS",ERR_MISSING_KEYS:"ERR_MISSING_KEYS",ERR_NO_KEY:"ERR_NO_KEY",ERR_INVALID_KEY_NAME:"ERR_INVALID_KEY_NAME",ERR_INVALID_KEY_TYPE:"ERR_INVALID_KEY_TYPE",ERR_KEY_ALREADY_EXISTS:"ERR_KEY_ALREADY_EXISTS",ERR_INVALID_KEY_SIZE:"ERR_INVALID_KEY_SIZE",ERR_KEY_NOT_FOUND:"ERR_KEY_NOT_FOUND",ERR_OLD_KEY_NAME_INVALID:"ERR_OLD_KEY_NAME_INVALID",ERR_NEW_KEY_NAME_INVALID:"ERR_NEW_KEY_NAME_INVALID",ERR_PASSWORD_REQUIRED:"ERR_PASSWORD_REQUIRED",ERR_PEM_REQUIRED:"ERR_PEM_REQUIRED",ERR_CANNOT_READ_KEY:"ERR_CANNOT_READ_KEY",ERR_MISSING_PRIVATE_KEY:"ERR_MISSING_PRIVATE_KEY",ERR_INVALID_OLD_PASS_TYPE:"ERR_INVALID_OLD_PASS_TYPE",ERR_INVALID_NEW_PASS_TYPE:"ERR_INVALID_NEW_PASS_TYPE",ERR_INVALID_PASS_LENGTH:"ERR_INVALID_PASS_LENGTH",ERR_NOT_IMPLEMENTED:"ERR_NOT_IMPLEMENTED",ERR_WRONG_PING_ACK:"ERR_WRONG_PING_ACK"}});var ad=b((YM,E1)=>{"use strict";var cN=async function*(t,e){for await(let r of t)yield e(r)};E1.exports=cN});var cd=b((QM,b1)=>{"use strict";var uN=ge(),lN=ji(),fN=ad(),dN=Jf();async function*hN(t,e){yield*fN(t,async r=>(await e.addressBook.add(r.id,r.multiaddrs),r))}function pN(t){let e=new Set;return lN(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*yN(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r{"use strict";w1.exports=function(){return Date.now()}});var _a=b((ZM,x1)=>{"use strict";var su=_1(),S1=class{constructor(e,r,n){let i=this;this._started=su(),this._rescheduled=0,this._scheduled=r,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(su()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,r)}reschedule(e){e||(e=this._scheduled);let r=su();r+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=r,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=su(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function mN(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let t;if(arguments.length>0){t=new Array(arguments.length-2);for(var e=0;e{"use strict";var{AbortController:vN}=globalThis,A1=_a(),ou=class extends vN{constructor(e){super();this._ms=e,this._timer=A1(()=>this.abort(),e),Object.setPrototypeOf(this,ou.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=A1(()=>this.abort(),this._ms)}};C1.exports={TimeoutController:ou}});var T1=b((tF,I1)=>{I1.exports=class{constructor(e){if(!(e>0)||(e-1&e)!=0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var ld=b((nF,B1)=>{var R1=T1();B1.exports=class{constructor(e){this.hwm=e||16,this.head=new R1(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){let r=this.head;this.head=r.next=new R1(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next){let r=this.tail.next;return this.tail.next=null,this.tail=r,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}});var dd=b((iF,P1)=>{var fd=ld();P1.exports=t=>{t=t||{};let e;typeof t=="function"?(e=t,t={}):e=t.onEnd;let r=new fd,n,i,s,o=()=>{if(!r.isEmpty()){if(t.writev){let g,v=[];for(;!r.isEmpty();){if(g=r.shift(),g.error)throw g.error;v.push(g.value)}return{done:g.done,value:v}}let h=r.shift();if(h.error)throw h.error;return h}return s?{done:!0}:new Promise((h,g)=>{i=v=>(i=null,v.error?g(v.error):t.writev&&!v.done?h({done:v.done,value:[v.value]}):h(v),n)})},a=h=>i?i(h):(r.push(h),n),c=h=>(r=new fd,i?i({error:h}):(r.push({error:h}),n)),u=h=>s?n:a({done:!1,value:h}),l=h=>s?n:(s=!0,h?c(h):a({done:!0})),f=()=>(r=new fd,l(),{done:!0}),d=h=>(l(h),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:o,return:f,throw:d,push:u,end:l},!e)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(h){return p.throw(h),e&&(e(h),e=null),{done:!0}},return(){return p.return(),e&&(e(),e=null),{done:!0}},push:u,end(h){return p.end(h),e&&(e(h),e=null),n}},n}});var hd=b((sF,N1)=>{"use strict";var EN=dd(),bN=async function*(...t){let e=EN();setTimeout(async()=>{try{await Promise.all(t.map(async r=>{for await(let n of r)e.push(n)})),e.end()}catch(r){e.end(r)}},0),yield*e};N1.exports=bN});var fr=b((oF,Hs)=>{var O1=(...t)=>{let e;for(;t.length;)e=t.shift()(e);return e},pd=t=>t&&(typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function"||typeof t.next=="function"),au=t=>t&&typeof t.sink=="function"&&pd(t.source),wN=t=>e=>(t.sink(e),t.source),D1=(...t)=>{if(au(t[0])){let e=t[0];t[0]=()=>e.source}else if(pd(t[0])){let e=t[0];t[0]=()=>e}if(t.length>1&&au(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let e=1;e{"use strict";var _N=async t=>{for await(let e of t)return e};L1.exports=_N});var gd=b((cF,k1)=>{"use strict";var zs=new Map,SN=()=>`${Date.now()}:${Math.floor(Math.random()*1e6)}`;async function xN(t,e,r){for(;zs.get(r);){try{await t()}catch(n){setTimeout(()=>{throw n},1);break}if(!zs.get(r))break;await new Promise(n=>{let i=setTimeout(n,e);zs.set(r,i)})}}function AN(t,e,r){r=r||e;let n=SN(),i=setTimeout(()=>{xN(t,e,n)},r);return zs.set(n,i),n}function CN(t){let e=zs.get(t);e&&(clearTimeout(e),zs.delete(t))}k1.exports={setDelayedInterval:AN,clearDelayedInterval:CN}});var M1=b((uF,U1)=>{"use strict";var IN=ge(),{messages:TN,codes:RN}=Ye(),q1=class{constructor(e){this._dht=e}async findPeer(e,r={}){for await(let n of this._dht.findPeer(e,r))if(n.name==="FINAL_PEER")return n.peer;throw IN(new Error(TN.NOT_FOUND),RN.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){for await(let n of this._dht.getClosestPeers(e,r))n.name==="PEER_RESPONSE"&&(yield*n.closer)}};U1.exports={DHTPeerRouting:q1}});var W1=b((lF,G1)=>{"use strict";var F1=Oe(),K1=Object.assign(F1("libp2p:peer-routing"),{error:F1("libp2p:peer-routing:err")}),cu=ge(),Sa=Ye(),{storeAddresses:V1,uniquePeers:BN,requirePeers:PN}=cd(),{TimeoutController:NN}=ud(),j1=hd(),{pipe:$1}=fr(),ON=yd(),DN=wa(),LN=ji(),{setDelayedInterval:kN,clearDelayedInterval:qN}=gd(),{DHTPeerRouting:UN}=M1(),{setMaxListeners:H1}=rr(),z1=class{constructor(e){this._peerId=e.peerId,this._peerStore=e.peerStore,this._routers=e._modules.peerRouting||[],e._dht&&e._config.dht.enabled&&this._routers.push(new UN(e._dht)),this._refreshManagerOptions=e._options.peerRouting.refreshManager,this._findClosestPeersTask=this._findClosestPeersTask.bind(this)}start(){!this._routers.length||this._timeoutId||!this._refreshManagerOptions.enabled||(this._timeoutId=kN(this._findClosestPeersTask,this._refreshManagerOptions.interval,this._refreshManagerOptions.bootDelay))}async _findClosestPeersTask(){try{await DN(this.getClosestPeers(this._peerId.id,{timeout:this._refreshManagerOptions.timeout||1e4}))}catch(e){K1.error(e)}}stop(){qN(this._timeoutId)}async findPeer(e,r){if(!this._routers.length)throw cu(new Error("No peer routers available"),Sa.codes.ERR_NO_ROUTERS_AVAILABLE);if(e.toB58String()===this._peerId.toB58String())throw cu(new Error("Should not try to find self"),Sa.codes.ERR_FIND_SELF);let n=await $1(j1(...this._routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){K1.error(s)}}())),i=>LN(i,Boolean),i=>V1(i,this._peerStore),i=>ON(i));if(n)return n;throw cu(new Error(Sa.messages.NOT_FOUND),Sa.codes.ERR_NOT_FOUND)}async*getClosestPeers(e,r={timeout:3e4}){if(!this._routers.length)throw cu(new Error("No peer routers available"),Sa.codes.ERR_NO_ROUTERS_AVAILABLE);if(r.timeout){let n=new NN(r.timeout);try{H1&&H1(1/0,n.signal)}catch{}r.signal=n.signal}yield*$1(j1(...this._routers.map(n=>n.getClosestPeers(e,r))),n=>V1(n,this._peerStore),n=>BN(n),n=>PN(n))}};G1.exports=z1});var X1=b((fF,Q1)=>{"use strict";var MN=wa(),Y1=class{constructor(e){this._dht=e}async provide(e){await MN(this._dht.provide(e))}async*findProviders(e,r){for await(let n of this._dht.findProviders(e,r))n.name==="PROVIDER"&&(yield*n.providers)}};Q1.exports={DHTContentRouting:Y1}});var eE=b((dF,J1)=>{"use strict";var Hi=ge(),{messages:xa,codes:zi}=Ye(),{storeAddresses:FN,uniquePeers:KN,requirePeers:VN,maybeLimitSource:jN}=cd(),$N=wa(),HN=hd(),{pipe:zN}=fr(),{DHTContentRouting:GN}=X1(),Z1=class{constructor(e){this.libp2p=e,this.routers=e._modules.contentRouting||[],this.dht=e._dht,this.dht&&e._config.dht.enabled&&this.routers.push(new GN(this.dht))}async*findProviders(e,r={}){if(!this.routers.length)throw Hi(new Error("No content this.routers available"),zi.ERR_NO_ROUTERS_AVAILABLE);yield*zN(HN(...this.routers.map(n=>n.findProviders(e,r))),n=>FN(n,this.libp2p.peerStore),n=>KN(n),n=>jN(n,r.maxNumProviders),n=>VN(n))}async provide(e){if(!this.routers.length)throw Hi(new Error("No content routers available"),zi.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(r=>r.provide(e)))}async put(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Hi(new Error(xa.NOT_STARTED_YET),zi.DHT_NOT_STARTED);await $N(this.dht.put(e,r,n))}async get(e,r){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Hi(new Error(xa.NOT_STARTED_YET),zi.DHT_NOT_STARTED);for await(let n of this.dht.get(e,r))if(n.name==="VALUE")return{from:n.peerId,val:n.value};throw Hi(new Error(xa.NOT_FOUND),zi.ERR_NOT_FOUND)}async*getMany(e,r,n){if(!this.libp2p.isStarted()||!this.dht.isStarted)throw Hi(new Error(xa.NOT_STARTED_YET),zi.DHT_NOT_STARTED);if(!r)return;let i=0;for await(let s of this.dht.get(e,n))if(s.name==="VALUE"&&(yield{from:s.peerId,val:s.value},i++,i===r))break;if(i===0)throw Hi(new Error(xa.NOT_FOUND),zi.ERR_NOT_FOUND)}};J1.exports=Z1});var md=b((hF,iE)=>{"use strict";var WN=qt(),{Multiaddr:tE}=$t(),rE=ge(),{codes:nE}=Ye();function YN(t){typeof t=="string"&&(t=new tE(t));let e;if(tE.isMultiaddr(t)){e=t;let r=t.getPeerId();if(!r)throw rE(new Error(`${t} does not have a valid peer type`),nE.ERR_INVALID_MULTIADDR);try{t=WN.createFromB58String(r)}catch(n){throw rE(new Error(`${t} is not a valid peer type`),nE.ERR_INVALID_MULTIADDR)}}return{id:t,multiaddrs:e?[e]:void 0}}iE.exports=YN});var oE=b((pF,sE)=>{"use strict";sE.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Ys=b((lE,fE)=>{"use strict";var uu=oE(),{hasOwnProperty:aE}=Object.prototype,{propertyIsEnumerable:QN}=Object,Gs=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),XN=lE,cE={concatArrays:!1,ignoreUndefined:!1},lu=t=>{let e=[];for(let r in t)aE.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)QN.call(t,n)&&e.push(n)}return e};function Ws(t){return Array.isArray(t)?ZN(t):uu(t)?JN(t):t}function ZN(t){let e=t.slice(0,0);return lu(t).forEach(r=>{Gs(e,r,Ws(t[r]))}),e}function JN(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return lu(t).forEach(r=>{Gs(e,r,Ws(t[r]))}),e}var uE=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]=="undefined"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?Gs(t,i,vd(t[i],e[i],n)):Gs(t,i,Ws(e[i])))}),t),eO=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a!o.includes(a)),r)}),n};function vd(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?eO(t,e,r):!uu(e)||!uu(t)?Ws(e):uE(t,e,lu(e),r)}fE.exports=function(...t){let e=vd(Ws(cE),this!==XN&&this||{},cE),r={_:{}};for(let n of t)if(n!==void 0){if(!uu(n))throw new TypeError("`"+n+"` is not an Option Object");r=vd(r,{_:n},e)}return r._}});var pE=b((yF,hE)=>{"use strict";hE.exports=dE;var tO=dl(),ui=dE.prototype,rO=new Date%1e9;function nO(){return(Math.random()*1e9>>>0)+rO++}function dE(t){t=t||{},this.id=t.id||nO(),this.max=t.max||1/0,this.items=t.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(t.lastModified||new Date);for(var e,r,n=this.items.length;n--;)e=this.items[n],r=new Date(e.expires)-new Date,this._lookup[e.key]=e,r>0?this.expire(e.key,r):r<=0&&this.delete(e.key)}ui.has=function(t){return t in this._lookup};ui.get=function(t){if(!this.has(t))return null;var e=this._lookup[t];return e.refresh&&this.expire(t,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};ui.meta=function(t){if(!this.has(t))return null;var e=this._lookup[t];return"meta"in e?e.meta:null};ui.set=function(t,e,r){var n=this._lookup[t],i=this._lookup[t]={key:t,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),r&&("ttl"in r&&this.expire(t,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};ui.delete=function(t){var e=this._lookup[t];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[t],this.size--,this):!1};ui.expire=function(t,e){var r=e||0,n=this._lookup[t];if(!n)return this;if(typeof r=="string"&&(r=tO(e)),typeof r!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),r),n.expires=Number(new Date)+r,this};ui.clear=function(){for(var t=this.items.length;t--;)this.delete(this.items[t].key);return this};ui.toJSON=function(){for(var t=new Array(this.items.length),e,r=t.length;r--;)e=this.items[r],t[r]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:t}}});var Aa=b((Qs,yE)=>{"use strict";var iO=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof Pn!="undefined")return Pn;throw new Error("unable to locate global object")},Pn=iO();yE.exports=Qs=Pn.fetch;Pn.fetch&&(Qs.default=Pn.fetch.bind(Pn));Qs.Headers=Pn.Headers;Qs.Request=Pn.Request;Qs.Response=Pn.Response});var gE=b((gF,Ed)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?Ed.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:Ed.exports={default:Aa().default,Headers:Aa().Headers,Request:Aa().Request,Response:Aa().Response}});var vE=b((mF,mE)=>{"use strict";var{default:sO,Headers:oO}=gE();function aO({serverResolver:t,hostname:e,recordType:r}){return`${t}?name=${e}&type=${r}`}function cO(t){return sO(t,{headers:new oO({accept:"application/dns-json"})})}function uO(t,e){return`${e}_${t}`}mE.exports={buildResource:aO,fetch:cO,getCacheKey:uO}});var wE=b((vF,bE)=>{"use strict";var EE=Oe(),fu=EE("dns-over-http-resolver");fu.error=EE("dns-over-http-resolver:error");var lO=pE(),Rr=vE(),du=class{constructor({maxCache:e=100}={}){this._cache=new lO({max:e}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"]}getServers(){return this._servers}_getShuffledServers(){let e=[].concat(this._servers);for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Rr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Rr.fetch(Rr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Rr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){fu.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Rr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Rr.fetch(Rr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>u.data),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Rr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){fu.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._cache.get(Rr.getCacheKey(e,r));if(n)return n;for(let i of this._getShuffledServers())try{let o=await(await Rr.fetch(Rr.buildResource({serverResolver:i,hostname:e,recordType:r}))).json(),a=o.Answer.map(u=>[u.data.replace(/['"]+/g,"")]),c=Math.min(o.Answer.map(u=>u.TTL));return this._cache.set(Rr.getCacheKey(e,r),a,{ttl:c}),a}catch(s){fu.error(`${i} could not resolve ${e} record ${r}`)}throw new Error(`Could not resolve ${e} record ${r}`)}};du.Resolver=du;bE.exports=du});var SE=b((EF,_E)=>{"use strict";var fO=wE();_E.exports=fO});var AE=b((bF,xE)=>{"use strict";var dO=ma(),{code:hO}=dO("dnsaddr");async function pO(t){let e=SE(),r=new e,n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===hO)||[],o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n&&(o=o.filter(a=>a.includes(n))),o}xE.exports={dnsaddrResolver:pO}});var hu=b((wF,CE)=>{"use strict";CE.exports={DIAL_TIMEOUT:3e4,MAX_PARALLEL_DIALS:100,MAX_PER_PEER_DIALS:4,MAX_ADDRS_TO_DIAL:25,METRICS:{computeThrottleMaxQueueSize:1e3,computeThrottleTimeout:2e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3],maxOldPeersRetention:50}}});var bd=b((_F,yO)=>{yO.exports={name:"libp2p",version:"0.36.2",description:"JavaScript implementation of libp2p, a modular peer to peer network stack",leadMaintainer:"Jacob Heun ",main:"src/index.js",types:"dist/src/index.d.ts",typesVersions:{"*":{"src/*":["dist/src/*","dist/src/*/index"]}},files:["dist","src"],scripts:{lint:"aegir lint",build:"aegir build","build:proto":"npm run build:proto:circuit && npm run build:proto:fetch && npm run build:proto:identify && npm run build:proto:plaintext && npm run build:proto:address-book && npm run build:proto:proto-book && npm run build:proto:peer && npm run build:proto:peer-record && npm run build:proto:envelope","build:proto:circuit":"pbjs -t static-module -w commonjs -r libp2p-circuit --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/circuit/protocol/index.js ./src/circuit/protocol/index.proto","build:proto:fetch":"pbjs -t static-module -w commonjs -r libp2p-fetch --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/fetch/proto.js ./src/fetch/proto.proto","build:proto:identify":"pbjs -t static-module -w commonjs -r libp2p-identify --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/identify/message.js ./src/identify/message.proto","build:proto:plaintext":"pbjs -t static-module -w commonjs -r libp2p-plaintext --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/insecure/proto.js ./src/insecure/proto.proto","build:proto:peer":"pbjs -t static-module -w commonjs -r libp2p-peer --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/peer-store/pb/peer.js ./src/peer-store/pb/peer.proto","build:proto:peer-record":"pbjs -t static-module -w commonjs -r libp2p-peer-record --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/peer-record/peer-record.js ./src/record/peer-record/peer-record.proto","build:proto:envelope":"pbjs -t static-module -w commonjs -r libp2p-envelope --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/envelope/envelope.js ./src/record/envelope/envelope.proto","build:proto-types":"npm run build:proto-types:circuit && npm run build:proto-types:fetch && npm run build:proto-types:identify && npm run build:proto-types:plaintext && npm run build:proto-types:address-book && npm run build:proto-types:proto-book && npm run build:proto-types:peer && npm run build:proto-types:peer-record && npm run build:proto-types:envelope","build:proto-types:circuit":"pbts -o src/circuit/protocol/index.d.ts src/circuit/protocol/index.js","build:proto-types:fetch":"pbts -o src/fetch/proto.d.ts src/fetch/proto.js","build:proto-types:identify":"pbts -o src/identify/message.d.ts src/identify/message.js","build:proto-types:plaintext":"pbts -o src/insecure/proto.d.ts src/insecure/proto.js","build:proto-types:peer":"pbts -o src/peer-store/pb/peer.d.ts src/peer-store/pb/peer.js","build:proto-types:peer-record":"pbts -o src/record/peer-record/peer-record.d.ts src/record/peer-record/peer-record.js","build:proto-types:envelope":"pbts -o src/record/envelope/envelope.d.ts src/record/envelope/envelope.js",test:"aegir test","test:ts":"aegir build --no-bundle && npm run test --prefix test/ts-use","test:node":'aegir test -t node -f "./test/**/*.{node,spec}.js"',"test:browser":"aegir test -t browser","test:examples":"cd examples && npm run test:all","test:interop":"LIBP2P_JS=$PWD npx aegir test -t node -f ./node_modules/libp2p-interop/test/*",prepare:"npm run build",coverage:"nyc --reporter=text --reporter=lcov npm run test:node"},repository:{type:"git",url:"https://github.com/libp2p/js-libp2p.git"},keywords:["libp2p","network","p2p","peer","peer-to-peer","IPFS"],bugs:{url:"https://github.com/libp2p/js-libp2p/issues"},homepage:"https://libp2p.io",license:"MIT",engines:{node:">=15.0.0"},browser:{"nat-api":!1},eslintConfig:{extends:"ipfs",ignorePatterns:["!.aegir.js","test/ts-use","*.d.ts"]},dependencies:{"@vascosantos/moving-average":"^1.1.0","abortable-iterator":"^3.0.0","aggregate-error":"^3.1.0","any-signal":"^3.0.0","bignumber.js":"^9.0.1","class-is":"^1.1.0","datastore-core":"^7.0.0",debug:"^4.3.1","err-code":"^3.0.0","es6-promisify":"^7.0.0",events:"^3.3.0",hashlru:"^2.3.0","interface-datastore":"^6.0.2","it-all":"^1.0.4","it-buffer":"^0.1.2","it-drain":"^1.0.3","it-filter":"^1.0.1","it-first":"^1.0.4","it-foreach":"^0.1.1","it-handshake":"^2.0.0","it-length-prefixed":"^5.0.2","it-map":"^1.0.4","it-merge":"^1.0.0","it-pipe":"^1.1.0","it-sort":"^1.0.1","it-take":"^1.0.0","libp2p-crypto":"^0.21.2","libp2p-interfaces":"^4.0.0","libp2p-utils":"^0.4.0",mafmt:"^10.0.0","merge-options":"^3.0.4",mortice:"^2.0.1",multiaddr:"^10.0.0",multiformats:"^9.0.0","multistream-select":"^3.0.0","mutable-proxy":"^1.0.0","nat-api":"^0.3.1","node-forge":"^1.2.1","p-any":"^3.0.0","p-fifo":"^1.0.0","p-retry":"^4.4.0","p-settle":"^4.1.1","peer-id":"^0.16.0","private-ip":"^2.1.0",protobufjs:"^6.10.2",retimer:"^3.0.0","sanitize-filename":"^1.6.3","set-delayed-interval":"^1.0.0","streaming-iterables":"^6.0.0","timeout-abort-controller":"^3.0.0",uint8arrays:"^3.0.0",varint:"^6.0.0",wherearewe:"^1.0.0",xsalsa20:"^1.1.0"},devDependencies:{"@chainsafe/libp2p-noise":"^5.0.0","@nodeutils/defaults-deep":"^1.1.0","@types/es6-promisify":"^6.0.0","@types/node":"^16.0.1","@types/node-forge":"^1.0.0","@types/varint":"^6.0.0",aegir:"^36.0.0",buffer:"^6.0.3",delay:"^5.0.0","into-stream":"^6.0.0","ipfs-http-client":"^54.0.2","it-concat":"^2.0.0","it-pair":"^1.0.0","it-pushable":"^1.4.0",libp2p:".","libp2p-bootstrap":"^0.14.0","libp2p-delegated-content-routing":"^0.11.0","libp2p-delegated-peer-routing":"^0.11.1","libp2p-interfaces-compliance-tests":"^4.0.8","libp2p-interop":"^0.7.1","libp2p-kad-dht":"^0.28.6","libp2p-mdns":"^0.18.0","libp2p-mplex":"^0.10.4","libp2p-tcp":"^0.17.0","libp2p-webrtc-star":"^0.25.0","libp2p-websockets":"^0.16.0",nock:"^13.0.3","p-defer":"^3.0.0","p-times":"^3.0.0","p-wait-for":"^3.2.0",rimraf:"^3.0.2",sinon:"^12.0.1",util:"^0.12.3"},contributors:["Vasco Santos ","David Dias ","Jacob Heun ","Alex Potsides ","Alan Shaw ","Cayman ","Pedro Teixeira ","Friedel Ziegelmayer ","Maciej Kr\xFCger ","Hugo Dias ","dirkmc ","Volker Mische ","Chris Dostert ","zeim839 <50573884+zeim839@users.noreply.github.com>","Robert Kiel ","Richard Littauer ","a1300 ","Ryan Bell ","\u1D20\u026A\u1D04\u1D1B\u1D0F\u0280 \u0299\u1D0A\u1D07\u029F\u1D0B\u029C\u1D0F\u029F\u1D0D ","Andrew Nesbitt ","Franck Royer ","Thomas Eizinger ","V\xEDt Habada ","Giovanni T. Parra ","acolytec3 <17355484+acolytec3@users.noreply.github.com>","Alan Smithee ","Elven ","Samlior ","Didrik Nordstr\xF6m ","Aditya Bose <13054902+adbose@users.noreply.github.com>","TJKoury ","TheStarBoys <41286328+TheStarBoys@users.noreply.github.com>","Tiago Alves ","Tim Daubensch\xFCtz ","XiaoZhang ","Yusef Napora ","Zane Starr ","ebinks ","greenSnot ","isan_rivkin ","mayerwin ","mcclure ","patrickwoodhead <91056047+patrickwoodhead@users.noreply.github.com>","phillmac ","robertkiel ","shresthagrawal <34920931+shresthagrawal@users.noreply.github.com>","swedneck <40505480+swedneck@users.noreply.github.com>","tuyennhv ","S\xF6nke Hahn ","Aleksei ","Bernd Strehl ","Chris Bratlien ","Cindy Wu ","Daijiro Wachi ","Diogo Silva ","Dmitriy Ryajov ","Ethan Lam ","Fei Liu ","Felipe Martins ","Florian-Merle ","Francis Gulotta ","Guy Sviry <32539816+guysv@users.noreply.github.com>","Henrique Dias ","Irakli Gozalishvili ","Joel Gustafson ","John Rees ","Jo\xE3o Santos ","Julien Bouquillon ","Kevin Kwok ","Kevin Lacker ","Lars Gierth ","Leask Wong ","Marcin Tojek ","Marston Connell <34043723+TheMarstonConnell@users.noreply.github.com>","Michael Burns <5170+mburns@users.noreply.github.com>","Miguel Mota ","Nuno Nogueira ","Philipp Muens ","RasmusErik Voel Jensen ","Smite Chow ","Soeren "]}});var wd=b((SF,gn)=>{"use strict";var gO=bd().version;gn.exports.PROTOCOL_VERSION="ipfs/0.1.0";gn.exports.AGENT_VERSION=`js-libp2p/${gO}`;gn.exports.MULTICODEC_IDENTIFY="/ipfs/id/1.0.0";gn.exports.MULTICODEC_IDENTIFY_PUSH="/ipfs/id/push/1.0.0";gn.exports.IDENTIFY_PROTOCOL_VERSION="0.1.0";gn.exports.MULTICODEC_IDENTIFY_PROTOCOL_NAME="id";gn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME="id/push";gn.exports.MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0";gn.exports.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION="1.0.0"});var pu=b((xF,TE)=>{"use strict";var IE=60*1e3;TE.exports={ADVERTISE_BOOT_DELAY:15*IE,ADVERTISE_TTL:30*IE,CIRCUIT_PROTO_CODE:290,HOP_METADATA_KEY:"hop_relay",HOP_METADATA_VALUE:"true",RELAY_RENDEZVOUS_NS:"/libp2p/relay"}});var RE=b(Ca=>{(function(){var t,e,r,n,i,s,o,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&255<<8)>>>8,d=c&255,[u,l,f,d].join(".")},o=function(c){var u,l,f,d,p,h;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=e(c),p=h[0],l=h[1],c=c.substring(l),u.push(p)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},r=function(c){return c.charCodeAt(0)},n=r("0"),s=r("a"),i=r("A"),e=function(c){var u,l,f,d,p;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),p=f;f>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+r(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+r(c[f])-i)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===p)throw new Error("empty octet");return[d,f]},t=function(){function c(u,l){var f,d,p,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(h=u.split("/",2),u=h[0],l=h[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=p=32;p>=0;d=--p)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=o(this.first),f=o(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Ca.ip2long=o,Ca.long2ip=a,Ca.Netmask=t}).call(Ca)});var PE=b((BE,yu)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(p,h){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let g=0,v=-1,w=(p.match(a.zoneIndex)||[])[0],C,q;for(w&&(w=w.substring(1),p=p.replace(/%.+$/,""));(v=p.indexOf(":",v+1))>=0;)g++;if(p.substr(0,2)==="::"&&g--,p.substr(-2,2)==="::"&&g--,g>h)return null;for(q=h-g,C=":";q--;)C+="0:";return p=p.replace("::",C),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),h=function(){let W=p.split(":"),F=[];for(let M=0;M0;){if(C=g-v,C<0&&(C=0),p[w]>>C!=h[w]>>C)return!1;v-=g,w+=1}return!0}function l(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function f(p,h){for(;p.length=0;w-=1)if(C=this.octets[w],C in v){if(q=v[C],g&&q!==0)return null;q!==8&&(g=!0),h+=q}else return null;return 32-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return d.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p}(),d.IPv4.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),v=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),w=[],C=0;for(;C<4;)w.push(parseInt(g[C],10)|parseInt(v[C],10)^255),C++;return new this(w)}catch(h){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.isIPv4=function(p){return this.parser(p)!==null},d.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch(h){return!1}},d.IPv4.isValidFourPartDecimal=function(p){return!!(d.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},d.IPv4.networkAddressFromCIDR=function(p){let h,g,v,w,C;try{for(h=this.parseCIDR(p),v=h[0].toByteArray(),C=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),w=[],g=0;g<4;)w.push(parseInt(v[g],10)&parseInt(C[g],10)),g++;return new this(w)}catch(q){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.parse=function(p){let h=this.parser(p);if(h===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(h)},d.IPv4.parseCIDR=function(p){let h;if(h=p.match(/^(.+)\/(\d+)$/)){let g=parseInt(h[2]);if(g>=0&&g<=32){let v=[this.parse(h[1]),g];return Object.defineProperty(v,"toString",{value:function(){return this.join("/")}}),v}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},d.IPv4.parser=function(p){let h,g,v;if(h=p.match(r.fourOctet))return function(){let w=h.slice(1,6),C=[];for(let q=0;q4294967295||v<0)throw new Error("ipaddr: address outside defined range");return function(){let w=[],C;for(C=0;C<=24;C+=8)w.push(v>>C&255);return w}().reverse()}else return(h=p.match(r.twoOctet))?function(){let w=h.slice(1,4),C=[];if(v=l(w[1]),v>16777215||v<0)throw new Error("ipaddr: address outside defined range");return C.push(l(w[0])),C.push(v>>16&255),C.push(v>>8&255),C.push(v&255),C}():(h=p.match(r.threeOctet))?function(){let w=h.slice(1,5),C=[];if(v=l(w[2]),v>65535||v<0)throw new Error("ipaddr: address outside defined range");return C.push(l(w[0])),C.push(l(w[1])),C.push(v>>8&255),C.push(v&255),C}():null},d.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let h=[0,0,0,0],g=0,v=Math.floor(p/8);for(;g=0;q-=1)if(w=this.parts[q],w in v){if(C=v[w],g&&C!==0)return null;C!==16&&(g=!0),h+=C}else return null;return 128-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let h,g=[],v=this.parts;for(let w=0;w>8),g.push(h&255);return g},p.prototype.toFixedLengthString=function(){let h=function(){let v=[];for(let w=0;w>8,g&255,v>>8,v&255])},p.prototype.toNormalizedString=function(){let h=function(){let v=[];for(let w=0;ww&&(v=C.index,w=C[0].length);return w<0?g:`${g.substring(0,v)}::${g.substring(v+w)}`},p.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},p}(),d.IPv6.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),g=h[0].toByteArray(),v=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),w=[],C=0;for(;C<16;)w.push(parseInt(g[C],10)|parseInt(v[C],10)^255),C++;return new this(w)}catch(h){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${h})`)}},d.IPv6.isIPv6=function(p){return this.parser(p)!==null},d.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{let h=this.parser(p);return new this(h.parts,h.zoneId),!0}catch(h){return!1}},d.IPv6.networkAddressFromCIDR=function(p){let h,g,v,w,C;try{for(h=this.parseCIDR(p),v=h[0].toByteArray(),C=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),w=[],g=0;g<16;)w.push(parseInt(v[g],10)&parseInt(C[g],10)),g++;return new this(w)}catch(q){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${q})`)}},d.IPv6.parse=function(p){let h=this.parser(p);if(h.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(h.parts,h.zoneId)},d.IPv6.parseCIDR=function(p){let h,g,v;if((g=p.match(/^(.+)\/(\d+)$/))&&(h=parseInt(g[2]),h>=0&&h<=128))return v=[this.parse(g[1]),h],Object.defineProperty(v,"toString",{value:function(){return this.join("/")}}),v;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},d.IPv6.parser=function(p){let h,g,v,w,C,q;if(v=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${v[1]}`);if(a.native.test(p))return c(p,8);if((v=p.match(a.transitional))&&(q=v[6]||"",h=c(v[1].slice(0,-1)+q,6),h.parts)){for(C=[parseInt(v[2]),parseInt(v[3]),parseInt(v[4]),parseInt(v[5])],g=0;g128)throw new Error("ipaddr: invalid IPv6 prefix length");let h=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,v=Math.floor(p/8);for(;g{"use strict";var NE=Ia&&Ia.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ia,"__esModule",{value:!0});var mO=RE(),vO=NE(Mf()),EO=NE(Kf()),OE=PE(),bO=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],wO=bO.map(t=>new mO.Netmask(t));function _O(t){for(let e of wO)if(e.contains(t))return!0;return!1}function DE(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}Ia.default=t=>{if(OE.isValid(t)){let e=OE.parse(t);if(e.kind()==="ipv4")return _O(e.toNormalizedString());if(e.kind()==="ipv6")return DE(t)}else if(EO.default(t)&&vO.default.v6().test(t))return DE(t)}});var _d=b((IF,kE)=>{"use strict";kE.exports=LE().default});var UE=b((TF,qE)=>{"use strict";var SO=_d();function xO(t){let{address:e}=t.nodeAddress();return SO(e)}qE.exports=xO});var Sd=b((RF,FE)=>{"use strict";var ME=UE();function AO(t,e){let r=ME(t.multiaddr),n=ME(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function CO(t){return[...t].sort(AO)}FE.exports.publicAddressesFirst=CO});var VE=b((BF,xd)=>{"use strict";var KE=async t=>{try{let e=await t;return{isFulfilled:!0,isRejected:!1,value:e}}catch(e){return{isFulfilled:!1,isRejected:!0,reason:e}}};xd.exports=KE;xd.exports.default=KE});var $E=b((PF,Ad)=>{"use strict";var jE=(t,...e)=>new Promise(r=>{r(t(...e))});Ad.exports=jE;Ad.exports.default=jE});var zE=b((NF,Cd)=>{"use strict";var IO=$E(),HE=t=>{if(!((Number.isInteger(t)||t===1/0)&&t>0))return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"));let e=[],r=0,n=()=>{r--,e.length>0&&e.shift()()},i=(a,c,...u)=>{r++;let l=IO(a,...u);c(l),l.then(n,n)},s=(a,c,...u)=>{rnew Promise(u=>s(a,u,...c));return Object.defineProperties(o,{activeCount:{get:()=>r},pendingCount:{get:()=>e.length},clearQueue:{value:()=>{e.length=0}}}),o};Cd.exports=HE;Cd.exports.default=HE});var WE=b((OF,GE)=>{"use strict";var Id=VE(),TO=zE();GE.exports=async(t,e={})=>{let{concurrency:r=1/0}=e,n=TO(r);return Promise.all(t.map(i=>i&&typeof i.then=="function"?Id(i):Id(typeof i=="function"?n(()=>i()):Promise.resolve(i))))}});var XE=b((DF,QE)=>{"use strict";var Xs=Sn(),YE=Xs.Reader,RO=Xs.Writer,at=Xs.util,Ta=Xs.roots["libp2p-envelope"]||(Xs.roots["libp2p-envelope"]={});Ta.Envelope=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.publicKey=r.bytes();break;case 2:s.payloadType=r.bytes();break;case 3:s.payload=r.bytes();break;case 5:s.signature=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Ta.Envelope)return r;var n=new Ta.Envelope;return r.publicKey!=null&&(typeof r.publicKey=="string"?at.base64.decode(r.publicKey,n.publicKey=at.newBuffer(at.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.payloadType!=null&&(typeof r.payloadType=="string"?at.base64.decode(r.payloadType,n.payloadType=at.newBuffer(at.base64.length(r.payloadType)),0):r.payloadType.length&&(n.payloadType=r.payloadType)),r.payload!=null&&(typeof r.payload=="string"?at.base64.decode(r.payload,n.payload=at.newBuffer(at.base64.length(r.payload)),0):r.payload.length&&(n.payload=r.payload)),r.signature!=null&&(typeof r.signature=="string"?at.base64.decode(r.signature,n.signature=at.newBuffer(at.base64.length(r.signature)),0):r.signature.length&&(n.signature=r.signature)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(n.bytes===String?i.publicKey="":(i.publicKey=[],n.bytes!==Array&&(i.publicKey=at.newBuffer(i.publicKey))),n.bytes===String?i.payloadType="":(i.payloadType=[],n.bytes!==Array&&(i.payloadType=at.newBuffer(i.payloadType))),n.bytes===String?i.payload="":(i.payload=[],n.bytes!==Array&&(i.payload=at.newBuffer(i.payload))),n.bytes===String?i.signature="":(i.signature=[],n.bytes!==Array&&(i.signature=at.newBuffer(i.signature)))),r.publicKey!=null&&r.hasOwnProperty("publicKey")&&(i.publicKey=n.bytes===String?at.base64.encode(r.publicKey,0,r.publicKey.length):n.bytes===Array?Array.prototype.slice.call(r.publicKey):r.publicKey),r.payloadType!=null&&r.hasOwnProperty("payloadType")&&(i.payloadType=n.bytes===String?at.base64.encode(r.payloadType,0,r.payloadType.length):n.bytes===Array?Array.prototype.slice.call(r.payloadType):r.payloadType),r.payload!=null&&r.hasOwnProperty("payload")&&(i.payload=n.bytes===String?at.base64.encode(r.payload,0,r.payload.length):n.bytes===Array?Array.prototype.slice.call(r.payload):r.payload),r.signature!=null&&r.hasOwnProperty("signature")&&(i.signature=n.bytes===String?at.base64.encode(r.signature,0,r.signature.length):n.bytes===Array?Array.prototype.slice.call(r.signature):r.signature),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Xs.util.toJSONOptions)},t}();QE.exports=Ta});var mu=b((LF,eb)=>{"use strict";var BO=ge(),{concat:PO}=(ei(),Jn),{fromString:NO}=(Dt(),Ft),OO=Wc(),DO=qt(),Td=Ki(),{equals:gu}=(Sr(),_r),{codes:LO}=Ye(),{Envelope:ZE}=XE(),li=class{constructor({peerId:e,payloadType:r,payload:n,signature:i}){this.peerId=e,this.payloadType=r,this.payload=n,this.signature=i,this._marshal=void 0}marshal(){if(this._marshal)return this._marshal;let e=OO.marshalPublicKey(this.peerId.pubKey);return this._marshal=ZE.encode({publicKey:e,payloadType:this.payloadType,payload:this.payload,signature:this.signature}).finish(),this._marshal}equals(e){return gu(this.peerId.pubKey.bytes,e.peerId.pubKey.bytes)&&gu(this.payloadType,e.payloadType)&&gu(this.payload,e.payload)&&gu(this.signature,e.signature)}validate(e){let r=JE(e,this.payloadType,this.payload);return this.peerId.pubKey.verify(r,this.signature)}},JE=(t,e,r)=>{let n=NO(t),i=Td.encode(n.byteLength),s=Td.encode(e.length),o=Td.encode(r.length);return PO([new Uint8Array(i),n,new Uint8Array(s),e,new Uint8Array(o),r])};li.createFromProtobuf=async t=>{let e=ZE.decode(t),r=await DO.createFromPubKey(e.publicKey);return new li({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};li.seal=async(t,e)=>{let r=t.domain,n=t.codec,i=t.marshal(),s=JE(r,n,i),o=await e.privKey.sign(s);return new li({peerId:e,payloadType:n,payload:i,signature:o})};li.openAndCertify=async(t,e)=>{let r=await li.createFromProtobuf(t);if(!await r.validate(e))throw BO(new Error("envelope signature is not valid for the given domain"),LO.ERR_SIGNATURE_NOT_VALID);return r};eb.exports=li});var rb=b((kF,tb)=>{"use strict";function kO(t,e){return t.length===e.length&&e.sort()&&t.sort().every((r,n)=>e[n].equals(r))}tb.exports=kO});var sb=b((qF,ib)=>{"use strict";var Gi=Sn(),vu=Gi.Reader,nb=Gi.Writer,yt=Gi.util,Br=Gi.roots["libp2p-peer-record"]||(Gi.roots["libp2p-peer-record"]={});Br.PeerRecord=function(){function t(e){if(this.addresses=[],e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.peerId=r.bytes();break;case 2:s.seq=r.uint64();break;case 3:s.addresses&&s.addresses.length||(s.addresses=[]),s.addresses.push(Br.PeerRecord.AddressInfo.decode(r,r.uint32()));break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Br.PeerRecord)return r;var n=new Br.PeerRecord;if(r.peerId!=null&&(typeof r.peerId=="string"?yt.base64.decode(r.peerId,n.peerId=yt.newBuffer(yt.base64.length(r.peerId)),0):r.peerId.length&&(n.peerId=r.peerId)),r.seq!=null&&(yt.Long?(n.seq=yt.Long.fromValue(r.seq)).unsigned=!0:typeof r.seq=="string"?n.seq=parseInt(r.seq,10):typeof r.seq=="number"?n.seq=r.seq:typeof r.seq=="object"&&(n.seq=new yt.LongBits(r.seq.low>>>0,r.seq.high>>>0).toNumber(!0))),r.addresses){if(!Array.isArray(r.addresses))throw TypeError(".PeerRecord.addresses: array expected");n.addresses=[];for(var i=0;i>>0,r.seq.high>>>0).toNumber(!0):r.seq),r.addresses&&r.addresses.length){i.addresses=[];for(var o=0;o>>3){case 1:o.multiaddr=n.bytes();break;default:n.skipType(a&7);break}}return o},e.fromObject=function(n){if(n instanceof Br.PeerRecord.AddressInfo)return n;var i=new Br.PeerRecord.AddressInfo;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?yt.base64.decode(n.multiaddr,i.multiaddr=yt.newBuffer(yt.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),i},e.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=yt.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?yt.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,Gi.util.toJSONOptions)},e}(),t}();ib.exports=Br});var ab=b((UF,ob)=>{"use strict";var qO="libp2p-peer-record",UO=Uint8Array.from([3,1]);ob.exports={ENVELOPE_DOMAIN_PEER_RECORD:qO,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:UO}});var Eu=b((MF,lb)=>{"use strict";var{Multiaddr:MO}=$t(),FO=qt(),KO=rb(),{PeerRecord:cb}=sb(),{ENVELOPE_DOMAIN_PEER_RECORD:ub,ENVELOPE_PAYLOAD_TYPE_PEER_RECORD:VO}=ab(),Wi=class{constructor({peerId:e,multiaddrs:r=[],seqNumber:n=Date.now()}){this.domain=ub,this.codec=VO,this.peerId=e,this.multiaddrs=r,this.seqNumber=n,this._marshal=void 0}marshal(){return this._marshal?this._marshal:(this._marshal=cb.encode({peerId:this.peerId.toBytes(),seq:this.seqNumber,addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))}).finish(),this._marshal)}equals(e){return!(!(e instanceof Wi)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!KO(this.multiaddrs,e.multiaddrs))}};Wi.createFromProtobuf=t=>{let e=cb.decode(t),r=FO.createFromBytes(e.peerId),n=(e.addresses||[]).map(s=>new MO(s.multiaddr)),i=Number(e.seq);return new Wi({peerId:r,multiaddrs:n,seqNumber:i})};Wi.DOMAIN=ub;lb.exports=Wi});var Rd=b((FF,fb)=>{"use strict";var jO=mu(),$O=Eu();async function HO(t){let e=new $O({peerId:t.peerId,multiaddrs:t.multiaddrs}),r=await jO.seal(e,t.peerId);await t.peerStore.addressBook.consumePeerRecord(r)}fb.exports.updateSelfPeerRecord=HO});var Pd=b((KF,pb)=>{"use strict";var db=Oe(),Yi=Object.assign(db("libp2p:transports"),{error:db("libp2p:transports:err")}),zO=WE(),{codes:Zs}=Ye(),Ra=ge(),{updateSelfPeerRecord:hb}=Rd(),Bd=class{constructor({libp2p:e,upgrader:r,faultTolerance:n=bu.FATAL_ALL}){this.libp2p=e,this.upgrader=r,this._transports=new Map,this._listeners=new Map,this._listenerOptions=new Map,this.faultTolerance=n}add(e,r,n={}){if(Yi("adding %s",e),!e)throw Ra(new Error(`Transport must have a valid key, was given '${e}'`),Zs.ERR_INVALID_KEY);if(this._transports.has(e))throw Ra(new Error("There is already a transport with this key"),Zs.ERR_DUPLICATE_TRANSPORT);let i=new r({...n,libp2p:this.libp2p,upgrader:this.upgrader});this._transports.set(e,i),this._listenerOptions.set(e,n.listenerOptions||{}),this._listeners.has(e)||this._listeners.set(e,[])}async close(){let e=[];for(let[r,n]of this._listeners)for(Yi("closing listeners for %s",r);n.length;){let i=n.pop();i.removeAllListeners("listening"),i.removeAllListeners("close"),e.push(i.close())}await Promise.all(e),Yi("all listeners closed");for(let r of this._listeners.keys())this._listeners.set(r,[])}async dial(e,r){let n=this.transportForMultiaddr(e);if(!n)throw Ra(new Error(`No transport available for address ${String(e)}`),Zs.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,r)}catch(i){throw i.code||(i.code=Zs.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this._listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return this._transports.values()}transportForMultiaddr(e){for(let r of this._transports.values())if(r.filter([e]).length)return r;return null}async listen(e){if(!e||e.length===0){Yi("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this._transports.entries()){let s=i.filter(e),o=[];for(let u of s){Yi("creating listener for %s on %s",n,u);let l=i.createListener(this._listenerOptions.get(n));this._listeners.get(n).push(l),l.on("listening",()=>hb(this.libp2p)),l.on("close",()=>hb(this.libp2p)),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if(!(await zO(o)).find(u=>u.isFulfilled===!0)&&this.faultTolerance!==bu.NO_FATAL)throw Ra(new Error(`Transport (${n}) could not listen on any available address`),Zs.ERR_NO_VALID_ADDRESSES)}if(r.length===this._transports.size){let n=`no valid addresses were provided for transports [${r}]`;if(this.faultTolerance===bu.FATAL_ALL)throw Ra(new Error(n),Zs.ERR_NO_VALID_ADDRESSES);Yi(`libp2p in dial mode only: ${n}`)}}async remove(e){if(Yi("removing %s",e),this._listeners.has(e))for(let r of this._listeners.get(e))r.removeAllListeners("listening"),r.removeAllListeners("close"),await r.close();this._transports.delete(e),this._listeners.delete(e)}async removeAll(){let e=[];for(let r of this._transports.keys())e.push(this.remove(r));await Promise.all(e)}},bu={FATAL_ALL:0,NO_FATAL:1};Bd.FaultTolerance=bu;pb.exports=Bd});var mb=b((VF,gb)=>{"use strict";var GO=Ys(),{dnsaddrResolver:WO}=AE(),Nd=hu(),{AGENT_VERSION:YO}=wd(),yb=pu(),{publicAddressesFirst:QO}=Sd(),{FaultTolerance:XO}=Pd(),ZO={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{minConnections:25},connectionGater:{},transportManager:{faultTolerance:XO.FATAL_ALL},dialer:{maxParallelDials:Nd.MAX_PARALLEL_DIALS,maxDialsPerPeer:Nd.MAX_PER_PEER_DIALS,dialTimeout:Nd.DIAL_TIMEOUT,resolvers:{dnsaddr:WO},addressSorter:QO},host:{agentVersion:YO},metrics:{enabled:!1},peerStore:{persistence:!1,threshold:5},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},config:{protocolPrefix:"ipfs",dht:{enabled:!1,kBucketSize:20},nat:{enabled:!0,ttl:7200,keepAlive:!0,gateway:null,externalIp:null,pmp:{enabled:!1}},peerDiscovery:{autoDial:!0},pubsub:{enabled:!0},relay:{enabled:!0,advertise:{bootDelay:yb.ADVERTISE_BOOT_DELAY,enabled:!1,ttl:yb.ADVERTISE_TTL},hop:{enabled:!1,active:!1},autoRelay:{enabled:!1,maxListeners:2}},transport:{}}};gb.exports.validate=t=>{let e=GO(ZO,t);if(e.modules.transport.length<1)throw new Error("'options.modules.transport' must contain at least 1 transport");return e}});var bb=b((jF,Eb)=>{"use strict";var{EventEmitter:JO}=rr(),{Multiaddr:Ba}=$t(),e3=qt(),vb=class extends JO{constructor(e,{listen:r=[],announce:n=[]}={}){super();this.peerId=e,this.listen=new Set(r.map(i=>i.toString())),this.announce=new Set(n.map(i=>i.toString())),this.observed=new Set}getListenAddrs(){return Array.from(this.listen).map(e=>new Ba(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>new Ba(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>new Ba(e))}addObservedAddr(e){let r=new Ba(e),n=r.getPeerId();n&&e3.createFromB58String(n).equals(this.peerId)&&(r=r.decapsulate(new Ba(`/p2p/${this.peerId}`)));let i=r.toString();this.observed.has(i)||(this.observed.add(i),this.emit("change:addresses"))}};Eb.exports=vb});var Sb=b(($F,_b)=>{"use strict";var{EventEmitter:t3}=rr(),Od=Oe()("latency-monitor:VisibilityChangeEmitter"),wb=class extends t3{constructor(){super();if(typeof document=="undefined"){Od('This is not a browser, no "document" found. Stopping.');return}this._initializeVisibilityVarNames(),this._addVisibilityChangeListener()}_initializeVisibilityVarNames(){let e,r;typeof document.hidden!="undefined"?(e="hidden",r="visibilitychange"):typeof document.mozHidden!="undefined"?(e="mozHidden",r="mozvisibilitychange"):typeof document.msHidden!="undefined"?(e="msHidden",r="msvisibilitychange"):typeof document.webkitHidden!="undefined"&&(e="webkitHidden",r="webkitvisibilitychange"),this._hidden=e,this._visibilityChange=r}_addVisibilityChangeListener(){typeof document.addEventListener=="undefined"||typeof document[this._hidden]=="undefined"?Od("Checking page visibility requires a browser that supports the Page Visibility API."):document.addEventListener(this._visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(!(this._hidden===void 0||document[this._hidden]===void 0))return!document[this._hidden]}_handleVisibilityChange(){let e=!document[this._hidden];Od(e?"Page Visible":"Page Hidden"),this.emit("visibilityChange",e)}};_b.exports=wb});var Cb=b((HF,Ab)=>{"use strict";var{EventEmitter:r3}=rr(),n3=Sb(),Nn=Oe()("latency-monitor:LatencyMonitor"),xb=class extends r3{constructor({latencyCheckIntervalMs:e,dataEmitIntervalMs:r,asyncTestFn:n,latencyRandomPercentage:i}={}){super();let s=this;s.latencyCheckIntervalMs=e||500,s.latencyRandomPercentage=i||10,s._latecyCheckMultiply=2*(s.latencyRandomPercentage/100)*s.latencyCheckIntervalMs,s._latecyCheckSubtract=s._latecyCheckMultiply/2,s.dataEmitIntervalMs=r===null||r===0?void 0:r||5*1e3,Nn("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",s.latencyCheckIntervalMs,s.dataEmitIntervalMs),s.dataEmitIntervalMs?Nn("Expecting ~%s events per summary",s.latencyCheckIntervalMs/s.dataEmitIntervalMs):Nn("Not emitting summaries"),s.asyncTestFn=n}start(){globalThis.process&&globalThis.process.hrtime?(Nn("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=e=>{let r=this.now(e);return r[0]*1e3+r[1]/1e6}):typeof window!="undefined"&&window.performance&&window.performance.now?(Nn("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=e=>Math.round(this.now()-e)):(Nn("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=e=>this.now()-e),this._latencyData=this._initLatencyData(),i3()&&(this._visibilityChangeEmitter=new n3,this._visibilityChangeEmitter.on("visibilityChange",e=>{e?this._startTimers():(this._emitSummary(),this._stopTimers())})),(!this._visibilityChangeEmitter||this._visibilityChangeEmitter.isVisible())&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){this._checkLatencyID||(this._checkLatency(),this.dataEmitIntervalMs&&(this._emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),typeof this._emitIntervalID.unref=="function"&&this._emitIntervalID.unref()))}_stopTimers(){this._checkLatencyID&&(clearTimeout(this._checkLatencyID),this._checkLatencyID=void 0),this._emitIntervalID&&(clearInterval(this._emitIntervalID),this._emitIntervalID=void 0)}_emitSummary(){let e=this.getSummary();e.events>0&&this.emit("data",e)}getSummary(){let e={events:this._latencyData.events,minMs:this._latencyData.minMs,maxMs:this._latencyData.maxMs,avgMs:this._latencyData.events?this._latencyData.totalMs/this._latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this._latencyData.startTime)};return this._latencyData=this._initLatencyData(),Nn("Summary: %O",e),e}_checkLatency(){let e=this,r=Math.random()*e._latecyCheckMultiply-e._latecyCheckSubtract,n={deltaOffset:Math.ceil(e.latencyCheckIntervalMs+r),startTime:e.now()},i=()=>{if(!this._checkLatencyID)return;let s=e.getDeltaMS(n.startTime)-n.deltaOffset;e._checkLatency(),e._latencyData.events++,e._latencyData.minMs=Math.min(e._latencyData.minMs,s),e._latencyData.maxMs=Math.max(e._latencyData.maxMs,s),e._latencyData.totalMs+=s,Nn("MS: %s Data: %O",s,e._latencyData)};Nn("localData: %O",n),this._checkLatencyID=setTimeout(()=>{e.asyncTestFn?(n.deltaOffset=0,n.startTime=e.now(),e.asyncTestFn(i)):(n.deltaOffset-=1,i())},n.deltaOffset),typeof this._checkLatencyID.unref=="function"&&this._checkLatencyID.unref()}_initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}};function i3(){return typeof window!="undefined"}Ab.exports=xb});var Dd=b((zF,Tb)=>{"use strict";var Ib=class extends Map{constructor(e){super();let{system:r,component:n,metric:i,metrics:s}=e;this._system=r,this._component=n,this._metric=i,this._metrics=s,this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}set(e,r){return super.set(e,r),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),this}delete(e){let r=super.delete(e);return this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size}),r}clear(){super.clear(),this._metrics.updateComponentMetric({system:this._system,component:this._component,metric:this._metric,value:this.size})}};Tb.exports=({system:t="libp2p",component:e,metric:r,metrics:n})=>{let i;return n?i=new Ib({system:t,component:e,metric:r,metrics:n}):i=new Map,i}});var qb=b((GF,kb)=>{"use strict";var Rb=Oe(),Hr=Object.assign(Rb("libp2p:connection-manager"),{error:Rb("libp2p:connection-manager:err")}),Bb=ge(),s3=Ys(),o3=Cb(),Pb=_a(),{EventEmitter:a3}=rr(),Nb=Dd(),c3=qt(),{codes:{ERR_INVALID_PARAMETERS:Ob}}=Ye(),u3={maxConnections:1/0,minConnections:0,maxData:1/0,maxSentData:1/0,maxReceivedData:1/0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,movingAverageInterval:6e4,defaultPeerValue:1},Db="connection-manager",l3="peer-connections",f3="peer-values",Lb=class extends a3{constructor(e,r={}){super();if(this._libp2p=e,this._peerId=e.peerId.toB58String(),this._options=s3.call({ignoreUndefined:!0},u3,r),this._options.maxConnectionse+r.length,0)}start(){this._libp2p.metrics&&(this._timer=this._timer||Pb(this._checkMetrics,this._options.pollInterval)),this._latencyMonitor.start(),this._onLatencyMeasure=this._onLatencyMeasure.bind(this),this._latencyMonitor.on("data",this._onLatencyMeasure),this._started=!0,Hr("started")}async stop(){this._timer&&this._timer.clear(),this._latencyMonitor.removeListener("data",this._onLatencyMeasure),this._latencyMonitor.stop(),this._started=!1,await this._close(),Hr("stopped")}async _close(){let e=[];for(let r of this.connections.values())for(let n of r)e.push(n.close());await Promise.all(e),this.connections.clear()}setPeerValue(e,r){if(r<0||r>1)throw new Error("value should be a number between 0 and 1");this._peerValues.set(e.toB58String(),r)}async _checkMetrics(){if(this._libp2p.metrics)try{let e=this._libp2p.metrics.global.movingAverages,r=e.dataReceived[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxReceivedData",r);let n=e.dataSent[this._options.movingAverageInterval].movingAverage();await this._checkMaxLimit("maxSentData",n);let i=r+n;await this._checkMaxLimit("maxData",i),Hr("metrics update",i)}finally{this._timer=Pb(this._checkMetrics,this._options.pollInterval)}}async onConnect(e){if(!this._started){await e.close();return}let r=e.remotePeer,n=r.toB58String(),i=this.connections.get(n);this.emit("peer:connect",e),i?i.push(e):this.connections.set(n,[e]),await this._libp2p.peerStore.keyBook.set(r,r.pubKey),this._peerValues.has(n)||this._peerValues.set(n,this._options.defaultPeerValue),await this._checkMaxLimit("maxConnections",this.size)}onDisconnect(e){if(!this._started)return;let r=e.remotePeer.toB58String(),n=this.connections.get(r);n&&n.length>1?(n=n.filter(i=>i.id!==e.id),this.connections.set(r,n)):n&&(this.connections.delete(r),this._peerValues.delete(e.remotePeer.toB58String()),this.emit("peer:disconnect",e),this._libp2p.metrics&&this._libp2p.metrics.onPeerDisconnected(e.remotePeer))}get(e){let r=this.getAll(e);return r.length?r[0]:null}getAll(e){if(!c3.isPeerId(e))throw Bb(new Error("peerId must be an instance of peer-id"),Ob);let r=e.toB58String(),n=this.connections.get(r);return n?n.filter(i=>i.stat.status==="open"):[]}_onLatencyMeasure(e){this._checkMaxLimit("maxEventLoopDelay",e.avgMs).catch(r=>{Hr.error(r)})}async _checkMaxLimit(e,r){let n=this._options[e];Hr("checking limit of %s. current value: %d of %d",e,r,n),r>n&&(Hr("%s: limit exceeded: %s, %d",this._peerId,e,r),await this._maybeDisconnectOne())}async _maybeDisconnectOne(){if(this._options.minConnectionsn[1]-i[1])));Hr("%s: sorted peer values: %j",this._peerId,e);let r=e[0];if(r){let n=r[0];Hr("%s: lowest value peer is %s",this._peerId,n),Hr("%s: closing a connection to %j",this._peerId,n);for(let i of this.connections.values())if(i[0].remotePeer.toB58String()===n){i[0].close().catch(s=>{Hr.error(s)}),this.onDisconnect(i[0]);break}}}}};kb.exports=Lb});var Mb=b((WF,Ub)=>{"use strict";var d3=Vi(),h3=async function*(t,e){yield*(await d3(t)).sort(e)};Ub.exports=h3});var $b=b((YF,jb)=>{"use strict";var Fb=Oe(),p3=Ys(),Kb=_a(),y3=Vi(),{pipe:g3}=fr(),m3=ji(),v3=Mb(),fi=Object.assign(Fb("libp2p:connection-manager:auto-dialler"),{error:Fb("libp2p:connection-manager:auto-dialler:err")}),E3={enabled:!0,minConnections:0,autoDialInterval:1e4},Vb=class{constructor(e,r={}){this._options=p3.call({ignoreUndefined:!0},E3,r),this._libp2p=e,this._running=!1,this._autoDialTimeout=null,this._autoDial=this._autoDial.bind(this),fi("options: %j",this._options)}async start(){if(!this._options.enabled){fi("not enabled");return}this._running=!0,this._autoDial().catch(e=>{fi.error("could start autodial",e)}),fi("started")}async stop(){if(!this._options.enabled){fi("not enabled");return}this._running=!1,this._autoDialTimeout&&this._autoDialTimeout.clear(),fi("stopped")}async _autoDial(){let e=this._options.minConnections;if(this._libp2p.connections.size>=e){this._autoDialTimeout=Kb(this._autoDial,this._options.autoDialInterval);return}let r=await g3(this._libp2p.peerStore.getPeers(),n=>m3(n,i=>!i.id.equals(this._libp2p.peerId)),n=>v3(n,(i,s)=>s.protocols&&s.protocols.length&&(!i.protocols||!i.protocols.length)||s.id.pubKey&&!i.id.pubKey?1:-1),n=>y3(n));for(let n=0;this._running&&n{"use strict";var{Multiaddr:Ld}=$t(),Hb=de("dns4"),zb=de("dns6"),Gb=de("dnsaddr"),Qi=Ht(de("dns"),Gb,Hb,zb),Pa=Ht(de("ip4"),de("ip6")),Js=Ht(we(Pa,de("tcp")),we(Qi,de("tcp"))),kd=we(Pa,de("udp")),Wb=we(kd,de("utp")),Yb=we(kd,de("quic")),eo=Ht(we(Js,de("ws")),we(Qi,de("ws"))),to=Ht(we(Js,de("wss")),we(Qi,de("wss"))),wu=Ht(we(Js,de("http")),we(Pa,de("http")),we(Qi,de("http"))),_u=Ht(we(Js,de("https")),we(Pa,de("https")),we(Qi,de("https"))),qd=Ht(we(eo,de("p2p-webrtc-star"),de("p2p")),we(to,de("p2p-webrtc-star"),de("p2p")),we(eo,de("p2p-webrtc-star")),we(to,de("p2p-webrtc-star"))),b3=Ht(we(eo,de("p2p-websocket-star"),de("p2p")),we(to,de("p2p-websocket-star"),de("p2p")),we(eo,de("p2p-websocket-star")),we(to,de("p2p-websocket-star"))),Ud=Ht(we(wu,de("p2p-webrtc-direct"),de("p2p")),we(_u,de("p2p-webrtc-direct"),de("p2p")),we(wu,de("p2p-webrtc-direct")),we(_u,de("p2p-webrtc-direct"))),ro=Ht(eo,to,wu,_u,qd,Ud,Js,Wb,Yb,Qi),w3=Ht(we(ro,de("p2p-stardust"),de("p2p")),we(ro,de("p2p-stardust"))),di=Ht(we(ro,de("p2p")),qd,Ud,de("p2p")),Qb=Ht(we(di,de("p2p-circuit"),di),we(di,de("p2p-circuit")),we(de("p2p-circuit"),di),we(ro,de("p2p-circuit")),we(de("p2p-circuit"),ro),de("p2p-circuit")),Xb=()=>Ht(we(Qb,Xb),Qb),no=Xb(),Zb=Ht(we(no,di,no),we(di,no),we(no,di),no,di);ew.exports={DNS:Qi,DNS4:Hb,DNS6:zb,DNSADDR:Gb,IP:Pa,TCP:Js,UDP:kd,QUIC:Yb,UTP:Wb,HTTP:wu,HTTPS:_u,WebSockets:eo,WebSocketsSecure:to,WebSocketStar:b3,WebRTCStar:qd,WebRTCDirect:Ud,Reliable:ro,Stardust:w3,Circuit:no,P2P:Zb,IPFS:Zb};function Jb(t){function e(r){if(!Ld.isMultiaddr(r))try{r=new Ld(r)}catch(i){return!1}let n=t(r.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function we(...t){function e(r){if(r.length(n=typeof i=="function"?i().partialMatch(r):i.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Jb(e),partialMatch:e}}function Ht(...t){function e(n){let i=null;return t.some(s=>{let o=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return o?(i=o,!0):!1}),i}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Jb(e),partialMatch:e}}function de(t){let e=t;function r(i){let s;if(typeof i=="string"||i instanceof Uint8Array)try{s=new Ld(i)}catch(a){return!1}else s=i;let o=s.protoNames();return o.length===1&&o[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:r,partialMatch:n}}});var io=b((XF,nw)=>{"use strict";var Xi=Sn(),Su=Xi.Reader,rw=Xi.Writer,Pr=Xi.util,Pt=Xi.roots["libp2p-circuit"]||(Xi.roots["libp2p-circuit"]={});Pt.CircuitRelay=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.type=r.int32();break;case 2:s.srcPeer=Pt.CircuitRelay.Peer.decode(r,r.uint32());break;case 3:s.dstPeer=Pt.CircuitRelay.Peer.decode(r,r.uint32());break;case 4:s.code=r.int32();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Pt.CircuitRelay)return r;var n=new Pt.CircuitRelay;switch(r.type){case"HOP":case 1:n.type=1;break;case"STOP":case 2:n.type=2;break;case"STATUS":case 3:n.type=3;break;case"CAN_HOP":case 4:n.type=4;break}if(r.srcPeer!=null){if(typeof r.srcPeer!="object")throw TypeError(".CircuitRelay.srcPeer: object expected");n.srcPeer=Pt.CircuitRelay.Peer.fromObject(r.srcPeer)}if(r.dstPeer!=null){if(typeof r.dstPeer!="object")throw TypeError(".CircuitRelay.dstPeer: object expected");n.dstPeer=Pt.CircuitRelay.Peer.fromObject(r.dstPeer)}switch(r.code){case"SUCCESS":case 100:n.code=100;break;case"HOP_SRC_ADDR_TOO_LONG":case 220:n.code=220;break;case"HOP_DST_ADDR_TOO_LONG":case 221:n.code=221;break;case"HOP_SRC_MULTIADDR_INVALID":case 250:n.code=250;break;case"HOP_DST_MULTIADDR_INVALID":case 251:n.code=251;break;case"HOP_NO_CONN_TO_DST":case 260:n.code=260;break;case"HOP_CANT_DIAL_DST":case 261:n.code=261;break;case"HOP_CANT_OPEN_DST_STREAM":case 262:n.code=262;break;case"HOP_CANT_SPEAK_RELAY":case 270:n.code=270;break;case"HOP_CANT_RELAY_TO_SELF":case 280:n.code=280;break;case"STOP_SRC_ADDR_TOO_LONG":case 320:n.code=320;break;case"STOP_DST_ADDR_TOO_LONG":case 321:n.code=321;break;case"STOP_SRC_MULTIADDR_INVALID":case 350:n.code=350;break;case"STOP_DST_MULTIADDR_INVALID":case 351:n.code=351;break;case"STOP_RELAY_REFUSED":case 390:n.code=390;break;case"MALFORMED_MESSAGE":case 400:n.code=400;break}return n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.type=n.enums===String?"HOP":1,i.srcPeer=null,i.dstPeer=null,i.code=n.enums===String?"SUCCESS":100),r.type!=null&&r.hasOwnProperty("type")&&(i.type=n.enums===String?Pt.CircuitRelay.Type[r.type]:r.type),r.srcPeer!=null&&r.hasOwnProperty("srcPeer")&&(i.srcPeer=Pt.CircuitRelay.Peer.toObject(r.srcPeer,n)),r.dstPeer!=null&&r.hasOwnProperty("dstPeer")&&(i.dstPeer=Pt.CircuitRelay.Peer.toObject(r.dstPeer,n)),r.code!=null&&r.hasOwnProperty("code")&&(i.code=n.enums===String?Pt.CircuitRelay.Status[r.code]:r.code),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,Xi.util.toJSONOptions)},t.Status=function(){var e={},r=Object.create(e);return r[e[100]="SUCCESS"]=100,r[e[220]="HOP_SRC_ADDR_TOO_LONG"]=220,r[e[221]="HOP_DST_ADDR_TOO_LONG"]=221,r[e[250]="HOP_SRC_MULTIADDR_INVALID"]=250,r[e[251]="HOP_DST_MULTIADDR_INVALID"]=251,r[e[260]="HOP_NO_CONN_TO_DST"]=260,r[e[261]="HOP_CANT_DIAL_DST"]=261,r[e[262]="HOP_CANT_OPEN_DST_STREAM"]=262,r[e[270]="HOP_CANT_SPEAK_RELAY"]=270,r[e[280]="HOP_CANT_RELAY_TO_SELF"]=280,r[e[320]="STOP_SRC_ADDR_TOO_LONG"]=320,r[e[321]="STOP_DST_ADDR_TOO_LONG"]=321,r[e[350]="STOP_SRC_MULTIADDR_INVALID"]=350,r[e[351]="STOP_DST_MULTIADDR_INVALID"]=351,r[e[390]="STOP_RELAY_REFUSED"]=390,r[e[400]="MALFORMED_MESSAGE"]=400,r}(),t.Type=function(){var e={},r=Object.create(e);return r[e[1]="HOP"]=1,r[e[2]="STOP"]=2,r[e[3]="STATUS"]=3,r[e[4]="CAN_HOP"]=4,r}(),t.Peer=function(){function e(r){if(this.addrs=[],r)for(var n=Object.keys(r),i=0;i>>3){case 1:o.id=n.bytes();break;case 2:o.addrs&&o.addrs.length||(o.addrs=[]),o.addrs.push(n.bytes());break;default:n.skipType(a&7);break}}if(!o.hasOwnProperty("id"))throw Pr.ProtocolError("missing required 'id'",{instance:o});return o},e.fromObject=function(n){if(n instanceof Pt.CircuitRelay.Peer)return n;var i=new Pt.CircuitRelay.Peer;if(n.id!=null&&(typeof n.id=="string"?Pr.base64.decode(n.id,i.id=Pr.newBuffer(Pr.base64.length(n.id)),0):n.id.length&&(i.id=n.id)),n.addrs){if(!Array.isArray(n.addrs))throw TypeError(".CircuitRelay.Peer.addrs: array expected");i.addrs=[];for(var s=0;s{iw.exports=function(e){if(e){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}});var aw=b((eK,ow)=>{ow.exports=class extends Error{constructor(e,r){super(e||"The operation was aborted");this.type="aborted",this.code=r||"ABORT_ERR"}}});var xu=b((tK,Zi)=>{var _3=sw(),Md=aw(),cw=(t,e,r)=>Fd(t,Array.isArray(e)?e:[{signal:e,options:r}]),Fd=(t,e)=>{t=_3(t),e=e.map(({signal:n,options:i})=>({signal:n,options:i||{}}));async function*r(){let n,i=()=>{n&&n()};for(let{signal:s}of e)s.addEventListener("abort",i);for(;;){let s;try{for(let{signal:a,options:c}of e)if(a.aborted){let{abortMessage:u,abortCode:l}=c;throw new Md(u,l)}let o=new Promise((a,c)=>{n=()=>{let{options:u}=e.find(({signal:d})=>d.aborted),{abortMessage:l,abortCode:f}=u;c(new Md(l,f))}});s=await Promise.race([o,t.next()]),n=null}catch(o){for(let{signal:u}of e)u.removeEventListener("abort",i);let a=e.find(({signal:u})=>u.aborted),c=o.type==="aborted"&&a;if(c&&a.options.onAbort&&await a.options.onAbort(t),typeof t.return=="function")try{let u=t.return();u instanceof Promise&&u.catch(l=>{a.options.onReturnError!=null&&a.options.onReturnError(l)})}catch(u){a.options.onReturnError!=null&&a.options.onReturnError(u)}if(c&&a.options.returnOnAbort)return;throw o}if(s.done)break;yield s.value}for(let{signal:s}of e)s.removeEventListener("abort",i)}return r()},uw=(t,e,r)=>lw(t,Array.isArray(e)?e:[{signal:e,options:r}]),lw=(t,e)=>r=>t(Fd(r,e)),S3=(t,e,r)=>x3(t,Array.isArray(e)?e:[{signal:e,options:r}]),x3=(t,e)=>({sink:lw(t.sink,e),source:Fd(t.source,e)});Zi.exports=cw;Zi.exports.AbortError=Md;Zi.exports.source=cw;Zi.exports.sink=uw;Zi.exports.transform=uw;Zi.exports.duplex=S3});var hw=b((rK,dw)=>{"use strict";var{source:fw}=xu(),A3=Oe(),C3=A3("libp2p:stream:converter");function I3({stream:t,remoteAddr:e,localAddr:r},n={}){let{sink:i,source:s}=t,o={async sink(c){n.signal&&(c=fw(c,n.signal));try{await i(c)}catch(u){u.type!=="aborted"&&C3(u)}a()},source:n.signal?fw(s,n.signal):s,conn:t,localAddr:r,remoteAddr:e,timeline:{open:Date.now(),close:void 0},close(){return i(new Uint8Array(0)),a()}};function a(){return o.timeline.close||(o.timeline.close=Date.now()),Promise.resolve()}return o}dw.exports=I3});var Na=b((nK,pw)=>{"use strict";pw.exports={relay:"/libp2p/circuit/relay/0.1.0"}});var gw=b((iK,yw)=>{"use strict";var{EventEmitter:T3}=rr(),{Multiaddr:R3}=$t();yw.exports=t=>{let e=new Map;async function r(s){let o=String(s).split("/p2p-circuit").find(u=>u!==""),a=await t.dial(new R3(o)),c=a.remoteAddr.encapsulate("/p2p-circuit");e.set(a.remotePeer.toB58String(),c),i.emit("listening")}function n(){let s=[];for(let o of e.values())s.push(o);return s}let i=Object.assign(new T3,{close:()=>Promise.resolve(),listen:r,getAddrs:n});return t.connectionManager.on("peer:disconnect",s=>{e.delete(s.remotePeer.toB58String())&&i.emit("close")}),i}});var Kd=b((sK,Ew)=>{"use strict";var{Multiaddr:mw}=$t(),{CircuitRelay:Ji}=io();function vw(t,e){t.write({type:Ji.Type.STATUS,code:e})}function B3(t,e){try{t.dstPeer&&t.dstPeer.addrs&&t.dstPeer.addrs.forEach(r=>new mw(r))}catch(r){throw vw(e,t.type===Ji.Type.HOP?Ji.Status.HOP_DST_MULTIADDR_INVALID:Ji.Status.STOP_DST_MULTIADDR_INVALID),r}try{t.srcPeer&&t.srcPeer.addrs&&t.srcPeer.addrs.forEach(r=>new mw(r))}catch(r){throw vw(e,t.type===Ji.Type.HOP?Ji.Status.HOP_SRC_MULTIADDR_INVALID:Ji.Status.STOP_SRC_MULTIADDR_INVALID),r}}Ew.exports={validateAddrs:B3}});var _w=b(Au=>{"use strict";Au.byteLength=N3;Au.toByteArray=D3;Au.fromByteArray=q3;var mn=[],Nr=[],P3=typeof Uint8Array!="undefined"?Uint8Array:Array,Vd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(es=0,bw=Vd.length;es0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function N3(t){var e=ww(t),r=e[0],n=e[1];return(r+n)*3/4-n}function O3(t,e,r){return(e+r)*3/4-r}function D3(t){var e,r=ww(t),n=r[0],i=r[1],s=new P3(O3(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Nr[t.charCodeAt(c)]<<2|Nr[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Nr[t.charCodeAt(c)]<<10|Nr[t.charCodeAt(c+1)]<<4|Nr[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function L3(t){return mn[t>>18&63]+mn[t>>12&63]+mn[t>>6&63]+mn[t&63]}function k3(t,e,r){for(var n,i=[],s=e;sa?a:o+s));return n===1?(e=t[r-1],i.push(mn[e>>2]+mn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(mn[e>>10]+mn[e>>4&63]+mn[e<<2&63]+"=")),i.join("")}});var Sw=b(jd=>{jd.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<>1,l=-7,f=r?i-1:0,d=r?-1:1,p=t[e+f];for(f+=d,s=p&(1<<-l)-1,p>>=-l,l+=a;l>0;s=s*256+t[e+f],f+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+t[e+f],f+=d,l-=8);if(s===0)s=1-u;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-u}return(p?-1:1)*o*Math.pow(2,s-n)};jd.write=function(t,e,r,n,i,s){var o,a,c,u=s*8-i-1,l=(1<>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,h=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=d/c:e+=d*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=l?(a=0,o=l):o+f>=1?(a=(e*c-1)*Math.pow(2,i),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=a&255,p+=h,a/=256,i-=8);for(o=o<0;t[r+p]=o&255,p+=h,o/=256,u-=8);t[r+p-h]|=g*128}});var pi=b(co=>{"use strict";var $d=_w(),so=Sw(),xw=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;co.Buffer=V;co.SlowBuffer=j3;co.INSPECT_MAX_BYTES=50;var Cu=2147483647;co.kMaxLength=Cu;V.TYPED_ARRAY_SUPPORT=U3();!V.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U3(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch(t){return!1}}Object.defineProperty(V.prototype,"parent",{enumerable:!0,get:function(){if(!!V.isBuffer(this))return this.buffer}});Object.defineProperty(V.prototype,"offset",{enumerable:!0,get:function(){if(!!V.isBuffer(this))return this.byteOffset}});function On(t){if(t>Cu)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,V.prototype),e}function V(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Hd(t)}return Aw(t,e,r)}V.poolSize=8192;function Aw(t,e,r){if(typeof t=="string")return F3(t,e);if(ArrayBuffer.isView(t))return K3(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(vn(t,ArrayBuffer)||t&&vn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(vn(t,SharedArrayBuffer)||t&&vn(t.buffer,SharedArrayBuffer)))return Gd(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return V.from(n,e,r);let i=V3(t);if(i)return i;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return V.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}V.from=function(t,e,r){return Aw(t,e,r)};Object.setPrototypeOf(V.prototype,Uint8Array.prototype);Object.setPrototypeOf(V,Uint8Array);function Cw(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function M3(t,e,r){return Cw(t),t<=0?On(t):e!==void 0?typeof r=="string"?On(t).fill(e,r):On(t).fill(e):On(t)}V.alloc=function(t,e,r){return M3(t,e,r)};function Hd(t){return Cw(t),On(t<0?0:Wd(t)|0)}V.allocUnsafe=function(t){return Hd(t)};V.allocUnsafeSlow=function(t){return Hd(t)};function F3(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!V.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Iw(t,e)|0,n=On(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function zd(t){let e=t.length<0?0:Wd(t.length)|0,r=On(e);for(let n=0;n=Cu)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Cu.toString(16)+" bytes");return t|0}function j3(t){return+t!=t&&(t=0),V.alloc(+t)}V.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==V.prototype};V.compare=function(e,r){if(vn(e,Uint8Array)&&(e=V.from(e,e.offset,e.byteLength)),vn(r,Uint8Array)&&(r=V.from(r,r.offset,r.byteLength)),!V.isBuffer(e)||!V.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,o=Math.min(n,i);si.length?(V.isBuffer(o)||(o=V.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(V.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function Iw(t,e){if(V.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||vn(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Qd(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Mw(t).length;default:if(i)return n?-1:Qd(t).length;e=(""+e).toLowerCase(),i=!0}}V.byteLength=Iw;function $3(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return eD(this,e,r);case"utf8":case"utf-8":return Bw(this,e,r);case"ascii":return Z3(this,e,r);case"latin1":case"binary":return J3(this,e,r);case"base64":return Q3(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return tD(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}V.prototype._isBuffer=!0;function ts(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}V.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;rr&&(e+=" ... "),""};xw&&(V.prototype[xw]=V.prototype.inspect);V.prototype.compare=function(e,r,n,i,s){if(vn(e,Uint8Array)&&(e=V.from(e,e.offset,e.byteLength)),!V.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let o=s-i,a=n-r,c=Math.min(o,a),u=this.slice(i,s),l=e.slice(r,n);for(let f=0;f2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Xd(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=V.from(e,n)),V.isBuffer(e))return e.length===0?-1:Rw(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Rw(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Rw(t,e,r,n,i){let s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function c(l,f){return s===1?l[f]:l.readUInt16BE(f*s)}let u;if(i){let l=-1;for(u=r;uo&&(r=o-a),u=r;u>=0;u--){let l=!0;for(let f=0;fi&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let o;for(o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return H3(this,e,r,n);case"utf8":case"utf-8":return z3(this,e,r,n);case"ascii":case"latin1":case"binary":return G3(this,e,r,n);case"base64":return W3(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y3(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};V.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Q3(t,e,r){return e===0&&r===t.length?$d.fromByteArray(t):$d.fromByteArray(t.slice(e,r))}function Bw(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i239?4:s>223?3:s>191?2:1;if(i+a<=r){let c,u,l,f;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)==128&&(f=(s&31)<<6|c&63,f>127&&(o=f));break;case 3:c=t[i+1],u=t[i+2],(c&192)==128&&(u&192)==128&&(f=(s&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:c=t[i+1],u=t[i+2],l=t[i+3],(c&192)==128&&(u&192)==128&&(l&192)==128&&(f=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return X3(n)}var Pw=4096;function X3(t){let e=t.length;if(e<=Pw)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn)&&(r=n);let i="";for(let s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}V.prototype.readUintLE=V.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Nt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o>>0,r=r>>>0,n||Nt(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};V.prototype.readUint8=V.prototype.readUInt8=function(e,r){return e=e>>>0,r||Nt(e,1,this.length),this[e]};V.prototype.readUint16LE=V.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Nt(e,2,this.length),this[e]|this[e+1]<<8};V.prototype.readUint16BE=V.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Nt(e,2,this.length),this[e]<<8|this[e+1]};V.prototype.readUint32LE=V.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Nt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};V.prototype.readUint32BE=V.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Nt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};V.prototype.readBigUInt64LE=hi(function(e){e=e>>>0,ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Oa(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Oa(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,r=r>>>0,n||Nt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o=s&&(i-=Math.pow(2,8*r)),i};V.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Nt(e,r,this.length);let i=r,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};V.prototype.readInt8=function(e,r){return e=e>>>0,r||Nt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};V.prototype.readInt16LE=function(e,r){e=e>>>0,r||Nt(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};V.prototype.readInt16BE=function(e,r){e=e>>>0,r||Nt(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};V.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Nt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};V.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Nt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};V.prototype.readBigInt64LE=hi(function(e){e=e>>>0,ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Oa(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Oa(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,r||Nt(e,4,this.length),so.read(this,e,!0,23,4)};V.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Nt(e,4,this.length),so.read(this,e,!1,23,4)};V.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Nt(e,8,this.length),so.read(this,e,!0,52,8)};V.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Nt(e,8,this.length),so.read(this,e,!1,52,8)};function ar(t,e,r,n,i,s){if(!V.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}V.prototype.writeUintLE=V.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;ar(this,e,r,n,a,0)}let s=1,o=0;for(this[r]=e&255;++o>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;ar(this,e,r,n,a,0)}let s=n-1,o=1;for(this[r+s]=e&255;--s>=0&&(o*=256);)this[r+s]=e/o&255;return r+n};V.prototype.writeUint8=V.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,1,255,0),this[r]=e&255,r+1};V.prototype.writeUint16LE=V.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};V.prototype.writeUint16BE=V.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};V.prototype.writeUint32LE=V.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};V.prototype.writeUint32BE=V.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function Nw(t,e,r,n,i){Uw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,r}function Ow(t,e,r,n,i){Uw(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o=o>>8,t[r+2]=o,o=o>>8,t[r+1]=o,o=o>>8,t[r]=o,r+8}V.prototype.writeBigUInt64LE=hi(function(e,r=0){return Nw(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});V.prototype.writeBigUInt64BE=hi(function(e,r=0){return Ow(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});V.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);ar(this,e,r,n,c-1,-c)}let s=0,o=1,a=0;for(this[r]=e&255;++s>0)-a&255;return r+n};V.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let c=Math.pow(2,8*n-1);ar(this,e,r,n,c-1,-c)}let s=n-1,o=1,a=0;for(this[r+s]=e&255;--s>=0&&(o*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};V.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};V.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};V.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};V.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};V.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ar(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};V.prototype.writeBigInt64LE=hi(function(e,r=0){return Nw(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});V.prototype.writeBigInt64BE=hi(function(e,r=0){return Ow(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Dw(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Lw(t,e,r,n,i){return e=+e,r=r>>>0,i||Dw(t,e,r,4,34028234663852886e22,-34028234663852886e22),so.write(t,e,r,n,23,4),r+4}V.prototype.writeFloatLE=function(e,r,n){return Lw(this,e,r,!0,n)};V.prototype.writeFloatBE=function(e,r,n){return Lw(this,e,r,!1,n)};function kw(t,e,r,n,i){return e=+e,r=r>>>0,i||Dw(t,e,r,8,17976931348623157e292,-17976931348623157e292),so.write(t,e,r,n,52,8),r+8}V.prototype.writeDoubleLE=function(e,r,n){return kw(this,e,r,!0,n)};V.prototype.writeDoubleBE=function(e,r,n){return kw(this,e,r,!1,n)};V.prototype.copy=function(e,r,n,i){if(!V.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s2**32?i=qw(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=qw(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function qw(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function rD(t,e,r){ao(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&Oa(e,t.length-(r+1))}function Uw(t,e,r,n,i,s){if(t>r||t3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:a=`>= -(2${o} ** ${(s+1)*8-1}${o}) and < 2 ** ${(s+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${r}${o}`,new oo.ERR_OUT_OF_RANGE("value",a,t)}rD(n,i,s)}function ao(t,e){if(typeof t!="number")throw new oo.ERR_INVALID_ARG_TYPE(e,"number",t)}function Oa(t,e,r){throw Math.floor(t)!==t?(ao(t,r),new oo.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new oo.ERR_BUFFER_OUT_OF_BOUNDS:new oo.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var nD=/[^+/0-9A-Za-z-_]/g;function iD(t){if(t=t.split("=")[0],t=t.trim().replace(nD,""),t.length<2)return"";for(;t.length%4!=0;)t=t+"=";return t}function Qd(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let o=0;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function sD(t){let e=[];for(let r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function Mw(t){return $d.toByteArray(iD(t))}function Iu(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function vn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Xd(t){return t!==t}var aD=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function hi(t){return typeof BigInt=="undefined"?cD:t}function cD(){throw new Error("BigInt not supported")}});var rs=b((lK,Kw)=>{"use strict";var{Buffer:zr}=pi(),Fw=Symbol.for("BufferList");function Ze(t){if(!(this instanceof Ze))return new Ze(t);Ze._init.call(this,t)}Ze._init=function(e){Object.defineProperty(this,Fw,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)};Ze.prototype._new=function(e){return new Ze(e)};Ze.prototype._offset=function(e){if(e===0)return[0,0];let r=0;for(let n=0;nthis.length||e<0)return;let r=this._offset(e);return this._bufs[r[0]][r[1]]};Ze.prototype.slice=function(e,r){return typeof e=="number"&&e<0&&(e+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,e,r)};Ze.prototype.copy=function(e,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return e||zr.alloc(0);let s=!!e,o=this._offset(n),a=i-n,c=a,u=s&&r||0,l=o[1];if(n===0&&i===this.length){if(!s)return this._bufs.length===1?this._bufs[0]:zr.concat(this._bufs,this.length);for(let f=0;fd)this._bufs[f].copy(e,u,l),u+=d;else{this._bufs[f].copy(e,u,l,l+c),u+=d;break}c-=d,l&&(l=0)}return e.length>u?e.slice(0,u):e};Ze.prototype.shallowSlice=function(e,r){if(e=e||0,r=typeof r!="number"?this.length:r,e<0&&(e+=this.length),r<0&&(r+=this.length),e===r)return this._new();let n=this._offset(e),i=this._offset(r),s=this._bufs.slice(n[0],i[0]+1);return i[1]===0?s.pop():s[s.length-1]=s[s.length-1].slice(0,i[1]),n[1]!==0&&(s[0]=s[0].slice(n[1])),this._new(s)};Ze.prototype.toString=function(e,r,n){return this.slice(r,n).toString(e)};Ze.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;)if(e>=this._bufs[0].length)e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}return this};Ze.prototype.duplicate=function(){let e=this._new();for(let r=0;rthis.length?this.length:e;let n=this._offset(e),i=n[0],s=n[1];for(;i=t.length){let c=o.indexOf(t,s);if(c!==-1)return this._reverseOffset([i,c]);s=o.length-t.length+1}else{let c=this._reverseOffset([i,s]);if(this._match(c,t))return c;s++}s=0}return-1};Ze.prototype._match=function(t,e){if(this.length-t{"use strict";var Vw=Ki(),{Buffer:uD}=pi(),jw=(t,e,r)=>{let n=Vw.encode(t,e,r);return jw.bytes=Vw.encode.bytes,e||uD.from(n)};$w.exports=jw});var Qw=b((dK,Tu)=>{"use strict";var{Buffer:Hw}=pi(),zw=rs(),Gw=Zd(),Jd=8,Ww=10*1024;function Yw(t){t=t||{};let e=Math.max(t.poolSize||Ww,t.minPoolSize||Jd),r=t.lengthEncoder||Gw;return async function*(i){let s=Hw.alloc(e),o=0;for await(let a of i){r(a.length,s,o);let c=s.slice(o,o+r.bytes);o+=r.bytes,s.length-o{e=e||{};let r=e.lengthEncoder||Gw;return new zw([r(t.length),t.slice()])};Tu.exports=Yw;Tu.exports.MIN_POOL_SIZE=Jd;Tu.exports.DEFAULT_POOL_SIZE=Ww});var eh=b((hK,Jw)=>{"use strict";var Xw=Ki(),{Buffer:lD}=pi(),fD=t=>new Proxy({},{get:(e,r)=>r[0]==="l"?t[r]:t.get(parseInt(r))}),Zw=t=>{let e=Xw.decode(lD.isBuffer(t)?t:fD(t));return Zw.bytes=Xw.decode.bytes,e};Jw.exports=Zw});var n2=b((pK,Ru)=>{"use strict";var{Buffer:dD}=pi(),th=rs(),hD=eh(),e2=8,t2=1024*1024*4,r2=dD.alloc(0),yi={LENGTH:"readLength",DATA:"readData"},pD={[yi.LENGTH]:(t,e,r,n)=>{e=e.append(t);let i;try{i=n.lengthDecoder(e)}catch(s){if(e.length>n.maxLengthLength)throw Object.assign(s,{message:"message length too long",code:"ERR_MSG_LENGTH_TOO_LONG"});if(s instanceof RangeError)return{mode:yi.LENGTH,buffer:e,chunk:void 0,state:void 0,data:void 0};throw s}if(i>n.maxDataLength)throw Object.assign(new Error("message data too long"),{code:"ERR_MSG_DATA_TOO_LONG"});return t=e.shallowSlice(n.lengthDecoder.bytes),e=new th,n.onLength&&n.onLength(i),i<=0?(n.onData&&n.onData(r2),{mode:yi.LENGTH,chunk:t,buffer:e,data:r2}):{mode:yi.DATA,chunk:t,buffer:e,state:{dataLength:i},data:void 0}},[yi.DATA]:(t,e,r,n)=>{if(e=e.append(t),!r)throw new Error("state is required");if(e.lengthi?e.shallowSlice(i):void 0;return e=new th,n.onData&&n.onData(s),{mode:yi.LENGTH,chunk:o,buffer:e,state:void 0,data:s}}};function rh(t){t=t||{};let e={lengthDecoder:t.lengthDecoder||hD,maxLengthLength:t.maxLengthLength||e2,maxDataLength:t.maxDataLength||t2,onLength:t.onLength,onData:t.onData};return async function*(n){let i=new th,s=yi.LENGTH,o;for await(let a of n){let c=a;for(;c;){let u=pD[s](c,i,o,e);s=u.mode,c=u.chunk,i=u.buffer,o=u.state,u.data&&(yield u.data)}}if(i.length)throw Object.assign(new Error("unexpected end of input"),{code:"ERR_UNEXPECTED_EOF"})}}rh.fromReader=(t,e)=>{let r=1,n={[Symbol.asyncIterator](){return this},next:async()=>{try{return await t.next(r)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}};return rh({...e||{},onLength:s=>{r=s}})(n)};Ru.exports=rh;Ru.exports.MAX_LENGTH_LENGTH=e2;Ru.exports.MAX_DATA_LENGTH=t2});var o2=b((yK,s2)=>{"use strict";var{Buffer:yD}=pi(),i2=(t,e,r)=>(e=e||yD.allocUnsafe(4),e.writeInt32BE(t,r),e);i2.bytes=4;s2.exports=i2});var u2=b((gK,c2)=>{"use strict";var a2=t=>{if(t.length<4)throw RangeError("Could not decode int32BE");return t.readInt32BE(0)};a2.bytes=4;c2.exports=a2});var uo=b(ns=>{"use strict";ns.encode=Qw();ns.decode=n2();ns.varintEncode=Zd();ns.varintDecode=eh();ns.int32BEEncode=o2();ns.int32BEDecode=u2()});var ih=b((vK,l2)=>{var nh=rs();l2.exports=t=>{let e=async function*(){let r=yield,n=new nh;for await(let i of t){if(!r){r=yield n.append(i),n=new nh;continue}for(n.append(i);n.length>=r;){let s=n.shallowSlice(0,r);if(n.consume(r),r=yield s,!r){n.length&&(r=yield n,n=new nh);break}}}if(r)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}});var sh=b((EK,f2)=>{"use strict";var gD=()=>{let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t};f2.exports=gD});var lo=b((bK,d2)=>{"use strict";var mD=ih(),vD=dd(),ED=sh();d2.exports=t=>{let e=vD(),r=mD(t.source),n=ED(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:a=>i?Promise.reject(i):(n.resolve(a),s),source:r},rest:()=>e.end(),write:e.push,read:async()=>(await r.next()).value}}});var Pu=b((wK,m2)=>{"use strict";var h2=Oe(),Bu=Object.assign(h2("libp2p:circuit:stream-handler"),{error:h2("libp2p:circuit:stream-handler:err")}),p2=uo(),bD=lo(),{CircuitRelay:y2}=io(),g2=class{constructor({stream:e,maxLength:r=4096}){this.stream=e,this.shake=bD(this.stream),this.decoder=p2.decode.fromReader(this.shake.reader,{maxDataLength:r})}async read(){let e=await this.decoder.next();if(e.value){let r=y2.decode(e.value.slice());return Bu("read message type",r.type),r}Bu("read received no value, closing stream"),this.close()}write(e){Bu("write message type %s",e.type),this.shake.write(p2.encode.single(y2.encode(e).finish()))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){Bu("closing the stream"),this.rest().sink([])}};m2.exports=g2});var ch=b((_K,ah)=>{"use strict";var v2=Oe(),Da=Object.assign(v2("libp2p:circuit:stop"),{error:v2("libp2p:circuit:stop:err")}),{CircuitRelay:oh}=io(),wD=Na(),_D=Pu(),{validateAddrs:SD}=Kd();ah.exports.handleStop=function({connection:e,request:r,streamHandler:n}){try{SD(r,n)}catch(i){return Da.error("invalid stop request via peer %s",e.remotePeer.toB58String(),i)}return Da("stop request is valid"),n.write({type:oh.Type.STATUS,code:oh.Status.SUCCESS}),n.rest()};ah.exports.stop=async function({connection:e,request:r}){let{stream:n}=await e.newStream([wD.relay]);Da("starting stop request to %s",e.remotePeer.toB58String());let i=new _D({stream:n});i.write(r);let s=await i.read();if(!s)return i.close();if(s.code===oh.Status.SUCCESS)return Da("stop request to %s was successful",e.remotePeer.toB58String()),i.rest();Da("stop request failed with code %d",s.code),i.close()}});var uh=b((SK,x2)=>{"use strict";var E2=Oe(),Dn=Object.assign(E2("libp2p:circuit:hop"),{error:E2("libp2p:circuit:hop:err")}),b2=ge(),xD=qt(),{validateAddrs:AD}=Kd(),w2=Pu(),{CircuitRelay:dr}=io(),{pipe:CD}=fr(),{codes:_2}=Ye(),{stop:ID}=ch(),S2=Na();async function TD({connection:t,request:e,streamHandler:r,circuit:n}){if(!n._options.hop.enabled)return Dn("HOP request received but we are not acting as a relay"),r.end({type:dr.Type.STATUS,code:dr.Status.HOP_CANT_SPEAK_RELAY});try{AD(e,r)}catch(u){return Dn.error("invalid hop request via peer %s",t.remotePeer.toB58String(),u)}if(!e.dstPeer){Dn("HOP request received but we do not receive a dstPeer");return}let i=new xD(e.dstPeer.id),s=n._connectionManager.get(i);if(!s&&!n._options.hop.active)return Dn("HOP request received but we are not connected to the destination peer"),r.end({type:dr.Type.STATUS,code:dr.Status.HOP_NO_CONN_TO_DST});if(!s)return;let o={type:dr.Type.STOP,dstPeer:e.dstPeer,srcPeer:e.srcPeer},a;try{a=await ID({connection:s,request:o})}catch(u){return Dn.error(u)}Dn("hop request from %s is valid",t.remotePeer.toB58String()),r.write({type:dr.Type.STATUS,code:dr.Status.SUCCESS});let c=r.rest();return CD(c,a,c)}async function RD({connection:t,request:e}){let{stream:r}=await t.newStream([S2.relay]),n=new w2({stream:r});n.write(e);let i=await n.read();if(!i)throw b2(new Error("HOP request had no response"),_2.ERR_HOP_REQUEST_FAILED);if(i.code===dr.Status.SUCCESS)return Dn("hop request was successful"),n.rest();throw Dn("hop request failed with code %d, closing stream",i.code),n.close(),b2(new Error(`HOP request failed with code ${i.code}`),_2.ERR_HOP_REQUEST_FAILED)}async function BD({connection:t}){let{stream:e}=await t.newStream([S2.relay]),r=new w2({stream:e});r.write({type:dr.Type.CAN_HOP});let n=await r.read();return await r.close(),!(!n||n.code!==dr.Status.SUCCESS)}function PD({connection:t,streamHandler:e,circuit:r}){let n=r._options.hop.enabled;Dn("can hop (%s) request from %s",n,t.remotePeer.toB58String()),e.end({type:dr.Type.STATUS,code:n?dr.Status.SUCCESS:dr.Status.HOP_CANT_SPEAK_RELAY})}x2.exports={handleHop:TD,hop:RD,canHop:BD,handleCanHop:PD}});var B2=b((xK,R2)=>{"use strict";var A2=Oe(),Ln=Object.assign(A2("libp2p:circuit"),{error:A2("libp2p:circuit:err")}),ND=ge(),OD=tw(),{Multiaddr:La}=$t(),C2=qt(),{CircuitRelay:ka}=io(),{codes:DD}=Ye(),I2=hw(),{relay:LD}=Na(),kD=gw(),{handleCanHop:qD,handleHop:UD,hop:MD}=uh(),{handleStop:FD}=ch(),KD=Pu(),VD=Symbol.for("@libp2p/js-libp2p-circuit/circuit"),T2=class{constructor({libp2p:e,upgrader:r}){this._dialer=e.dialer,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._upgrader=r,this._options=e._config.relay,this._libp2p=e,this.peerId=e.peerId,this._registrar.handle(LD,this._onProtocol.bind(this))}async _onProtocol({connection:e,stream:r}){let n=new KD({stream:r}),i=await n.read();if(!i)return;let s=this,o;switch(i.type){case ka.Type.CAN_HOP:{Ln("received CAN_HOP request from %s",e.remotePeer.toB58String()),await qD({circuit:s,connection:e,streamHandler:n});break}case ka.Type.HOP:{Ln("received HOP request from %s",e.remotePeer.toB58String()),o=await UD({connection:e,request:i,streamHandler:n,circuit:s});break}case ka.Type.STOP:{Ln("received STOP request from %s",e.remotePeer.toB58String()),o=await FD({connection:e,request:i,streamHandler:n});break}default:Ln("Request of type %s not supported",i.type)}if(o){let a=new La(i.dstPeer.addrs[0]),c=new La(i.srcPeer.addrs[0]),u=I2({stream:o,remoteAddr:a,localAddr:c}),l=i.type===ka.Type.HOP?"relay":"inbound";Ln("new %s connection %s",l,u.remoteAddr);let f=await this._upgrader.upgradeInbound(u);Ln("%s connection %s upgraded",l,u.remoteAddr),this.handler&&this.handler(f)}}async dial(e,r){let n=e.toString().split("/p2p-circuit"),i=new La(n[0]),s=new La(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(!o||!a){let d="Circuit relay dial failed as addresses did not have peer id";throw Ln.error(d),ND(new Error(d),DD.ERR_RELAYED_DIAL)}let c=C2.createFromB58String(o),u=C2.createFromB58String(a),l=!1,f=this._connectionManager.get(c);f||(f=await this._dialer.connectToPeer(i,r),l=!0);try{let d=await MD({connection:f,request:{type:ka.Type.HOP,srcPeer:{id:this.peerId.toBytes(),addrs:this._libp2p.multiaddrs.map(g=>g.bytes)},dstPeer:{id:u.toBytes(),addrs:[new La(s).bytes]}}}),p=i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toB58String()}`),h=I2({stream:d,remoteAddr:e,localAddr:p});return Ln("new outbound connection %s",h.remoteAddr),this._upgrader.upgradeOutbound(h)}catch(d){throw Ln.error("Circuit relay dial failed",d),l&&await f.close(),d}}createListener(e,r){return typeof e=="function"&&(r=e,e={}),this.handler=r,kD(this._libp2p)}filter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>OD.Circuit.matches(r))}get[Symbol.toStringTag](){return"Circuit"}static isTransport(e){return Boolean(e&&e[VD])}};R2.exports=T2});var lh=b((AK,P2)=>{"use strict";var{CID:jD}=(Ss(),Fo),{sha256:$D}=(ki(),Zn);P2.exports.namespaceToCid=async t=>{let e=new TextEncoder().encode(t),r=await $D.digest(e);return jD.createV0(r)}});var q2=b((CK,k2)=>{"use strict";var N2=Oe(),fh=Object.assign(N2("libp2p:auto-relay"),{error:N2("libp2p:auto-relay:err")}),{fromString:HD}=(Dt(),Ft),{toString:zD}=(Lt(),Kt),{Multiaddr:GD}=$t(),WD=Vi(),{relay:YD}=Na(),{canHop:QD}=uh(),{namespaceToCid:XD}=lh(),{CIRCUIT_PROTO_CODE:ZD,HOP_METADATA_KEY:O2,HOP_METADATA_VALUE:D2,RELAY_RENDEZVOUS_NS:JD}=pu(),L2=class{constructor({libp2p:e,maxListeners:r=1,onError:n}){this._libp2p=e,this._peerId=e.peerId,this._peerStore=e.peerStore,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._addressSorter=e.dialer.addressSorter,this.maxListeners=r,this._listenRelays=new Set,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this._peerStore.on("change:protocols",this._onProtocolChange),this._connectionManager.on("peer:disconnect",this._onPeerDisconnected),this._onError=(i,s)=>{fh.error(s||i),n&&n(i,s)}}async _onProtocolChange({peerId:e,protocols:r}){let n=e.toB58String(),i=r.find(s=>s===YD);if(!i&&this._listenRelays.has(n)){await this._removeListenRelay(n);return}else if(!i||this._listenRelays.has(n))return;try{let s=this._connectionManager.get(e);if(!s)return;if(s.remoteAddr.protoCodes().includes(ZD)){fh(`relayed connection to ${n} will not be used to hop on`);return}await QD({connection:s})&&(await this._peerStore.metadataBook.setValue(e,O2,HD(D2)),await this._addListenRelay(s,n))}catch(s){this._onError(s)}}_onPeerDisconnected(e){let n=e.remotePeer.toB58String();!this._listenRelays.has(n)||this._removeListenRelay(n).catch(i=>{fh.error(i)})}async _addListenRelay(e,r){try{if(this._listenRelays.size>=this.maxListeners)return;let n=await this._peerStore.addressBook.getMultiaddrsForPeer(e.remotePeer,this._addressSorter);(await Promise.all(n.map(async s=>{try{return await this._transportManager.listen([new GD(`${s.toString()}/p2p-circuit`)]),!0}catch(o){this._onError(o)}return!1}))).includes(!0)&&this._listenRelays.add(r)}catch(n){this._onError(n),this._listenRelays.delete(r)}}async _removeListenRelay(e){this._listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this._listenRelays.size>=this.maxListeners)return;let r=[],n=await WD(this._peerStore.getPeers());for await(let{id:i,metadata:s}of n){let o=i.toB58String();if(this._listenRelays.has(o)||e.includes(o))continue;let a=s.get(O2);if(!a||zD(a)!==D2)continue;let c=this._connectionManager.get(i);if(!c){r.push(i);continue}if(await this._addListenRelay(c,o),this._listenRelays.size>=this.maxListeners)return}for(let i of r)if(await this._tryToListenOnRelay(i),this._listenRelays.size>=this.maxListeners)return;try{let i=await XD(JD);for await(let s of this._libp2p.contentRouting.findProviders(i)){if(!s.multiaddrs.length)continue;let o=s.id;if(await this._peerStore.addressBook.add(o,s.multiaddrs),await this._tryToListenOnRelay(o),this._listenRelays.size>=this.maxListeners)return}}catch(i){this._onError(i)}}async _tryToListenOnRelay(e){try{let r=await this._libp2p.dial(e);await this._addListenRelay(r,e.toB58String())}catch(r){this._onError(r,`could not connect and listen on known hop relay ${e.toB58String()}`)}}};k2.exports=L2});var V2=b((IK,K2)=>{"use strict";var U2=Oe(),M2=Object.assign(U2("libp2p:relay"),{error:U2("libp2p:relay:err")}),{codes:eL}=Ye(),{setDelayedInterval:tL,clearDelayedInterval:rL}=gd(),nL=q2(),{namespaceToCid:iL}=lh(),{RELAY_RENDEZVOUS_NS:sL}=pu(),F2=class{constructor(e){this._libp2p=e,this._options={...e._config.relay},this._autoRelay=this._options.autoRelay.enabled&&new nL({libp2p:e,...this._options.autoRelay}),this._advertiseService=this._advertiseService.bind(this)}start(){this._options.hop.enabled&&this._options.advertise.enabled&&(this._timeout=tL(this._advertiseService,this._options.advertise.ttl,this._options.advertise.bootDelay))}stop(){rL(this._timeout)}async _advertiseService(){try{let e=await iL(sL);await this._libp2p.contentRouting.provide(e)}catch(e){e.code===eL.ERR_NO_ROUTERS_AVAILABLE?(M2.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop()):M2.error(e)}}};K2.exports=F2});var hh=b((TK,dh)=>{function j2(t){let e=new globalThis.AbortController;function r(){e.abort();for(let n of t)!n||!n.removeEventListener||n.removeEventListener("abort",r)}for(let n of t)if(!(!n||!n.addEventListener)){if(n.aborted){r();break}n.addEventListener("abort",r)}return e.signal}dh.exports=j2;dh.exports.anySignal=j2});var G2=b((BK,z2)=>{var $2=ld(),H2=sh();z2.exports=class{constructor(){this._buffer=new $2,this._waitingConsumers=new $2}push(e){let{promise:r,resolve:n}=H2();return this._buffer.push({chunk:e,resolve:n}),this._consume(),r}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){let e=this._waitingConsumers.shift(),r=this._buffer.shift();e.resolve(r.chunk),r.resolve()}}shift(){let{promise:e,resolve:r}=H2();return this._waitingConsumers.push({resolve:r}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}});var Y2=b((PK,W2)=>{"use strict";W2.exports=(t,e=1,r)=>{if(r={indent:" ",includeEmptyLines:!1,...r},typeof t!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof t}\``);if(typeof e!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof e}\``);if(typeof r.indent!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``);if(e===0)return t;let n=r.includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return t.replace(n,r.indent.repeat(e))}});var Q2=b(()=>{});var e_=b((DK,J2)=>{"use strict";var X2=Q2(),Z2=/\s+at.*(?:\(|\s)(.*)\)?/,oL=/^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/,aL=typeof X2.homedir=="undefined"?"":X2.homedir();J2.exports=(t,e)=>(e=Object.assign({pretty:!1},e),t.replace(/\\/g,"/").split(` +`).filter(r=>{let n=r.match(Z2);if(n===null||!n[1])return!0;let i=n[1];return i.includes(".app/Contents/Resources/electron.asar")||i.includes(".app/Contents/Resources/default_app.asar")?!1:!oL.test(i)}).filter(r=>r.trim()!=="").map(r=>e.pretty?r.replace(Z2,(n,i)=>n.replace(i,i.replace(aL,"~"))):r).join(` +`))});var n_=b((LK,r_)=>{"use strict";var cL=Y2(),uL=e_(),lL=t=>t.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g,""),t_=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);e=[...e].map(n=>n instanceof Error?n:n!==null&&typeof n=="object"?Object.assign(new Error(n.message),n):new Error(n));let r=e.map(n=>typeof n.stack=="string"?lL(uL(n.stack)):String(n)).join(` +`);r=` +`+cL(r,4);super(r);this.name="AggregateError",Object.defineProperty(this,"_errors",{value:e})}*[Symbol.iterator](){for(let e of this._errors)yield e}};r_.exports=t_});var i_=b((kK,yh)=>{"use strict";var ph=class extends Error{constructor(e){super(e||"Promise was canceled");this.name="CancelError"}get isCanceled(){return!0}},qa=class{static fn(e){return(...r)=>new qa((n,i,s)=>{r.push(s),e(...r).then(n,i)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((r,n)=>{this._reject=n;let i=a=>{(!this._isCanceled||!o.shouldReject)&&(this._isPending=!1,r(a))},s=a=>{this._isPending=!1,n(a)},o=a=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(a)};return Object.defineProperties(o,{shouldReject:{get:()=>this._rejectOnCancel,set:a=>{this._rejectOnCancel=a}}}),e(i,s,o)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let r of this._cancelHandlers)r()}catch(r){this._reject(r);return}this._rejectOnCancel&&this._reject(new ph(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(qa.prototype,Promise.prototype);yh.exports=qa;yh.exports.CancelError=ph});var o_=b((qK,Nu)=>{"use strict";var s_=n_(),fL=i_(),gh=class extends Error{},dL=(t,e)=>new fL((r,n,i)=>{let{count:s,filter:o=()=>!0}=e;if(!Number.isFinite(s)){n(new TypeError(`Expected a finite number, got ${typeof e.count}`));return}let a=[],c=[],u=0,l=!1,f=new Set,d=()=>(a.length===s&&(r(a),l=!0),u-c.length{for(let h of t)!f.has(h)&&typeof h.cancel=="function"&&h.cancel()};i(p);for(let h of t)u++,(async()=>{try{let g=await h;if(l)return;if(!o(g))throw new gh("Value does not satisfy filter");a.push(g)}catch(g){c.push(g)}finally{f.add(h),!l&&d()&&p()}})();s>u&&(n(new RangeError(`Expected input to contain at least ${e.count} items, but contains ${u} items`)),p())});Nu.exports=dL;Nu.exports.AggregateError=s_;Nu.exports.FilterError=gh});var a_=b((UK,vh)=>{"use strict";var mh=class extends Error{constructor(e){super(e||"Promise was canceled");this.name="CancelError"}get isCanceled(){return!0}},Ua=class{static fn(e){return(...r)=>new Ua((n,i,s)=>{r.push(s),e(...r).then(n,i)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((r,n)=>{this._reject=n;let i=a=>{(!this._isCanceled||!o.shouldReject)&&(this._isPending=!1,r(a))},s=a=>{this._isPending=!1,n(a)},o=a=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(a)};return Object.defineProperties(o,{shouldReject:{get:()=>this._rejectOnCancel,set:a=>{this._rejectOnCancel=a}}}),e(i,s,o)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let r of this._cancelHandlers)r()}catch(r){this._reject(r);return}this._rejectOnCancel&&this._reject(new mh(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(Ua.prototype,Promise.prototype);vh.exports=Ua;vh.exports.CancelError=mh});var u_=b((MK,Eh)=>{"use strict";var c_=o_(),hL=a_();Eh.exports=(t,e)=>{let r=c_(t,{...e,count:1});return hL.fn(async n=>{n(()=>{r.cancel()});let[i]=await r;return i})()};Eh.exports.AggregateError=c_.AggregateError});var h_=b((FK,d_)=>{"use strict";var pL=ge(),{anySignal:yL}=hh(),gL=G2(),mL=u_(),{setMaxListeners:l_}=rr(),{codes:vL}=Ye(),f_=class{constructor({addrs:e,dialAction:r,dialer:n}){this.addrs=e,this.dialer=n,this.dialAction=r}async run(e={}){let r=this.dialer.getTokens(this.addrs.length);if(r.length<1)throw pL(new Error("No dial tokens available"),vL.ERR_NO_DIAL_TOKENS);let n=new gL;r.forEach(o=>n.push(o));let i=this.addrs.map(()=>{let o=new AbortController;try{l_&&l_(1/0,o.signal)}catch{}return o}),s=0;try{return await mL(this.addrs.map(async(o,a)=>{let c=await n.shift(),u;try{let l=i[a].signal;u=await this.dialAction(o,{...e,signal:e.signal?yL([l,e.signal]):l}),i[a]=void 0}finally{s++,this.addrs.length-s>=r.length?n.push(c):this.dialer.releaseToken(r.splice(r.indexOf(c),1)[0])}return u}))}finally{i.forEach(o=>{o!==void 0&&o.abort()}),r.forEach(o=>this.dialer.releaseToken(o))}}};d_.exports=f_});var w_=b((KK,b_)=>{"use strict";var p_=Oe(),EL=Vi(),bL=ji(),{pipe:wL}=fr(),fo=Object.assign(p_("libp2p:dialer"),{error:p_("libp2p:dialer:err")}),Ou=ge(),{Multiaddr:bh}=$t(),{TimeoutController:_L}=ud(),{AbortError:SL}=xu(),{anySignal:xL}=hh(),{setMaxListeners:y_}=rr(),AL=h_(),{publicAddressesFirst:CL}=Sd(),g_=md(),m_=Dd(),{codes:Ma}=Ye(),{DIAL_TIMEOUT:IL,MAX_PARALLEL_DIALS:TL,MAX_PER_PEER_DIALS:RL,MAX_ADDRS_TO_DIAL:BL}=hu(),v_="dialler",PL="pending-dials",NL="pending-dial-targets",E_=class{constructor({transportManager:e,peerStore:r,connectionGater:n,addressSorter:i=CL,maxParallelDials:s=TL,maxAddrsToDial:o=BL,dialTimeout:a=IL,maxDialsPerPeer:c=RL,resolvers:u={},metrics:l}){this.connectionGater=n,this.transportManager=e,this.peerStore=r,this.addressSorter=i,this.maxParallelDials=s,this.maxAddrsToDial=o,this.timeout=a,this.maxDialsPerPeer=c,this.tokens=[...new Array(s)].map((f,d)=>d),this._pendingDials=m_({component:v_,metric:PL,metrics:l}),this._pendingDialTargets=m_({component:v_,metric:NL,metrics:l});for(let[f,d]of Object.entries(u))bh.resolvers.set(f,d)}destroy(){for(let e of this._pendingDials.values())try{e.controller.abort()}catch(r){fo.error(r)}this._pendingDials.clear();for(let e of this._pendingDialTargets.values())e.reject(new SL("Dialer was destroyed"));this._pendingDialTargets.clear()}async connectToPeer(e,r={}){let{id:n}=g_(e);if(await this.connectionGater.denyDialPeer(n))throw Ou(new Error("The dial request is blocked by gater.allowDialPeer"),Ma.ERR_PEER_DIAL_INTERCEPTED);let i=await this._createCancellableDialTarget(e);if(!i.addrs.length)throw Ou(new Error("The dial request has no valid addresses"),Ma.ERR_NO_VALID_ADDRESSES);let s=this._pendingDials.get(i.id)||this._createPendingDial(i,r);try{let o=await s.promise;return fo("dial succeeded to %s",i.id),o}catch(o){throw s.controller.signal.aborted&&(o.code=Ma.ERR_TIMEOUT),fo.error(o),o}finally{s.destroy()}}async _createCancellableDialTarget(e){let r=`${parseInt(String(Math.random()*1e9),10).toString()+Date.now()}`,n=new Promise((i,s)=>{this._pendingDialTargets.set(r,{resolve:i,reject:s})});try{return await Promise.race([this._createDialTarget(e),n])}finally{this._pendingDialTargets.delete(r)}}async _createDialTarget(e){let{id:r,multiaddrs:n}=g_(e);n&&await this.peerStore.addressBook.add(r,n);let i=await wL(await this.peerStore.addressBook.getMultiaddrsForPeer(r,this.addressSorter),a=>bL(a,async c=>!await this.connectionGater.denyDialMultiaddr(r,c)),a=>EL(a));bh.isMultiaddr(e)&&(i=i.filter(a=>!e.equals(a)),i.unshift(e));let s=[];for(let a of i)(await this._resolve(a)).forEach(u=>s.push(u));let o=s.filter(a=>this.transportManager.transportForMultiaddr(a));if(o.length>this.maxAddrsToDial)throw await this.peerStore.delete(r),Ou(new Error("dial with more addresses than allowed"),Ma.ERR_TOO_MANY_ADDRESSES);return{id:r.toB58String(),addrs:o}}_createPendingDial(e,r={}){let n=(u,l)=>{if(l.signal.aborted)throw Ou(new Error("already aborted"),Ma.ERR_ALREADY_ABORTED);return this.transportManager.dial(u,l)},i=new AL({addrs:e.addrs,dialAction:n,dialer:this}),s=new _L(this.timeout),o=[s.signal];r.signal&&o.push(r.signal);let a=xL(o);try{y_&&y_(1/0,a)}catch{}let c={dialRequest:i,controller:s,promise:i.run({...r,signal:a}),destroy:()=>{s.clear(),this._pendingDials.delete(e.id)}};return this._pendingDials.set(e.id,c),c}getTokens(e){let r=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,r);return fo("%d tokens request, returning %d, %d remaining",e,r,this.tokens.length),n}releaseToken(e){this.tokens.indexOf(e)>-1||(fo("token %d released",e),this.tokens.push(e))}async _resolve(e){if(!e.protoNames().includes("dnsaddr"))return[e];let n=await this._resolveRecord(e);return(await Promise.all(n.map(o=>this._resolve(o)))).flat().reduce((o,a)=>(o.find(c=>c.equals(a))||o.push(a),o),[])}async _resolveRecord(e){try{return e=new bh(e.toString()),await e.resolve()}catch(r){return fo.error(`multiaddr ${e} could not be resolved`),[]}}};b_.exports=E_});var S_=b((VK,__)=>{"use strict";function OL(t){return t>=55296&&t<=56319}function DL(t){return t>=56320&&t<=57343}__.exports=function(e,r,n){if(typeof r!="string")throw new Error("Input must be string");for(var i=r.length,s=0,o,a,c=0;cn)return r.slice(0,c-a.length+1)}return r}});var A_=b((jK,x_)=>{"use strict";function LL(t){return t>=55296&&t<=56319}function kL(t){return t>=56320&&t<=57343}x_.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var r=e.length,n=0,i=null,s=null,o=0;o=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var I_=b(($K,C_)=>{"use strict";var qL=S_(),UL=A_();C_.exports=qL.bind(null,UL)});var B_=b((HK,R_)=>{"use strict";var ML=I_(),FL=/[\/\?<>\\:\*\|"]/g,KL=/[\x00-\x1f\x80-\x9f]/g,VL=/^\.+$/,jL=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,$L=/[\. ]+$/;function T_(t,e){if(typeof t!="string")throw new Error("Input must be string");var r=t.replace(FL,e).replace(KL,e).replace(VL,e).replace(jL,e).replace($L,e);return ML(r,255)}R_.exports=function(t,e){var r=e&&e.replacement||"",n=T_(t,r);return r===""?n:T_(n,"")}});var O_=b((zK,N_)=>{"use strict";Rs();var Du=_e(),{toString:ho}=(Lt(),Kt),{fromString:P_}=(Dt(),Ft);N_.exports={createCipheriv:(t,e,r)=>{let n=Du.cipher.createCipher("AES-CTR",ho(e,"ascii"));return n.start({iv:ho(r,"ascii")}),{update:i=>(n.update(Du.util.createBuffer(ho(i,"ascii"))),P_(n.output.getBytes(),"ascii"))}},createDecipheriv:(t,e,r)=>{let n=Du.cipher.createDecipher("AES-CTR",ho(e,"ascii"));return n.start({iv:ho(r,"ascii")}),{update:i=>(n.update(Du.util.createBuffer(ho(i,"ascii"))),P_(n.output.getBytes(),"ascii"))}}}});var k_=b((GK,L_)=>{"use strict";var HL=ge(),D_={16:"aes-128-ctr",32:"aes-256-ctr"};L_.exports=function(t){let e=D_[t.length];if(!e){let r=Object.entries(D_).map(([n,i])=>`${n} (${i})`).join(" / ");throw HL(new Error(`Invalid key length ${t.length} bytes. Must be ${r}`),"ERR_INVALID_KEY_LENGTH")}return e}});var M_=b(U_=>{"use strict";var q_=O_(),zL=k_();U_.create=async function(t,e){let r=zL(t),n=q_.createCipheriv(r,t,e),i=q_.createDecipheriv(r,t,e);return{async encrypt(o){return n.update(o)},async decrypt(o){return i.update(o)}}}});var V_=b((YK,K_)=>{"use strict";var GL=$l(),WL=Qe(),YL=ge(),F_={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function QL(t,e,r,n,i){let s=F_[i];if(!s){let a=Object.keys(F_).join(" / ");throw YL(new Error(`Hash '${i}' is unknown or not supported. Must be ${a}`),"ERR_UNSUPPORTED_HASH_TYPE")}let o=GL(t,e,r,n,s);return WL.encode64(o)}K_.exports=QL});var Lu=b(po=>{"use strict";var XL=Pf(),ZL=M_(),JL=Wc();po.aes=ZL;po.hmac=XL;po.keys=JL;po.randomBytes=Nc();po.pbkdf2=V_()});var z_=b((XK,H_)=>{var yo=_e();Wn();Qe();var J=yo.asn1,go=H_.exports=yo.pkcs7asn1=yo.pkcs7asn1||{};yo.pkcs7=yo.pkcs7||{};yo.pkcs7.asn1=go;var j_={name:"ContentInfo",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:J.Class.UNIVERSAL,type:J.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:J.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};go.contentInfoValidator=j_;var $_={name:"EncryptedContentInfo",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:J.Class.UNIVERSAL,type:J.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:J.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:J.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};go.envelopedDataValidator={name:"EnvelopedData",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:J.Class.UNIVERSAL,type:J.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat($_)};go.encryptedDataValidator={name:"EncryptedData",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"version"}].concat($_)};var e6={name:"SignerInfo",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:J.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:J.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:J.Class.UNIVERSAL,type:J.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:J.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};go.signedDataValidator={name:"SignedData",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:J.Class.UNIVERSAL,type:J.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},j_,{name:"SignedData.Certificates",tagClass:J.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:J.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:J.Class.UNIVERSAL,type:J.Type.SET,capture:"signerInfos",optional:!0,value:[e6]}]};go.recipientInfoValidator={name:"RecipientInfo",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:J.Class.UNIVERSAL,type:J.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:J.Class.UNIVERSAL,type:J.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:J.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:J.Class.UNIVERSAL,type:J.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var W_=b((ZK,G_)=>{var is=_e();Qe();is.mgf=is.mgf||{};var t6=G_.exports=is.mgf.mgf1=is.mgf1=is.mgf1||{};t6.create=function(t){var e={generate:function(r,n){for(var i=new is.util.ByteBuffer,s=Math.ceil(n/t.digestLength),o=0;o{var ku=_e();W_();Y_.exports=ku.mgf=ku.mgf||{};ku.mgf.mgf1=ku.mgf1});var Z_=b((eV,X_)=>{var ss=_e();Ni();Qe();var r6=X_.exports=ss.pss=ss.pss||{};r6.create=function(t){arguments.length===3&&(t={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var e=t.md,r=t.mgf,n=e.digestLength,i=t.salt||null;typeof i=="string"&&(i=ss.util.createBuffer(i));var s;if("saltLength"in t)s=t.saltLength;else if(i!==null)s=i.length();else throw new Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==s)throw new Error("Given salt length does not match length of given salt.");var o=t.prng||ss.random,a={};return a.encode=function(c,u){var l,f=u-1,d=Math.ceil(f/8),p=c.digest().getBytes();if(d>8*d-f&255;return F=String.fromCharCode(F.charCodeAt(0)&~M)+F.substr(1),F+v+String.fromCharCode(188)},a.verify=function(c,u,l){var f,d=l-1,p=Math.ceil(d/8);if(u=u.substr(-p),p>8*p-d&255;if((g.charCodeAt(0)&w)!=0)throw new Error("Bits beyond keysize not zero as expected.");var C=r.generate(v,h),q="";for(f=0;f{var fe=_e();Rs();Wn();vc();Yn();Q_();Cs();_c();Z_();Yo();Qe();var y=fe.asn1,Q=nS.exports=fe.pki=fe.pki||{},Ne=Q.oids,gt={};gt.CN=Ne.commonName;gt.commonName="CN";gt.C=Ne.countryName;gt.countryName="C";gt.L=Ne.localityName;gt.localityName="L";gt.ST=Ne.stateOrProvinceName;gt.stateOrProvinceName="ST";gt.O=Ne.organizationName;gt.organizationName="O";gt.OU=Ne.organizationalUnitName;gt.organizationalUnitName="OU";gt.E=Ne.emailAddress;gt.emailAddress="E";var J_=fe.pki.rsa.publicKeyValidator,n6={name:"Certificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},J_,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},i6={name:"rsapss",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},s6={name:"CertificationRequestInfo",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},J_,{name:"CertificationRequestInfo.attributes",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:y.Class.UNIVERSAL,type:y.Type.SET,constructed:!0}]}]}]},o6={name:"CertificationRequest",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[s6,{name:"CertificationRequest.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};Q.RDNAttributesAsArray=function(t,e){for(var r=[],n,i,s,o=0;o2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(o.validity.notBefore=c[0],o.validity.notAfter=c[1],o.tbsCertificate=r.tbsCertificate,e){o.md=Uu({signatureOid:o.signatureOid,type:"certificate"});var u=y.toDer(o.tbsCertificate);o.md.update(u.getBytes())}var l=fe.md.sha1.create(),f=y.toDer(r.certIssuer);l.update(f.getBytes()),o.issuer.getField=function(h){return gi(o.issuer,h)},o.issuer.addField=function(h){Or([h]),o.issuer.attributes.push(h)},o.issuer.attributes=Q.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(o.issuer.uniqueId=r.certIssuerUniqueId),o.issuer.hash=l.digest().toHex();var d=fe.md.sha1.create(),p=y.toDer(r.certSubject);return d.update(p.getBytes()),o.subject.getField=function(h){return gi(o.subject,h)},o.subject.addField=function(h){Or([h]),o.subject.attributes.push(h)},o.subject.attributes=Q.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(o.subject.uniqueId=r.certSubjectUniqueId),o.subject.hash=d.digest().toHex(),r.certExtensions?o.extensions=Q.certificateExtensionsFromAsn1(r.certExtensions):o.extensions=[],o.publicKey=Q.publicKeyFromAsn1(r.subjectPublicKeyInfo),o};Q.certificateExtensionsFromAsn1=function(t){for(var e=[],r=0;r1&&(n=r.value.charCodeAt(1),i=r.value.length>2?r.value.charCodeAt(2):0),e.digitalSignature=(n&128)==128,e.nonRepudiation=(n&64)==64,e.keyEncipherment=(n&32)==32,e.dataEncipherment=(n&16)==16,e.keyAgreement=(n&8)==8,e.keyCertSign=(n&4)==4,e.cRLSign=(n&2)==2,e.encipherOnly=(n&1)==1,e.decipherOnly=(i&128)==128}else if(e.name==="basicConstraints"){var r=y.fromDer(e.value);r.value.length>0&&r.value[0].type===y.Type.BOOLEAN?e.cA=r.value[0].value.charCodeAt(0)!==0:e.cA=!1;var s=null;r.value.length>0&&r.value[0].type===y.Type.INTEGER?s=r.value[0].value:r.value.length>1&&(s=r.value[1].value),s!==null&&(e.pathLenConstraint=y.derToInteger(s))}else if(e.name==="extKeyUsage")for(var r=y.fromDer(e.value),o=0;o1&&(n=r.value.charCodeAt(1)),e.client=(n&128)==128,e.server=(n&64)==64,e.email=(n&32)==32,e.objsign=(n&16)==16,e.reserved=(n&8)==8,e.sslCA=(n&4)==4,e.emailCA=(n&2)==2,e.objCA=(n&1)==1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];for(var c,r=y.fromDer(e.value),u=0;u128)throw new Error('Invalid "nsComment" content.');t.value=y.create(y.Class.UNIVERSAL,y.Type.IA5STRING,!1,t.comment)}else if(t.name==="subjectKeyIdentifier"&&e.cert){var f=e.cert.generateSubjectKeyIdentifier();t.subjectKeyIdentifier=f.toHex(),t.value=y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,f.getBytes())}else if(t.name==="authorityKeyIdentifier"&&e.cert){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);var a=t.value.value;if(t.keyIdentifier){var d=t.keyIdentifier===!0?e.cert.generateSubjectKeyIdentifier().getBytes():t.keyIdentifier;a.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!1,d))}if(t.authorityCertIssuer){var p=[y.create(y.Class.CONTEXT_SPECIFIC,4,!0,[mo(t.authorityCertIssuer===!0?e.cert.issuer:t.authorityCertIssuer)])];a.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,p))}if(t.serialNumber){var h=fe.util.hexToBytes(t.serialNumber===!0?e.cert.serialNumber:t.serialNumber);a.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!1,h))}}else if(t.name==="cRLDistributionPoints"){t.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);for(var a=t.value.value,g=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),v=y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[]),u,l=0;l=c6&&t0&&n.value.push(Q.certificateExtensionsToAsn1(t.extensions)),n};Q.getCertificationRequestInfo=function(t){var e=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(t.version).getBytes()),mo(t.subject),Q.publicKeyToAsn1(t.publicKey),a6(t)]);return e};Q.distinguishedNameToAsn1=function(t){return mo(t)};Q.certificateToAsn1=function(t){var e=t.tbsCertificate||Q.getTBSCertificate(t);return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[e,y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.signatureOid).getBytes()),wh(t.signatureOid,t.signatureParameters)]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,String.fromCharCode(0)+t.signature)])};Q.certificateExtensionsToAsn1=function(t){var e=y.create(y.Class.CONTEXT_SPECIFIC,3,!0,[]),r=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);e.value.push(r);for(var n=0;nc.validity.notAfter)&&(o={message:"Certificate is not valid yet or has expired.",error:Q.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:i}),o===null){if(u=e[0]||t.getIssuer(c),u===null&&c.isIssuer(c)&&(l=!0,u=c),u){var f=u;fe.util.isArray(f)||(f=[f]);for(var d=!1;!d&&f.length>0;){u=f.shift();try{d=u.verify(c)}catch(F){}}d||(o={message:"Certificate signature is invalid.",error:Q.certificateError.bad_certificate})}o===null&&(!u||l)&&!t.hasCertificate(c)&&(o={message:"Certificate is not trusted.",error:Q.certificateError.unknown_ca})}if(o===null&&u&&!c.isIssuer(u)&&(o={message:"Certificate issuer is invalid.",error:Q.certificateError.bad_certificate}),o===null)for(var p={keyUsage:!0,basicConstraints:!0},h=0;o===null&&hv.pathLenConstraint&&(o={message:"Certificate basicConstraints pathLenConstraint violated.",error:Q.certificateError.bad_certificate})}}var q=o===null?!0:o.error,W=r.verify?r.verify(q,a,n):q;if(W===!0)o=null;else throw q===!0&&(o={message:"The application rejected the certificate.",error:Q.certificateError.bad_certificate}),(W||W===0)&&(typeof W=="object"&&!fe.util.isArray(W)?(W.message&&(o.message=W.message),W.error&&(o.error=W.error)):typeof W=="string"&&(o.error=W)),o;s=!1,++a}while(e.length>0);return!0}});var oS=b((rV,sS)=>{var X=_e();Rs();Wn();vc();Cs();_c();z_();Ni();Qe();_h();var A=X.asn1,Xt=sS.exports=X.pkcs7=X.pkcs7||{};Xt.messageFromPem=function(t){var e=X.pem.decode(t)[0];if(e.type!=="PKCS7"){var r=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw r.headerType=e.type,r}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var n=A.fromDer(e.body);return Xt.messageFromAsn1(n)};Xt.messageToPem=function(t,e){var r={type:"PKCS7",body:A.toDer(t.toAsn1()).getBytes()};return X.pem.encode(r,{maxline:e})};Xt.messageFromAsn1=function(t){var e={},r=[];if(!A.validate(t,Xt.asn1.contentInfoValidator,e,r)){var n=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw n.errors=r,n}var i=A.derToOid(e.contentType),s;switch(i){case X.pki.oids.envelopedData:s=Xt.createEnvelopedData();break;case X.pki.oids.encryptedData:s=Xt.createEncryptedData();break;case X.pki.oids.signedData:s=Xt.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return s.fromAsn1(e.content.value[0]),s};Xt.createSignedData=function(){var t=null;return t={type:X.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(n){if(xh(t,n,Xt.asn1.signedDataValidator),t.certificates=[],t.crls=[],t.digestAlgorithmIdentifiers=[],t.contentInfo=null,t.signerInfos=[],t.rawCapture.certificates)for(var i=t.rawCapture.certificates.value,s=0;s0&&o.value[0].value.push(A.create(A.Class.CONTEXT_SPECIFIC,0,!0,n)),s.length>0&&o.value[0].value.push(A.create(A.Class.CONTEXT_SPECIFIC,1,!0,s)),o.value[0].value.push(A.create(A.Class.UNIVERSAL,A.Type.SET,!0,t.signerInfos)),A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(t.type).getBytes()),o])},addSigner:function(n){var i=n.issuer,s=n.serialNumber;if(n.certificate){var o=n.certificate;typeof o=="string"&&(o=X.pki.certificateFromPem(o)),i=o.issuer.attributes,s=o.serialNumber}var a=n.key;if(!a)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof a=="string"&&(a=X.pki.privateKeyFromPem(a));var c=n.digestAlgorithm||X.pki.oids.sha1;switch(c){case X.pki.oids.sha1:case X.pki.oids.sha256:case X.pki.oids.sha384:case X.pki.oids.sha512:case X.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=n.authenticatedAttributes||[];if(u.length>0){for(var l=!1,f=!1,d=0;d0){for(var r=A.create(A.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n=r&&i{"use strict";_h();var m6=_e(),aS=m6.pki,v6=(t,e)=>{let r=aS.setRsaPublicKey(e.n,e.e),n=aS.createCertificate();n.publicKey=r,n.serialNumber="01",n.validity.notBefore=new Date,n.validity.notAfter=new Date,n.validity.notAfter.setFullYear(n.validity.notBefore.getFullYear()+10);let i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:t.id}];return n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),n.sign(e),n};async function E6(t,e){let r=t.map(e),i=(await Promise.all(r)).findIndex(s=>s);return t[i]}cS.exports={certificateForKey:v6,findAsync:E6}});var hS=b((iV,dS)=>{"use strict";oS();ef();var mi=_e(),{certificateForKey:b6,findAsync:w6}=uS(),vo=ge(),{fromString:lS}=(Dt(),Ft),{toString:_6}=(Lt(),Kt),{codes:Eo}=Ye(),Ah=new WeakMap,fS=class{constructor(e,r){if(!e)throw vo(new Error("keychain is required"),Eo.ERR_KEYCHAIN_REQUIRED);this.keychain=e,Ah.set(this,{dek:r})}async encrypt(e,r){if(!(r instanceof Uint8Array))throw vo(new Error("Plain data must be a Uint8Array"),Eo.ERR_INVALID_PARAMETERS);let n=await this.keychain.findKeyByName(e),i=await this.keychain._getPrivateKey(e),s=Ah.get(this).dek,o=mi.pki.decryptRsaPrivateKey(i,s),a=await b6(n,o),c=mi.pkcs7.createEnvelopedData();c.addRecipient(a),c.content=mi.util.createBuffer(r),c.encrypt();let u=mi.asn1.toDer(c.toAsn1()).getBytes();return lS(u,"ascii")}async decrypt(e){if(!(e instanceof Uint8Array))throw vo(new Error("CMS data is required"),Eo.ERR_INVALID_PARAMETERS);let r;try{let u=mi.util.createBuffer(_6(e,"ascii")),l=mi.asn1.fromDer(u);r=mi.pkcs7.messageFromAsn1(l)}catch(u){throw vo(new Error("Invalid CMS: "+u.message),Eo.ERR_INVALID_CMS)}let n=r.recipients.filter(u=>u.issuer.find(l=>l.shortName==="O"&&l.value==="ipfs")).filter(u=>u.issuer.find(l=>l.shortName==="CN")).map(u=>({recipient:u,keyId:u.issuer.find(l=>l.shortName==="CN").value})),i=await w6(n,async u=>{try{if(await this.keychain.findKeyById(u.keyId))return!0}catch(l){return!1}return!1});if(!i){let u=n.map(l=>l.keyId);throw vo(new Error("Decryption needs one of the key(s): "+u.join(", ")),Eo.ERR_MISSING_KEYS,{missingKeys:u})}let s=await this.keychain.findKeyById(i.keyId);if(!s)throw vo(new Error("No key available to decrypto"),Eo.ERR_NO_KEY);let o=await this.keychain._getPrivateKey(s.name),a=Ah.get(this).dek,c=mi.pki.decryptRsaPrivateKey(o,a);return r.decrypt(i.recipient,c),lS(r.content.getBytes(),"ascii")}};dS.exports=fS});var bS=b((sV,ES)=>{"use strict";var pS=Oe(),yS=Object.assign(pS("libp2p:keychain"),{error:pS("libp2p:keychain:err")}),S6=B_(),x6=Ys(),os=Lu(),{Key:gS}=(iu(),sd),A6=hS(),ct=ge(),{codes:ut}=Ye(),{toString:as}=(Lt(),Kt),{fromString:kn}=(Dt(),Ft);gf();var C6="/pkcs8/",mS="/info/",vi=new WeakMap,cs={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},Ch={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function qn(t){return!t||typeof t!="string"?!1:t===S6(t.trim())}async function Ve(t){let e=200,r=1e3,n=Math.random()*(r-e)+e;throw await new Promise(i=>setTimeout(i,n)),t}function En(t){return new gS(C6+t)}function Ei(t){return new gS(mS+t)}var vS=class{constructor(e,r){if(!e)throw new Error("store is required");if(this.store=e,this.opts=x6(Ch,r),this.opts.pass&&this.opts.pass.length<20)throw new Error("pass must be least 20 characters");if(this.opts.dek.keyLengthn.id===e)}catch(r){return Ve(r)}}async findKeyByName(e){if(!qn(e))return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));let r=Ei(e);try{let n=await this.store.get(r);return JSON.parse(as(n))}catch(n){return Ve(ct(new Error(`Key '${e}' does not exist. ${n.message}`),ut.ERR_KEY_NOT_FOUND))}}async removeKey(e){let r=this;if(!qn(e)||e==="self")return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));let n=En(e),i=await r.findKeyByName(e),s=r.store.batch();return s.delete(n),s.delete(Ei(e)),await s.commit(),i}async renameKey(e,r){let n=this;if(!qn(e)||e==="self")return Ve(ct(new Error(`Invalid old key name '${e}'`),ut.ERR_OLD_KEY_NAME_INVALID));if(!qn(r)||r==="self")return Ve(ct(new Error(`Invalid new key name '${r}'`),ut.ERR_NEW_KEY_NAME_INVALID));let i=En(e),s=En(r),o=Ei(e),a=Ei(r);if(await n.store.has(s))return Ve(ct(new Error(`Key '${r}' already exists`),ut.ERR_KEY_ALREADY_EXISTS));try{let u=await n.store.get(i),l=await n.store.get(o),f=JSON.parse(as(l));f.name=r;let d=n.store.batch();return d.put(s,u),d.put(a,kn(JSON.stringify(f))),d.delete(i),d.delete(o),await d.commit(),f}catch(u){return Ve(u)}}async exportKey(e,r){if(!qn(e))return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));if(!r)return Ve(ct(new Error("Password is required"),ut.ERR_PASSWORD_REQUIRED));let n=En(e);try{let i=await this.store.get(n),s=as(i),o=vi.get(this).dek;return(await os.keys.import(s,o)).export(r)}catch(i){return Ve(i)}}async importKey(e,r,n){let i=this;if(!qn(e)||e==="self")return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));if(!r)return Ve(ct(new Error("PEM encoded key is required"),ut.ERR_PEM_REQUIRED));let s=En(e);if(await i.store.has(s))return Ve(ct(new Error(`Key '${e}' already exists`),ut.ERR_KEY_ALREADY_EXISTS));let a;try{a=await os.keys.import(r,n)}catch(f){return Ve(ct(new Error("Cannot read the key, most likely the password is wrong"),ut.ERR_CANNOT_READ_KEY))}let c;try{c=await a.id();let f=vi.get(this).dek;r=await a.export(f)}catch(f){return Ve(f)}let u={name:e,id:c},l=i.store.batch();return l.put(s,kn(r)),l.put(Ei(e),kn(JSON.stringify(u))),await l.commit(),u}async importPeer(e,r){let n=this;if(!qn(e))return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));if(!r||!r.privKey)return Ve(ct(new Error("Peer.privKey is required"),ut.ERR_MISSING_PRIVATE_KEY));let i=r.privKey,s=En(e);if(await n.store.has(s))return Ve(ct(new Error(`Key '${e}' already exists`),ut.ERR_KEY_ALREADY_EXISTS));try{let a=await i.id(),c=vi.get(this).dek,u=await i.export(c),l={name:e,id:a},f=n.store.batch();return f.put(s,kn(u)),f.put(Ei(e),kn(JSON.stringify(l))),await f.commit(),l}catch(a){return Ve(a)}}async _getPrivateKey(e){if(!qn(e))return Ve(ct(new Error(`Invalid key name '${e}'`),ut.ERR_INVALID_KEY_NAME));try{let r=En(e),n=await this.store.get(r);return as(n)}catch(r){return Ve(ct(new Error(`Key '${e}' does not exist. ${r.message}`),ut.ERR_KEY_NOT_FOUND))}}async rotateKeychainPass(e,r){if(typeof e!="string")return Ve(ct(new Error(`Invalid old pass type '${typeof e}'`),ut.ERR_INVALID_OLD_PASS_TYPE));if(typeof r!="string")return Ve(ct(new Error(`Invalid new pass type '${typeof r}'`),ut.ERR_INVALID_NEW_PASS_TYPE));if(r.length<20)return Ve(ct(new Error(`Invalid pass length ${r.length}`),ut.ERR_INVALID_PASS_LENGTH));yS("recreating keychain");let n=vi.get(this).dek;this.opts.pass=r;let i=r?os.pbkdf2(r,this.opts.dek.salt,this.opts.dek.iterationCount,this.opts.dek.keyLength,this.opts.dek.hash):"";vi.set(this,{dek:i});let s=await this.listKeys();for(let o of s){let a=await this.store.get(En(o.name)),c=as(a),u=await os.keys.import(c,n),l=i.toString(),f=await u.export(l),d=this.store.batch(),p={name:o.name,id:o.id};d.put(En(o.name),kn(f)),d.put(Ei(o.name),kn(JSON.stringify(p))),await d.commit()}yS("keychain reconstructed")}};ES.exports=vS});var Fu=b((Mu,wS)=>{(function(t,e){typeof Mu=="object"&&typeof wS!="undefined"?e(Mu):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis!="undefined"?globalThis:t||self,e(t.streamingIterables={}))})(Mu,function(t){"use strict";async function*e(m,S){let R=[];for await(let O of S)R.push(O),R.length===m&&(yield R,R=[]);R.length>0&&(yield R)}function*r(m,S){let R=[];for(let O of S)R.push(O),R.length===m&&(yield R,R=[]);R.length>0&&(yield R)}function n(m,S){return S===void 0?R=>n(m,R):S[Symbol.asyncIterator]?e(m,S):r(m,S)}let i=Symbol("TIMEOUT"),s=m=>{let S;return[new Promise(R=>{S=setTimeout(()=>R(i),m)}),()=>{clearTimeout(S)}]};async function*o(m,S,R){let O=R[Symbol.asyncIterator](),H,ne=[],ce,oe,ae=()=>{he(),[ce,oe]=s(S)},he=()=>{oe&&oe(),ce=void 0};for(H=O.next();;){let ke=await(ce?Promise.race([H,ce]):H);if(ke===i||ke.done){if(ne.length&&(yield ne,ne=[]),he(),ke!==i)break;continue}if(H=O.next(),ne.push(ke.value),ne.length===1&&ae(),ne.length===m){yield ne,ne=[],he();continue}}}function a(m,S,R){return R===void 0?O=>a(m,S,O):R[Symbol.asyncIterator]&&S!==1/0?o(m,S,R):n(m,R)}function c(m){if(typeof m.next=="function")return m;if(typeof m[Symbol.iterator]=="function")return m[Symbol.iterator]();if(typeof m[Symbol.asyncIterator]=="function")return m[Symbol.asyncIterator]();throw new TypeError('"values" does not to conform to any of the iterator or iterable protocols')}function u(){let m,S;return{promise:new Promise((O,H)=>{S=O,m=H}),reject:m,resolve:S}}function l(m,S){let R=c(S),O=[],H=[],ne=!1,ce=!1;function oe(){for(;H.length>0&&O.length>0;){let ve=H.shift(),{error:nt,value:wt}=O.shift();nt?ve.reject(nt):ve.resolve({done:!1,value:wt})}for(;H.length>0&&ce;){let{resolve:ve}=H.shift();ve({done:!0,value:void 0})}}async function ae(){if(!ce&&!ne&&!(O.length>=m)){ne=!0;try{let{done:ve,value:nt}=await R.next();ve?ce=!0:O.push({value:nt})}catch(ve){ce=!0,O.push({error:ve})}oe(),ne=!1,ae()}}async function he(){if(O.length>0){let{error:nt,value:wt}=O.shift();if(nt)throw nt;return ae(),{done:!1,value:wt}}if(ce)return{done:!0,value:void 0};let ve=u();return H.push(ve),ae(),ve.promise}let ke={next:he,[Symbol.asyncIterator]:()=>ke};return ke}function*f(m,S){let R=[],O;try{for(let H of S)R.push(H),!(R.length<=m)&&(yield R.shift())}catch(H){O=H}for(let H of R)yield H;if(O)throw O}function d(m,S){return S===void 0?R=>d(m,R):m===0?S:S[Symbol.asyncIterator]?l(m,S):f(m,S)}async function p(m){let S=[];for await(let R of m)S.push(R);return S}function h(m){return m[Symbol.asyncIterator]?p(m):Array.from(m)}async function*g(m){for await(let S of m)yield*S}function*v(m){for(let S of m)yield*S}function w(...m){return m.find(R=>R[Symbol.asyncIterator]!==void 0)?g(m):v(m)}async function C(m){for await(let S of m);}function q(m){if(m[Symbol.asyncIterator])return C(m);for(let S of m);}async function*W(m,S){for await(let R of S)await m(R)&&(yield R)}function F(m,S){return S===void 0?R=>W(m,R):W(m,S)}async function*M(m){for await(let S of m)S&&typeof S!="string"&&(S[Symbol.iterator]||S[Symbol.asyncIterator])?yield*M(S):yield S}async function*re(m,S){for await(let R of S)yield await m(R)}function ie(m,S){return S===void 0?R=>re(m,R):re(m,S)}function z(m,S){return S===void 0?R=>z(m,R):F(R=>R!=null,M(ie(m,S)))}function Ae(m,S,R){let O=c(R),H=[],ne=[],ce=!1,oe=!1,ae=0,he=null;function ke(){for(;ne.length>0&&H.length>0;){let{resolve:Ce}=ne.shift(),pe=H.shift();Ce({done:!1,value:pe})}for(;ne.length>0&&ae===0&&ce;){let{resolve:Ce,reject:pe}=ne.shift();he?(pe(he),he=null):Ce({done:!0,value:void 0})}}async function ve(){if(ce){ke();return}if(!oe&&!(ae+H.length>=m)){oe=!0,ae++;try{let{done:Ce,value:pe}=await O.next();Ce?(ce=!0,ae--,ke()):nt(pe)}catch(Ce){ce=!0,ae--,he=Ce,ke()}oe=!1,ve()}}async function nt(Ce){try{let pe=await S(Ce);if(pe&&pe[Symbol.asyncIterator])for await(let it of pe)H.push(it);else H.push(pe)}catch(pe){ce=!0,he=pe}ae--,ke(),ve()}async function wt(){if(H.length===0){let pe=u();return ne.push(pe),ve(),pe.promise}let Ce=H.shift();return ve(),{done:!1,value:Ce}}let cr={next:wt,[Symbol.asyncIterator]:()=>cr};return cr}function ye(m,S,R){return S===void 0?(O,H)=>H?ye(m,O,H):ye(m,O):R===void 0?O=>ye(m,S,O):F(O=>O!=null,M(Ae(m,S,R)))}async function be(m){return new Promise(S=>{m.once("readable",()=>{S()})})}async function*ft(m){for(;;){let S=m.read();if(S!==null){yield S;continue}if(m._readableState.ended)break;await be(m)}}function bt(m){return typeof m[Symbol.asyncIterator]=="function"?m:ft(m)}async function*Fe(...m){let S=new Set(m.map(c));for(;S.size>0;)for(let R of S){let O=await R.next();O.done?S.delete(R):yield O.value}}function $e(m,...S){let R=m();for(let O of S)R=O(R);return R}async function*se(m,S,R){let O=null,H=ae=>({value:S(ae)}),ne=async function*(ae){for await(let he of ae){if(O)return;yield he}},ce=$e(()=>R,d(1),ne,ie(H),d(m-1)),oe=c(ce);for(;;){let{value:ae,done:he}=await oe.next();if(he)break;try{let ke=await ae.value;O||(yield ke)}catch(ke){O=ke}}if(O)throw O}function Jt(m,S,R){return S===void 0?(O,H)=>Jt(m,O,H):R===void 0?O=>Jt(m,S,O):m===1?ie(S,R):se(m,S,R)}function Ot(m,S,R){return S===void 0?(O,H)=>H?Ot(m,O,H):Ot(m,O):R===void 0?O=>Ot(m,S,O):F(O=>O!=null,M(Jt(m,S,R)))}async function*wn(...m){let S=m.map(c),R=new Set,O=new Map,H=null,ne=null,ce=null,oe=ve=>{H=ve,ne&&ne(ve)},ae=ve=>{ce&&ce(ve)},he=()=>new Promise((ve,nt)=>{if(H&&nt(H),O.size>0)return ve();ce=ve,ne=nt}),ke=ve=>{let nt=Promise.resolve(ve.next()).then(async({done:wt,value:cr})=>{wt||O.set(ve,cr),R.delete(nt)});R.add(nt),nt.then(ae,oe)};for(let ve of S)ke(ve);for(;;){if(R.size===0&&O.size===0)return;await he();for(let[ve,nt]of O)O.delete(ve),yield nt,ke(ve)}}async function er(m,S,R){let O=S;for await(let H of R)O=await m(O,H);return O}function Qr(m,S,R){return S===void 0?(O,H)=>H?er(m,O,H):Qr(m,O):R===void 0?O=>Qr(m,S,O):er(m,S,R)}async function*Y(m,S){let R=0;for await(let O of S)if(yield await O,R++,R>=m)break}function*Oo(m,S){let R=0;for(let O of S)if(yield O,R++,R>=m)break}function Do(m,S){return S===void 0?R=>Do(m,R):S[Symbol.asyncIterator]?Y(m,S):Oo(m,S)}async function*ps(m,S){for await(let R of S)await m(R),yield R}function tr(m,S){return S===void 0?R=>ps(m,R):ps(m,S)}let qr=m=>new Promise(S=>setTimeout(S,m));function E(m,S,R){if(!Number.isFinite(m))throw new TypeError("Expected `limit` to be a finite number");if(m<=0)throw new TypeError("Expected `limit` to be greater than 0");if(!Number.isFinite(S))throw new TypeError("Expected `interval` to be a finite number");return async function*(){let H=0,ne;for await(let ce of R){if(H0&&await qr(ae),ne=Date.now(),H=1,yield ce}}()}function _(m,S,R){return R===void 0?O=>E(m,S,O):E(m,S,R)}function x(m,S){let R=m[0]+S[0],O=m[1]+S[1];if(O>=1e9){let H=O%1e9;R+=(O-H)/1e9,O=H}return[R,O]}async function*L(m,S){let R=S[Symbol.asyncIterator](),O=[0,0];for(;;){let H=process.hrtime(),{value:ne,done:ce}=await R.next(),oe=process.hrtime(H);if(O=x(O,oe),m.progress&&m.progress(oe,O),ce)return m.total&&m.total(O),ne;yield ne}}function*B(m,S){let R=S[Symbol.iterator](),O=[0,0];for(;;){let H=process.hrtime(),{value:ne,done:ce}=R.next(),oe=process.hrtime(H);if(O=x(O,oe),m.progress&&m.progress(oe,O),ce)return m.total&&m.total(O),ne;yield ne}}function D(m={},S){return S===void 0?R=>D(m,R):S[Symbol.asyncIterator]!==void 0?L(m,S):B(m,S)}function U(m,S,R){let O=c(R),H=[],ne=[],ce=!1,oe=!1,ae=0,he=null;function ke(){for(;ne.length>0&&H.length>0;){let{resolve:Ce}=ne.shift(),pe=H.shift();Ce({done:!1,value:pe})}for(;ne.length>0&&ae===0&&ce;){let{resolve:Ce,reject:pe}=ne.shift();he?(pe(he),he=null):Ce({done:!0,value:void 0})}}async function ve(){if(ce){ke();return}if(!oe&&!(ae+H.length>=m)){oe=!0,ae++;try{let{done:Ce,value:pe}=await O.next();Ce?(ce=!0,ae--,ke()):nt(pe)}catch(Ce){ce=!0,ae--,he=Ce,ke()}oe=!1,ve()}}async function nt(Ce){try{let pe=await S(Ce);H.push(pe)}catch(pe){ce=!0,he=pe}ae--,ke(),ve()}async function wt(){if(H.length===0){let pe=u();return ne.push(pe),ve(),pe.promise}let Ce=H.shift();return ve(),{done:!1,value:Ce}}let cr={next:wt,[Symbol.asyncIterator]:()=>cr};return cr}function T(m,S,R){return S===void 0?(O,H)=>H?T(m,O,H):T(m,O):R===void 0?O=>T(m,S,O):U(m,S,R)}async function P(m,S){let R=null,O=null,H=null,ne=he=>{R=he,O&&O(he)},ce=()=>{H&&H()},oe=()=>{m.removeListener("error",ne),m.removeListener("drain",ce)};m.once("error",ne);let ae=()=>new Promise((he,ke)=>{if(R)return ke(R);m.once("drain",ce),H=he,O=ke});for await(let he of S)if(m.write(he)===!1&&await ae(),R)break;if(oe(),R)throw R}function k(m,S){return S===void 0?R=>P(m,R):P(m,S)}t.batch=n,t.batchWithTimeout=a,t.buffer=d,t.collect=h,t.concat=w,t.consume=q,t.filter=F,t.flatMap=z,t.flatTransform=ye,t.flatten=M,t.fromStream=bt,t.getIterator=c,t.map=ie,t.merge=Fe,t.parallelFlatMap=Ot,t.parallelMap=Jt,t.parallelMerge=wn,t.pipeline=$e,t.reduce=Qr,t.take=Do,t.tap=tr,t.throttle=_,t.time=D,t.transform=T,t.writeToStream=k,Object.defineProperty(t,"__esModule",{value:!0})})});var SS=b((oV,_S)=>{_S.exports=function(t){if(!t)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,r=Object.create(null),n=Object.create(null);function i(s,o){r[s]=o,e++,e>=t&&(e=0,n=r,r=Object.create(null))}return{has:function(s){return r[s]!==void 0||n[s]!==void 0},remove:function(s){r[s]!==void 0&&(r[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var o=r[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){r[s]!==void 0?r[s]=o:i(s,o)},clear:function(){r=Object.create(null),n=Object.create(null)}}}});var AS=b((aV,xS)=>{"use strict";var I6=SS();xS.exports=t=>{let e=I6(t);return e.delete=e.remove,e}});var IS=b((CS,Ku)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,i=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",a=1e14,c=14,u=9007199254740991,l=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],f=1e7,d=1e9;function p(F){var M,re,ie,z=Y.prototype={constructor:Y,toString:null,valueOf:null},Ae=new Y(1),ye=20,be=4,ft=-7,bt=21,Fe=-1e7,$e=1e7,se=!1,Jt=1,Ot=0,wn={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},er="0123456789abcdefghijklmnopqrstuvwxyz",Qr=!0;function Y(E,_){var x,L,B,D,U,T,P,k,m=this;if(!(m instanceof Y))return new Y(E,_);if(_==null){if(E&&E._isBigNumber===!0){m.s=E.s,!E.c||E.e>$e?m.c=m.e=null:E.e=10;U/=10,D++);D>$e?m.c=m.e=null:(m.e=D,m.c=[E]);return}k=String(E)}else{if(!r.test(k=String(E)))return ie(m,k,T);m.s=k.charCodeAt(0)==45?(k=k.slice(1),-1):1}(D=k.indexOf("."))>-1&&(k=k.replace(".","")),(U=k.search(/e/i))>0?(D<0&&(D=U),D+=+k.slice(U+1),k=k.substring(0,U)):D<0&&(D=k.length)}else{if(w(_,2,er.length,"Base"),_==10&&Qr)return m=new Y(E),tr(m,ye+m.e+1,be);if(k=String(E),T=typeof E=="number"){if(E*0!=0)return ie(m,k,T,_);if(m.s=1/E<0?(k=k.slice(1),-1):1,Y.DEBUG&&k.replace(/^0\.0*|\./,"").length>15)throw Error(o+E)}else m.s=k.charCodeAt(0)===45?(k=k.slice(1),-1):1;for(x=er.slice(0,_),D=U=0,P=k.length;UD){D=P;continue}}else if(!B&&(k==k.toUpperCase()&&(k=k.toLowerCase())||k==k.toLowerCase()&&(k=k.toUpperCase()))){B=!0,U=-1,D=0;continue}return ie(m,String(E),T,_)}T=!1,k=re(k,_,10,m.s),(D=k.indexOf("."))>-1?k=k.replace(".",""):D=k.length}for(U=0;k.charCodeAt(U)===48;U++);for(P=k.length;k.charCodeAt(--P)===48;);if(k=k.slice(U,++P)){if(P-=U,T&&Y.DEBUG&&P>15&&(E>u||E!==i(E)))throw Error(o+m.s*E);if((D=D-U-1)>$e)m.c=m.e=null;else if(D=-d&&B<=d&&B===i(B)){if(L[0]===0){if(B===0&&L.length===1)return!0;break e}if(_=(B+1)%c,_<1&&(_+=c),String(L[0]).length==_){for(_=0;_=a||x!==i(x))break e;if(x!==0)return!0}}}else if(L===null&&B===null&&(D===null||D===1||D===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},Y.maximum=Y.max=function(){return Do(arguments,z.lt)},Y.minimum=Y.min=function(){return Do(arguments,z.gt)},Y.random=function(){var E=9007199254740992,_=Math.random()*E&2097151?function(){return i(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(x){var L,B,D,U,T,P=0,k=[],m=new Y(Ae);if(x==null?x=ye:w(x,0,d),U=n(x/c),se)if(crypto.getRandomValues){for(L=crypto.getRandomValues(new Uint32Array(U*=2));P>>11),T>=9e15?(B=crypto.getRandomValues(new Uint32Array(2)),L[P]=B[0],L[P+1]=B[1]):(k.push(T%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(L=crypto.randomBytes(U*=7);P=9e15?crypto.randomBytes(7).copy(L,P):(k.push(T%1e14),P+=7);P=U/7}else throw se=!1,Error(s+"crypto unavailable");if(!se)for(;P=10;T/=10,P++);PB-1&&(T[U+1]==null&&(T[U+1]=0),T[U+1]+=T[U]/B|0,T[U]%=B)}return T.reverse()}return function(x,L,B,D,U){var T,P,k,m,S,R,O,H,ne=x.indexOf("."),ce=ye,oe=be;for(ne>=0&&(m=Ot,Ot=0,x=x.replace(".",""),H=new Y(L),R=H.pow(x.length-ne),Ot=m,H.c=_(W(g(R.c),R.e,"0"),10,B,E),H.e=H.c.length),O=_(x,L,B,U?(T=er,E):(T=E,er)),k=m=O.length;O[--m]==0;O.pop());if(!O[0])return T.charAt(0);if(ne<0?--k:(R.c=O,R.e=k,R.s=D,R=M(R,H,ce,oe,B),O=R.c,S=R.r,k=R.e),P=k+ce+1,ne=O[P],m=B/2,S=S||P<0||O[P+1]!=null,S=oe<4?(ne!=null||S)&&(oe==0||oe==(R.s<0?3:2)):ne>m||ne==m&&(oe==4||S||oe==6&&O[P-1]&1||oe==(R.s<0?8:7)),P<1||!O[0])x=S?W(T.charAt(1),-ce,T.charAt(0)):T.charAt(0);else{if(O.length=P,S)for(--B;++O[--P]>B;)O[P]=0,P||(++k,O=[1].concat(O));for(m=O.length;!O[--m];);for(ne=0,x="";ne<=m;x+=T.charAt(O[ne++]));x=W(x,k,T.charAt(0))}return x}}(),M=function(){function E(L,B,D){var U,T,P,k,m=0,S=L.length,R=B%f,O=B/f|0;for(L=L.slice();S--;)P=L[S]%f,k=L[S]/f|0,U=O*P+k*R,T=R*P+U%f*f+m,m=(T/D|0)+(U/f|0)+O*k,L[S]=T%D;return m&&(L=[m].concat(L)),L}function _(L,B,D,U){var T,P;if(D!=U)P=D>U?1:-1;else for(T=P=0;TB[T]?1:-1;break}return P}function x(L,B,D,U){for(var T=0;D--;)L[D]-=T,T=L[D]1;L.splice(0,1));}return function(L,B,D,U,T){var P,k,m,S,R,O,H,ne,ce,oe,ae,he,ke,ve,nt,wt,cr,Ce=L.s==B.s?1:-1,pe=L.c,it=B.c;if(!pe||!pe[0]||!it||!it[0])return new Y(!L.s||!B.s||(pe?it&&pe[0]==it[0]:!it)?NaN:pe&&pe[0]==0||!it?Ce*0:Ce/0);for(ne=new Y(Ce),ce=ne.c=[],k=L.e-B.e,Ce=D+k+1,T||(T=a,k=h(L.e/c)-h(B.e/c),Ce=Ce/c|0),m=0;it[m]==(pe[m]||0);m++);if(it[m]>(pe[m]||0)&&k--,Ce<0)ce.push(1),S=!0;else{for(ve=pe.length,wt=it.length,m=0,Ce+=2,R=i(T/(it[0]+1)),R>1&&(it=E(it,R,T),pe=E(pe,R,T),wt=it.length,ve=pe.length),ke=wt,oe=pe.slice(0,wt),ae=oe.length;ae=T/2&&nt++;do{if(R=0,P=_(it,oe,wt,ae),P<0){if(he=oe[0],wt!=ae&&(he=he*T+(oe[1]||0)),R=i(he/nt),R>1)for(R>=T&&(R=T-1),O=E(it,R,T),H=O.length,ae=oe.length;_(O,oe,H,ae)==1;)R--,x(O,wt=10;Ce/=10,m++);tr(ne,D+(ne.e=m+k*c-1)+1,U,S)}else ne.e=k,ne.r=+S;return ne}}();function Oo(E,_,x,L){var B,D,U,T,P;if(x==null?x=be:w(x,0,8),!E.c)return E.toString();if(B=E.c[0],U=E.e,_==null)P=g(E.c),P=L==1||L==2&&(U<=ft||U>=bt)?q(P,U):W(P,U,"0");else if(E=tr(new Y(E),_,x),D=E.e,P=g(E.c),T=P.length,L==1||L==2&&(_<=D||D<=ft)){for(;T<_;P+="0",T++);P=q(P,D)}else if(_-=U,P=W(P,D,"0"),D+1>T){if(--_>0)for(P+=".";_--;P+="0");}else if(_+=D-T,_>0)for(D+1==T&&(P+=".");_--;P+="0");return E.s<0&&B?"-"+P:P}function Do(E,_){for(var x,L=1,B=new Y(E[0]);L=10;B/=10,L++);return(x=L+x*c-1)>$e?E.c=E.e=null:x=10;T/=10,B++);if(D=_-B,D<0)D+=c,U=_,P=S[k=0],m=P/R[B-U-1]%10|0;else if(k=n((D+1)/c),k>=S.length)if(L){for(;S.length<=k;S.push(0));P=m=0,B=1,D%=c,U=D-c+1}else break e;else{for(P=T=S[k],B=1;T>=10;T/=10,B++);D%=c,U=D-c+B,m=U<0?0:P/R[B-U-1]%10|0}if(L=L||_<0||S[k+1]!=null||(U<0?P:P%R[B-U-1]),L=x<4?(m||L)&&(x==0||x==(E.s<0?3:2)):m>5||m==5&&(x==4||L||x==6&&(D>0?U>0?P/R[B-U]:0:S[k-1])%10&1||x==(E.s<0?8:7)),_<1||!S[0])return S.length=0,L?(_-=E.e+1,S[0]=R[(c-_%c)%c],E.e=-_||0):S[0]=E.e=0,E;if(D==0?(S.length=k,T=1,k--):(S.length=k+1,T=R[c-D],S[k]=U>0?i(P/R[B-U]%R[U])*T:0),L)for(;;)if(k==0){for(D=1,U=S[0];U>=10;U/=10,D++);for(U=S[0]+=T,T=1;U>=10;U/=10,T++);D!=T&&(E.e++,S[0]==a&&(S[0]=1));break}else{if(S[k]+=T,S[k]!=a)break;S[k--]=0,T=1}for(D=S.length;S[--D]===0;S.pop());}E.e>$e?E.c=E.e=null:E.e=bt?q(_,x):W(_,x,"0"),E.s<0?"-"+_:_)}return z.absoluteValue=z.abs=function(){var E=new Y(this);return E.s<0&&(E.s=1),E},z.comparedTo=function(E,_){return v(this,new Y(E,_))},z.decimalPlaces=z.dp=function(E,_){var x,L,B,D=this;if(E!=null)return w(E,0,d),_==null?_=be:w(_,0,8),tr(new Y(D),E+D.e+1,_);if(!(x=D.c))return null;if(L=((B=x.length-1)-h(this.e/c))*c,B=x[B])for(;B%10==0;B/=10,L--);return L<0&&(L=0),L},z.dividedBy=z.div=function(E,_){return M(this,new Y(E,_),ye,be)},z.dividedToIntegerBy=z.idiv=function(E,_){return M(this,new Y(E,_),0,1)},z.exponentiatedBy=z.pow=function(E,_){var x,L,B,D,U,T,P,k,m,S=this;if(E=new Y(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+qr(E));if(_!=null&&(_=new Y(_)),T=E.e>14,!S.c||!S.c[0]||S.c[0]==1&&!S.e&&S.c.length==1||!E.c||!E.c[0])return m=new Y(Math.pow(+qr(S),T?2-C(E):+qr(E))),_?m.mod(_):m;if(P=E.s<0,_){if(_.c?!_.c[0]:!_.s)return new Y(NaN);L=!P&&S.isInteger()&&_.isInteger(),L&&(S=S.mod(_))}else{if(E.e>9&&(S.e>0||S.e<-1||(S.e==0?S.c[0]>1||T&&S.c[1]>=24e7:S.c[0]<8e13||T&&S.c[0]<=9999975e7)))return D=S.s<0&&C(E)?-0:0,S.e>-1&&(D=1/D),new Y(P?1/D:D);Ot&&(D=n(Ot/c+2))}for(T?(x=new Y(.5),P&&(E.s=1),k=C(E)):(B=Math.abs(+qr(E)),k=B%2),m=new Y(Ae);;){if(k){if(m=m.times(S),!m.c)break;D?m.c.length>D&&(m.c.length=D):L&&(m=m.mod(_))}if(B){if(B=i(B/2),B===0)break;k=B%2}else if(E=E.times(x),tr(E,E.e+1,1),E.e>14)k=C(E);else{if(B=+qr(E),B===0)break;k=B%2}S=S.times(S),D?S.c&&S.c.length>D&&(S.c.length=D):L&&(S=S.mod(_))}return L?m:(P&&(m=Ae.div(m)),_?m.mod(_):D?tr(m,Ot,be,U):m)},z.integerValue=function(E){var _=new Y(this);return E==null?E=be:w(E,0,8),tr(_,_.e+1,E)},z.isEqualTo=z.eq=function(E,_){return v(this,new Y(E,_))===0},z.isFinite=function(){return!!this.c},z.isGreaterThan=z.gt=function(E,_){return v(this,new Y(E,_))>0},z.isGreaterThanOrEqualTo=z.gte=function(E,_){return(_=v(this,new Y(E,_)))===1||_===0},z.isInteger=function(){return!!this.c&&h(this.e/c)>this.c.length-2},z.isLessThan=z.lt=function(E,_){return v(this,new Y(E,_))<0},z.isLessThanOrEqualTo=z.lte=function(E,_){return(_=v(this,new Y(E,_)))===-1||_===0},z.isNaN=function(){return!this.s},z.isNegative=function(){return this.s<0},z.isPositive=function(){return this.s>0},z.isZero=function(){return!!this.c&&this.c[0]==0},z.minus=function(E,_){var x,L,B,D,U=this,T=U.s;if(E=new Y(E,_),_=E.s,!T||!_)return new Y(NaN);if(T!=_)return E.s=-_,U.plus(E);var P=U.e/c,k=E.e/c,m=U.c,S=E.c;if(!P||!k){if(!m||!S)return m?(E.s=-_,E):new Y(S?U:NaN);if(!m[0]||!S[0])return S[0]?(E.s=-_,E):new Y(m[0]?U:be==3?-0:0)}if(P=h(P),k=h(k),m=m.slice(),T=P-k){for((D=T<0)?(T=-T,B=m):(k=P,B=S),B.reverse(),_=T;_--;B.push(0));B.reverse()}else for(L=(D=(T=m.length)<(_=S.length))?T:_,T=_=0;_0)for(;_--;m[x++]=0);for(_=a-1;L>T;){if(m[--L]=0;){for(x=0,R=he[B]%ce,O=he[B]/ce|0,U=P,D=B+U;D>B;)k=ae[--U]%ce,m=ae[U]/ce|0,T=O*k+m*R,k=R*k+T%ce*ce+H[D]+x,x=(k/ne|0)+(T/ce|0)+O*m,H[D--]=k%ne;H[D]=x}return x?++L:H.splice(0,1),ps(E,H,L)},z.negated=function(){var E=new Y(this);return E.s=-E.s||null,E},z.plus=function(E,_){var x,L=this,B=L.s;if(E=new Y(E,_),_=E.s,!B||!_)return new Y(NaN);if(B!=_)return E.s=-_,L.minus(E);var D=L.e/c,U=E.e/c,T=L.c,P=E.c;if(!D||!U){if(!T||!P)return new Y(B/0);if(!T[0]||!P[0])return P[0]?E:new Y(T[0]?L:B*0)}if(D=h(D),U=h(U),T=T.slice(),B=D-U){for(B>0?(U=D,x=P):(B=-B,x=T),x.reverse();B--;x.push(0));x.reverse()}for(B=T.length,_=P.length,B-_<0&&(x=P,P=T,T=x,_=B),B=0;_;)B=(T[--_]=T[_]+P[_]+B)/a|0,T[_]=a===T[_]?0:T[_]%a;return B&&(T=[B].concat(T),++U),ps(E,T,U)},z.precision=z.sd=function(E,_){var x,L,B,D=this;if(E!=null&&E!==!!E)return w(E,1,d),_==null?_=be:w(_,0,8),tr(new Y(D),E,_);if(!(x=D.c))return null;if(B=x.length-1,L=B*c+1,B=x[B]){for(;B%10==0;B/=10,L--);for(B=x[0];B>=10;B/=10,L++);}return E&&D.e+1>L&&(L=D.e+1),L},z.shiftedBy=function(E){return w(E,-u,u),this.times("1e"+E)},z.squareRoot=z.sqrt=function(){var E,_,x,L,B,D=this,U=D.c,T=D.s,P=D.e,k=ye+4,m=new Y("0.5");if(T!==1||!U||!U[0])return new Y(!T||T<0&&(!U||U[0])?NaN:U?D:1/0);if(T=Math.sqrt(+qr(D)),T==0||T==1/0?(_=g(U),(_.length+P)%2==0&&(_+="0"),T=Math.sqrt(+_),P=h((P+1)/2)-(P<0||P%2),T==1/0?_="5e"+P:(_=T.toExponential(),_=_.slice(0,_.indexOf("e")+1)+P),x=new Y(_)):x=new Y(T+""),x.c[0]){for(P=x.e,T=P+k,T<3&&(T=0);;)if(B=x,x=m.times(B.plus(M(D,B,k,1))),g(B.c).slice(0,T)===(_=g(x.c)).slice(0,T))if(x.e0&&H>0){for(D=H%T||T,m=O.substr(0,D);D0&&(m+=k+O.slice(D)),R&&(m="-"+m)}L=S?m+(x.decimalSeparator||"")+((P=+x.fractionGroupSize)?S.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(x.fractionGroupSeparator||"")):S):m}return(x.prefix||"")+L+(x.suffix||"")},z.toFraction=function(E){var _,x,L,B,D,U,T,P,k,m,S,R,O=this,H=O.c;if(E!=null&&(T=new Y(E),!T.isInteger()&&(T.c||T.s!==1)||T.lt(Ae)))throw Error(s+"Argument "+(T.isInteger()?"out of range: ":"not an integer: ")+qr(T));if(!H)return new Y(O);for(_=new Y(Ae),k=x=new Y(Ae),L=P=new Y(Ae),R=g(H),D=_.e=R.length-O.e-1,_.c[0]=l[(U=D%c)<0?c+U:U],E=!E||T.comparedTo(_)>0?D>0?_:k:T,U=$e,$e=1/0,T=new Y(R),P.c[0]=0;m=M(T,_,0,1),B=x.plus(m.times(L)),B.comparedTo(E)!=1;)x=L,L=B,k=P.plus(m.times(B=k)),P=B,_=T.minus(m.times(B=_)),T=B;return B=M(E.minus(x),L,0,1),P=P.plus(B.times(k)),x=x.plus(B.times(L)),P.s=k.s=O.s,D=D*2,S=M(k,L,D,be).minus(O).abs().comparedTo(M(P,x,D,be).minus(O).abs())<1?[k,L]:[P,x],$e=U,S},z.toNumber=function(){return+qr(this)},z.toPrecision=function(E,_){return E!=null&&w(E,1,d),Oo(this,E,_,2)},z.toString=function(E){var _,x=this,L=x.s,B=x.e;return B===null?L?(_="Infinity",L<0&&(_="-"+_)):_="NaN":(E==null?_=B<=ft||B>=bt?q(g(x.c),B):W(g(x.c),B,"0"):E===10&&Qr?(x=tr(new Y(x),ye+B+1,be),_=W(g(x.c),x.e,"0")):(w(E,2,er.length,"Base"),_=re(W(g(x.c),B,"0"),10,E,L,!0)),L<0&&x.c[0]&&(_="-"+_)),_},z.valueOf=z.toJSON=function(){return qr(this)},z._isBigNumber=!0,F!=null&&Y.set(F),Y}function h(F){var M=F|0;return F>0||F===M?M:M-1}function g(F){for(var M,re,ie=1,z=F.length,Ae=F[0]+"";iebt^re?1:-1;for(be=(ft=z.length)<(bt=Ae.length)?ft:bt,ye=0;yeAe[ye]^re?1:-1;return ft==bt?0:ft>bt^re?1:-1}function w(F,M,re,ie){if(Fre||F!==i(F))throw Error(s+(ie||"Argument")+(typeof F=="number"?Fre?" out of range: ":" not an integer: ":" not a primitive number: ")+String(F))}function C(F){var M=F.c.length-1;return h(F.e/c)==M&&F.c[M]%2!=0}function q(F,M){return(F.length>1?F.charAt(0)+"."+F.slice(1):F)+(M<0?"e":"e+")+M}function W(F,M,re){var ie,z;if(M<0){for(z=re+".";++M;z+=re);F=z+F}else if(ie=F.length,++M>ie){for(z=re,M-=ie;--M;z+=re);F+=z}else M{"use strict";var T6=Math.exp;TS=RS.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let r,n=0,i=0,s=0,o,a={};function c(u,l){return 1-T6(-(u-l)/e)}return a.push=function(l,f){if(o){let d=c(l,o),p=f-r,h=d*p;r=d*f+(1-d)*r,n=(1-d)*(n+p*h),i=Math.sqrt(n),s=r+d*p}else r=f;o=l},a.movingAverage=function(){return r},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return s},a}});var DS=b((cV,OS)=>{"use strict";var{EventEmitter:R6}=rr(),{BigNumber:Vu}=IS(),PS=BS(),B6=_a(),NS=class extends R6{constructor(e,r){super();this._options=r,this._queue=[],this._stats={dataReceived:Vu(0),dataSent:Vu(0)},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this);let n=this._options.movingAverageIntervals;for(let i=0;i{this._updateFrequencyFor(n,r,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,r,n){let i=this._frequencyAccumulators[e]||0;this._frequencyAccumulators[e]=0;let o=i/(r||1)*1e3,a=this._movingAverages[e];a||(a=this._movingAverages[e]={});let c=this._options.movingAverageIntervals;for(let u=0;u{"use strict";var P6=Ys(),{pipe:N6}=fr(),{tap:LS}=Fu(),O6=AS(),{METRICS:D6}=hu(),Ih=DS(),Th=["dataReceived","dataSent"],L6={in:"dataReceived",out:"dataSent"},ju=class{constructor(e){this._options=P6(D6,e),this._globalStats=new Ih(Th,this._options),this._peerStats=new Map,this._protocolStats=new Map,this._oldPeers=O6(this._options.maxOldPeersRetention),this._running=!1,this._onMessage=this._onMessage.bind(this),this._systems=new Map}start(){this._running=!0}stop(){this._running=!1,this._globalStats.stop();for(let e of this._peerStats.values())e.stop();for(let e of this._protocolStats.values())e.stop()}get global(){return this._globalStats}get peers(){return Array.from(this._peerStats.keys())}getComponentMetrics(){return this._systems}updateComponentMetric({system:e="libp2p",component:r,metric:n,value:i}){this._systems.has(e)||this._systems.set(e,new Map);let s=this._systems.get(e);s.has(r)||s.set(r,new Map),s.get(r).set(n,i)}forPeer(e){let r=e.toB58String();return this._peerStats.get(r)||this._oldPeers.get(r)}get protocols(){return Array.from(this._protocolStats.keys())}forProtocol(e){return this._protocolStats.get(e)}onPeerDisconnected(e){let r=e.toB58String(),n=this._peerStats.get(r);n&&(n.stop(),this._peerStats.delete(r),this._oldPeers.set(r,n))}_onMessage({remotePeer:e,protocol:r,direction:n,dataLength:i}){if(!this._running)return;let s=L6[n],o=this.forPeer(e);if(o||(o=new Ih(Th,this._options),this._peerStats.set(e.toB58String(),o)),o.push(s,i),this._globalStats.push(s,i),r){let a=this.forProtocol(r);a||(a=new Ih(Th,this._options),this._protocolStats.set(r,a)),a.push(s,i)}}updatePlaceholder(e,r){if(!this._running)return;let n=this.forPeer(e),i=r.toB58String(),s=this.forPeer(r),o=n;s&&(o=ju.mergeStats(s,o),this._oldPeers.delete(i)),this._peerStats.delete(e.toB58String()),this._peerStats.set(i,o),o.start()}trackStream({stream:e,remotePeer:r,protocol:n}){let i=this,s=e.source;e.source=LS(a=>i._onMessage({remotePeer:r,protocol:n,direction:"in",dataLength:a.length}))(s);let o=e.sink;return e.sink=a=>N6(a,LS(c=>i._onMessage({remotePeer:r,protocol:n,direction:"out",dataLength:c.length})),o),e}static mergeStats(e,r){return e.stop(),r.stop(),e._queue=[...e._queue,...r._queue],e}};kS.exports=ju});var $u=b((lV,KS)=>{"use strict";var US=rs(),MS=uo(),{pipe:k6}=fr(),q6=ge(),{fromString:U6}=(Dt(),Ft),M6=yd(),{source:F6}=xu(),FS=U6(` +`);function Rh(t){return MS.encode.single(new US([t,FS]))}function K6(t,e){t.push(Rh(e))}async function V6(t,e){t.push(e.reduce((r,n)=>r.append(Rh(n)),new US))}async function j6(t,e){let r=1,n={[Symbol.asyncIterator](){return this},next:()=>t.next(r)},i=n;e&&e.signal&&(i=F6(n,e.signal));let s=a=>{r=a},o=await k6(i,MS.decode({onLength:s}),M6);if(o.get(o.length-1)!==FS[0])throw q6(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.shallowSlice(0,-1)}KS.exports={encode:Rh,write:K6,writeAll:V6,read:j6}});var $S=b((fV,jS)=>{"use strict";var VS=Oe(),$6=ge(),bo=$u(),H6=lo(),wo=Object.assign(VS("mss:select"),{error:VS("mss:select:error")});jS.exports=async function(e,r,n,i){r=Array.isArray(r)?[...r]:[r];let{reader:s,writer:o,rest:a,stream:c}=H6(e),u=r.shift();if(!u)throw new Error("At least one protocol must be specified");n?(wo('select: write ["%s", "%s"]',n,u),bo.writeAll(o,[n,u])):(wo('select: write "%s"',u),bo.write(o,u));let l=(await bo.read(s,i)).toString();if(wo('select: read "%s"',l),l===n&&(l=(await bo.read(s,i)).toString(),wo('select: read "%s"',l)),l===u)return a(),{stream:c,protocol:u};for(let f of r){wo('select: write "%s"',f),bo.write(o,f);let d=(await bo.read(s,i)).toString();if(wo('select: read "%s" for "%s"',d,f),d===f)return a(),{stream:c,protocol:f}}throw a(),$6(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}});var Bh=b(HS=>{"use strict";HS.PROTOCOL_ID="/multistream/1.0.0"});var WS=b((hV,GS)=>{"use strict";var zS=Oe(),z6=rs(),_o=$u(),G6=lo(),{PROTOCOL_ID:Ph}=Bh(),Fa=Object.assign(zS("mss:handle"),{error:zS("mss:handle:error")});GS.exports=async function(e,r,n){r=Array.isArray(r)?r:[r];let{writer:i,reader:s,rest:o,stream:a}=G6(e);for(;;){let c=(await _o.read(s,n)).toString();if(Fa('read "%s"',c),c===Ph){Fa('respond with "%s" for "%s"',Ph,c),_o.write(i,Ph);continue}if(r.includes(c))return _o.write(i,c),Fa('respond with "%s" for "%s"',c,c),o(),{stream:a,protocol:c};if(c==="ls"){_o.write(i,new z6(r.map(u=>_o.encode(u)))),Fa('respond with "%s" for %s',r,c);continue}_o.write(i,"na"),Fa('respond with "na" for "%s"',c)}}});var ZS=b((pV,XS)=>{"use strict";var W6=ih(),YS=Oe(),QS=$u(),Y6=lo(),Q6=uo(),{pipe:X6}=fr(),Z6=Object.assign(YS("mss:ls"),{error:YS("mss:ls:error")});XS.exports=async function(e,r){let{reader:n,writer:i,rest:s,stream:o}=Y6(e);Z6('write "ls"'),QS.write(i,"ls"),s();let a=await QS.read(n,r),c=W6([a]),u=[];return await X6(c,Q6.decode(),async f=>{for await(let d of f)u.push(d.shallowSlice(0,-1).toString())}),{stream:o,protocols:u}}});var rx=b(Hu=>{"use strict";var JS=$S(),J6=WS(),ek=ZS(),{PROTOCOL_ID:Nh}=Bh();Hu.PROTOCOL_ID=Nh;var Oh=class{constructor(e){this._stream=e,this._shaken=!1}async _handshake(e){if(this._shaken)return;let{stream:r}=await JS(this._stream,Nh,void 0,e);this._stream=r,this._shaken=!0}},ex=class extends Oh{select(e,r){return JS(this._stream,e,this._shaken?void 0:Nh,r)}async ls(e){await this._handshake(e);let r=await ek(this._stream,e),{stream:n,protocols:i}=r;return this._stream=n,i}};Hu.Dialer=ex;var tx=class extends Oh{handle(e,r){return J6(this._stream,e,r)}};Hu.Listener=tx});var ix=b((gV,nx)=>{"use strict";var tk={OPEN:"open",CLOSING:"closing",CLOSED:"closed"};nx.exports=tk});var lx=b((mV,ux)=>{"use strict";var sx=qt(),{Multiaddr:rk}=$t(),hr=ge(),{OPEN:nk,CLOSING:ox,CLOSED:Dh}=ix(),ax=Symbol.for("@libp2p/interface-connection/connection"),cx=class{constructor({localAddr:e,remoteAddr:r,localPeer:n,remotePeer:i,newStream:s,close:o,getStreams:a,stat:c}){ik(e,n,i,s,o,a,c),this.id=parseInt(String(Math.random()*1e9)).toString(36)+Date.now(),this.localAddr=e,this.remoteAddr=r,this.localPeer=n,this.remotePeer=i,this._stat={...c,status:nk},this._newStream=s,this._close=o,this._getStreams=a,this.registry=new Map,this.tags=[]}get[Symbol.toStringTag](){return"Connection"}get[ax](){return!0}static isConnection(e){return Boolean(e&&e[ax])}get stat(){return this._stat}get streams(){return this._getStreams()}async newStream(e){if(this.stat.status===ox)throw hr(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Dh)throw hr(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let{stream:r,protocol:n}=await this._newStream(e);return this.addStream(r,{protocol:n}),{stream:r,protocol:n}}addStream(e,{protocol:r,metadata:n={}}){this.registry.set(e.id,{protocol:r,...n})}removeStream(e){this.registry.delete(e)}async close(){if(this.stat.status!==Dh){if(this._closing)return this._closing;this.stat.status=ox,this._closing=await this._close(),this._stat.timeline.close=Date.now(),this.stat.status=Dh}}};ux.exports=cx;function ik(t,e,r,n,i,s,o){if(t&&!rk.isMultiaddr(t))throw hr(new Error("localAddr must be an instance of multiaddr"),"ERR_INVALID_PARAMETERS");if(!sx.isPeerId(e))throw hr(new Error("localPeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(!sx.isPeerId(r))throw hr(new Error("remotePeer must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");if(typeof n!="function")throw hr(new Error("new stream must be a function"),"ERR_INVALID_PARAMETERS");if(typeof i!="function")throw hr(new Error("close must be a function"),"ERR_INVALID_PARAMETERS");if(typeof s!="function")throw hr(new Error("getStreams must be a function"),"ERR_INVALID_PARAMETERS");if(!o)throw hr(new Error("connection metadata object must be provided"),"ERR_INVALID_PARAMETERS");if(o.direction!=="inbound"&&o.direction!=="outbound")throw hr(new Error('direction must be "inbound" or "outbound"'),"ERR_INVALID_PARAMETERS");if(!o.timeline)throw hr(new Error("connection timeline object must be provided in the stat object"),"ERR_INVALID_PARAMETERS");if(!o.timeline.open)throw hr(new Error("connection open timestamp must be provided"),"ERR_INVALID_PARAMETERS");if(!o.timeline.upgraded)throw hr(new Error("connection upgraded timestamp must be provided"),"ERR_INVALID_PARAMETERS")}});var dx=b(fx=>{"use strict";fx.Connection=lx()});var px=b((EV,hx)=>{"use strict";function sk(t){if(Array.isArray(t)){for(var e=0,r=Array(t.length);e{"use strict";var yx=Oe(),xt=Object.assign(yx("libp2p:upgrader"),{error:yx("libp2p:upgrader:err")}),pr=ge(),So=rx(),{Connection:ok}=dx(),ak=qt(),{pipe:ck}=fr(),gx=px(),{codes:yr}=Ye(),mx=class{constructor({localPeer:e,metrics:r,connectionGater:n,cryptos:i=new Map,muxers:s=new Map,onConnectionEnd:o=()=>{},onConnection:a=()=>{}}){this.connectionGater=n,this.localPeer=e,this.metrics=r,this.cryptos=i,this.muxers=s,this.protector=null,this.protocols=new Map,this.onConnection=a,this.onConnectionEnd=o}async upgradeInbound(e){let r,n,i,s,o,a,c;if(await this.connectionGater.denyInboundConnection(e))throw pr(new Error("The multiaddr connection is blocked by gater.acceptConnection"),yr.ERR_CONNECTION_INTERCEPTED);if(this.metrics){({setTarget:a,proxy:c}=gx());let l=(Math.random()*1e9).toString(36)+Date.now();a({toB58String:()=>l}),e=this.metrics.trackStream({stream:e,remotePeer:c})}xt("Starting the inbound connection upgrade");let u=e;this.protector&&(u=await this.protector.protect(e));try{if({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(this.localPeer,u,this.cryptos),await this.connectionGater.denyInboundEncryptedConnection(n,r))throw pr(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),yr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:i,Muxer:s}=await this._multiplexInbound(r,this.muxers):i=r}catch(l){throw xt.error("Failed to upgrade inbound connection",l),await e.close(l),l}if(await this.connectionGater.denyInboundUpgradedConnection(n,r))throw pr(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),yr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(c,n),a(n)),xt("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:o,direction:"inbound",maConn:e,upgradedConn:i,Muxer:s,remotePeer:n})}async upgradeOutbound(e){let r=e.remoteAddr.getPeerId();if(!r)throw pr(new Error("outbound connection must have a peer id"),yr.ERR_INVALID_MULTIADDR);let n=ak.createFromB58String(r);if(await this.connectionGater.denyOutboundConnection(n,e))throw pr(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),yr.ERR_CONNECTION_INTERCEPTED);let i,s,o,a,c,u,l;if(this.metrics){({setTarget:u,proxy:l}=gx());let d=(Math.random()*1e9).toString(36)+Date.now();u({toB58String:()=>d}),e=this.metrics.trackStream({stream:e,remotePeer:l})}xt("Starting the outbound connection upgrade");let f=e;this.protector&&(f=await this.protector.protect(e));try{if({conn:i,remotePeer:s,protocol:a}=await this._encryptOutbound(this.localPeer,f,n,this.cryptos),await this.connectionGater.denyOutboundEncryptedConnection(s,i))throw pr(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),yr.ERR_CONNECTION_INTERCEPTED);this.muxers.size?{stream:o,Muxer:c}=await this._multiplexOutbound(i,this.muxers):o=i}catch(d){throw xt.error("Failed to upgrade outbound connection",d),await e.close(d),d}if(await this.connectionGater.denyOutboundUpgradedConnection(s,i))throw pr(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),yr.ERR_CONNECTION_INTERCEPTED);return this.metrics&&(this.metrics.updatePlaceholder(l,s),u(s)),xt("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:o,Muxer:c,remotePeer:s})}_createConnection({cryptoProtocol:e,direction:r,maConn:n,upgradedConn:i,Muxer:s,remotePeer:o}){let a,c,u;s&&(a=new s({onStream:async d=>{if(!u)return;let p=new So.Listener(d);try{let{stream:h,protocol:g}=await p.handle(Array.from(this.protocols.keys()));xt("%s: incoming stream opened on %s",r,g),this.metrics&&this.metrics.trackStream({stream:h,remotePeer:o,protocol:g}),u.addStream(d,{protocol:g}),this._onStream({connection:u,stream:{...d,...h},protocol:g})}catch(h){xt.error(h)}},onStreamEnd:d=>{u.removeStream(d.id)}}),c=async d=>{xt("%s: starting new stream on %s",r,d);let p=a.newStream(),h=new So.Dialer(p);try{let{stream:g,protocol:v}=await h.select(d);return this.metrics&&this.metrics.trackStream({stream:g,remotePeer:o,protocol:v}),{stream:{...p,...g},protocol:v}}catch(g){throw xt.error("could not create new stream",g),pr(g,yr.ERR_UNSUPPORTED_PROTOCOL)}},ck(i,a,i).catch(xt.error));let l=n.timeline;n.timeline=new Proxy(l,{set:(...d)=>(u&&d[1]==="close"&&d[2]&&!l.close&&(async()=>{try{u.stat.status==="open"&&await u.close()}catch(p){xt.error(p)}finally{this.onConnectionEnd(u)}})().catch(p=>{xt.error(p)}),Reflect.set(...d))}),n.timeline.upgraded=Date.now();let f=()=>{throw pr(new Error("connection is not multiplexed"),yr.ERR_CONNECTION_NOT_MULTIPLEXED)};return u=new ok({localAddr:n.localAddr,remoteAddr:n.remoteAddr,localPeer:this.localPeer,remotePeer:o,stat:{direction:r,timeline:n.timeline,multiplexer:s&&s.multicodec,encryption:e},newStream:c||f,getStreams:()=>a?a.streams:f(),close:async()=>{await n.close(),a&&a.streams.map(d=>d.abort())}}),this.onConnection(u),u}_onStream({connection:e,stream:r,protocol:n}){this.protocols.get(n)({connection:e,stream:r,protocol:n})}async _encryptInbound(e,r,n){let i=new So.Listener(r),s=Array.from(n.keys());xt("handling inbound crypto protocol selection",s);try{let{stream:o,protocol:a}=await i.handle(s),c=n.get(a);if(xt("encrypting inbound connection..."),!c)throw new Error(`no crypto module found for ${a}`);return{...await c.secureInbound(e,o),protocol:a}}catch(o){throw pr(o,yr.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r,n,i){let s=new So.Dialer(r),o=Array.from(i.keys());xt("selecting outbound crypto protocol",o);try{let{stream:a,protocol:c}=await s.select(o),u=i.get(c);if(xt("encrypting outbound connection to %j",n),!u)throw new Error(`no crypto module found for ${c}`);return{...await u.secureOutbound(e,a,n),protocol:c}}catch(a){throw pr(a,yr.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=new So.Dialer(e),i=Array.from(r.keys());xt("outbound selecting muxer %s",i);try{let{stream:s,protocol:o}=await n.select(i);xt("%s selected as muxer protocol",o);let a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw pr(s,yr.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=new So.Listener(e),i=Array.from(r.keys());xt("inbound handling muxers %s",i);try{let{stream:s,protocol:o}=await n.handle(i),a=r.get(o);return{stream:s,Muxer:a}}catch(s){throw pr(s,yr.ERR_MUXER_UNAVAILABLE)}}};vx.exports=mx});var wx=b((wV,bx)=>{"use strict";var uk=async function*(t,e){for await(let r of t)await e(r),yield r};bx.exports=uk});var Tx=b((_V,Ix)=>{"use strict";var _x=Oe(),us=ge(),{Multiaddr:Sx}=$t(),zu=qt(),{codes:Gr}=Ye(),xx=Eu(),Ax=mu(),{pipe:lk}=fr(),fk=Vi(),dk=ji(),hk=ad(),pk=wx(),je=Object.assign(_x("libp2p:peer-store:address-book"),{error:_x("libp2p:peer-store:address-book:err")}),Gu="change:multiaddrs",Cx=class{constructor(e,r,n){this._emit=e,this._store=r,this._addressFilter=n}async consumePeerRecord(e){je("consumePeerRecord await write lock");let r=await this._store.lock.writeLock();je("consumePeerRecord got write lock");let n,i;try{let s;try{s=xx.createFromProtobuf(e.payload)}catch(a){return je.error("invalid peer record received"),!1}n=s.peerId;let o=s.multiaddrs;if(!n.equals(e.peerId))return je("signing key does not match PeerId in the PeerRecord"),!1;if(!o||!o.length)return!1;if(await this._store.has(n)){let a=await this._store.load(n);if(a.peerRecordEnvelope){let c=await Ax.createFromProtobuf(a.peerRecordEnvelope);if(xx.createFromProtobuf(c.payload).seqNumber>=s.seqNumber)return!1}}i=await this._store.patchOrCreate(n,{addresses:await Lh(n,o,this._addressFilter,!0),peerRecordEnvelope:e.marshal()}),je(`stored provided peer record for ${s.peerId.toB58String()}`)}finally{je("consumePeerRecord release write lock"),r()}return this._emit(Gu,{peerId:n,multiaddrs:i.addresses.map(({multiaddr:s})=>s)}),!0}async getRawEnvelope(e){je("getRawEnvelope await read lock");let r=await this._store.lock.readLock();je("getRawEnvelope got read lock");try{return(await this._store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==Gr.ERR_NOT_FOUND)throw n}finally{je("getRawEnvelope release read lock"),r()}}async getPeerRecord(e){let r=await this.getRawEnvelope(e);if(!!r)return Ax.createFromProtobuf(r)}async get(e){if(!zu.isPeerId(e))throw je.error("peerId must be an instance of peer-id to store data"),us(new Error("peerId must be an instance of peer-id"),Gr.ERR_INVALID_PARAMETERS);je("get wait for read lock");let r=await this._store.lock.readLock();je("get got read lock");try{return(await this._store.load(e)).addresses}catch(n){if(n.code!==Gr.ERR_NOT_FOUND)throw n}finally{je("get release read lock"),r()}return[]}async set(e,r){if(!zu.isPeerId(e))throw je.error("peerId must be an instance of peer-id to store data"),us(new Error("peerId must be an instance of peer-id"),Gr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw je.error("multiaddrs must be an array of Multiaddrs"),us(new Error("multiaddrs must be an array of Multiaddrs"),Gr.ERR_INVALID_PARAMETERS);je("set await write lock");let n=await this._store.lock.writeLock();je("set got write lock");let i=!1,s;try{let o=await Lh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length&&o.length===a.addresses.length)return}catch(a){if(a.code!==Gr.ERR_NOT_FOUND)throw a}s=await this._store.patchOrCreate(e,{addresses:o}),je(`set multiaddrs for ${e.toB58String()}`)}finally{je("set release write lock"),n()}this._emit(Gu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async add(e,r){if(!zu.isPeerId(e))throw je.error("peerId must be an instance of peer-id to store data"),us(new Error("peerId must be an instance of peer-id"),Gr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw je.error("multiaddrs must be an array of Multiaddrs"),us(new Error("multiaddrs must be an array of Multiaddrs"),Gr.ERR_INVALID_PARAMETERS);je("add await write lock");let n=await this._store.lock.writeLock();je("add got write lock");let i,s;try{let o=await Lh(e,r,this._addressFilter);if(!o.length)return;try{let a=await this._store.load(e);if(i=!0,new Set([...o.map(({multiaddr:c})=>c.toString()),...a.addresses.map(({multiaddr:c})=>c.toString())]).size===a.addresses.length)return}catch(a){if(a.code!==Gr.ERR_NOT_FOUND)throw a}s=await this._store.mergeOrCreate(e,{addresses:o}),je(`added multiaddrs for ${e.toB58String()}`)}finally{je("set release write lock"),n()}this._emit(Gu,{peerId:e,multiaddrs:s.addresses.map(o=>o.multiaddr)}),i||this._emit("peer",e)}async delete(e){if(!zu.isPeerId(e))throw je.error("peerId must be an instance of peer-id to store data"),us(new Error("peerId must be an instance of peer-id"),Gr.ERR_INVALID_PARAMETERS);je("delete await write lock");let r=await this._store.lock.writeLock();je("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{addresses:[]})}finally{je("delete release write lock"),r()}n&&this._emit(Gu,{peerId:e,multiaddrs:[]})}async getMultiaddrsForPeer(e,r=n=>n){let n=await this.get(e);return r(n).map(i=>{let s=i.multiaddr,o=s.getPeerId();return o&&o===e.toB58String()?s:s.encapsulate(`/p2p/${e.toB58String()}`)})}};function Lh(t,e,r,n=!1){return lk(e,i=>pk(i,s=>{if(!Sx.isMultiaddr(s))throw je.error("multiaddr must be an instance of Multiaddr"),us(new Error("multiaddr must be an instance of Multiaddr"),Gr.ERR_INVALID_PARAMETERS)}),i=>dk(i,s=>r(t,s)),i=>hk(i,s=>({multiaddr:new Sx(s.toString()),isCertified:n})),i=>fk(i))}Ix.exports=Cx});var Ox=b((SV,Nx)=>{"use strict";var Rx=Oe(),Wu=ge(),{codes:xo}=Ye(),kh=qt(),{equals:yk}=(Sr(),_r),gr=Object.assign(Rx("libp2p:peer-store:key-book"),{error:Rx("libp2p:peer-store:key-book:err")}),Bx="change:pubkey",Px=class{constructor(e,r){this._emit=e,this._store=r}async set(e,r){if(!kh.isPeerId(e))throw gr.error("peerId must be an instance of peer-id to store data"),Wu(new Error("peerId must be an instance of peer-id"),xo.ERR_INVALID_PARAMETERS);if(!r)throw gr.error("publicKey must be an instance of PublicKey to store data"),Wu(new Error("publicKey must be an instance of PublicKey"),xo.ERR_INVALID_PARAMETERS);gr("set await write lock");let n=await this._store.lock.writeLock();gr("set got write lock");let i=!1;try{try{let s=await this._store.load(e);if(s.pubKey&&yk(s.pubKey.bytes,r.bytes))return}catch(s){if(s.code!==xo.ERR_NOT_FOUND)throw s}await this._store.patchOrCreate(e,{pubKey:r}),i=!0}finally{gr("set release write lock"),n()}i&&this._emit(Bx,{peerId:e,pubKey:r})}async get(e){if(!kh.isPeerId(e))throw gr.error("peerId must be an instance of peer-id to store data"),Wu(new Error("peerId must be an instance of peer-id"),xo.ERR_INVALID_PARAMETERS);gr("get await write lock");let r=await this._store.lock.readLock();gr("get got write lock");try{return(await this._store.load(e)).pubKey}catch(n){if(n.code!==xo.ERR_NOT_FOUND)throw n}finally{gr("get release write lock"),r()}}async delete(e){if(!kh.isPeerId(e))throw gr.error("peerId must be an instance of peer-id to store data"),Wu(new Error("peerId must be an instance of peer-id"),xo.ERR_INVALID_PARAMETERS);gr("delete await write lock");let r=await this._store.lock.writeLock();gr("delete got write lock");try{await this._store.patchOrCreate(e,{pubKey:void 0})}finally{gr("delete release write lock"),r()}this._emit(Bx,{peerId:e,pubKey:void 0})}};Nx.exports=Px});var qx=b((xV,kx)=>{"use strict";var Dx=Oe(),bi=ge(),{codes:Dr}=Ye(),Ao=qt(),{equals:gk}=(Sr(),_r),Je=Object.assign(Dx("libp2p:peer-store:metadata-book"),{error:Dx("libp2p:peer-store:metadata-book:err")}),Yu="change:metadata",Lx=class{constructor(e,r){this._emit=e,this._store=r}async get(e){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);Je("get await read lock");let r=await this._store.lock.readLock();Je("get got read lock");try{return(await this._store.load(e)).metadata}catch(n){if(n.code!==Dr.ERR_NOT_FOUND)throw n}finally{Je("get release read lock"),r()}return new Map}async getValue(e,r){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);Je("getValue await read lock");let n=await this._store.lock.readLock();Je("getValue got read lock");try{return(await this._store.load(e)).metadata.get(r)}catch(i){if(i.code!==Dr.ERR_NOT_FOUND)throw i}finally{Je("getValue release write lock"),n()}}async set(e,r){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);if(!r||!(r instanceof Map))throw Je.error("valid metadata must be provided to store data"),bi(new Error("valid metadata must be provided"),Dr.ERR_INVALID_PARAMETERS);Je("set await write lock");let n=await this._store.lock.writeLock();Je("set got write lock");try{await this._store.mergeOrCreate(e,{metadata:r})}finally{Je("set release write lock"),n()}this._emit(Yu,{peerId:e,metadata:r})}async setValue(e,r,n){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);if(typeof r!="string"||!(n instanceof Uint8Array))throw Je.error("valid key and value must be provided to store data"),bi(new Error("valid key and value must be provided"),Dr.ERR_INVALID_PARAMETERS);Je("setValue await write lock");let i=await this._store.lock.writeLock();Je("setValue got write lock");let s;try{try{let a=(await this._store.load(e)).metadata.get(r);if(a!=null&&gk(n,a))return}catch(o){if(o.code!==Dr.ERR_NOT_FOUND)throw o}s=await this._store.mergeOrCreate(e,{metadata:new Map([[r,n]])})}finally{Je("setValue release write lock"),i()}this._emit(Yu,{peerId:e,metadata:s.metadata})}async delete(e){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);Je("delete await write lock");let r=await this._store.lock.writeLock();Je("delete got write lock");let n;try{n=await this._store.has(e),n&&await this._store.patch(e,{metadata:new Map})}finally{Je("delete release write lock"),r()}n&&this._emit(Yu,{peerId:e,metadata:new Map})}async deleteValue(e,r){if(!Ao.isPeerId(e))throw Je.error("peerId must be an instance of peer-id to store data"),bi(new Error("peerId must be an instance of peer-id"),Dr.ERR_INVALID_PARAMETERS);Je("deleteValue await write lock");let n=await this._store.lock.writeLock();Je("deleteValue got write lock");let i;try{i=(await this._store.load(e)).metadata,i.delete(r),await this._store.patch(e,{metadata:i})}catch(s){if(s.code!==Dr.ERR_NOT_FOUND)throw s}finally{Je("deleteValue release write lock"),n()}i&&this._emit(Yu,{peerId:e,metadata:i})}};kx.exports=Lx});var Kx=b((AV,Fx)=>{"use strict";var Ux=Oe(),Co=ge(),{codes:Wr}=Ye(),qh=qt(),ht=Object.assign(Ux("libp2p:peer-store:proto-book"),{error:Ux("libp2p:peer-store:proto-book:err")}),Qu="change:protocols",Mx=class{constructor(e,r){this._emit=e,this._store=r}async get(e){ht("get wait for read lock");let r=await this._store.lock.readLock();ht("get got read lock");try{return(await this._store.load(e)).protocols}catch(n){if(n.code!==Wr.ERR_NOT_FOUND)throw n}finally{ht("get release read lock"),r()}return[]}async set(e,r){if(!qh.isPeerId(e))throw ht.error("peerId must be an instance of peer-id to store data"),Co(new Error("peerId must be an instance of peer-id"),Wr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ht.error("protocols must be provided to store data"),Co(new Error("protocols must be provided"),Wr.ERR_INVALID_PARAMETERS);ht("set await write lock");let n=await this._store.lock.writeLock();ht("set got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...r]).size===s.protocols.length)return}catch(s){if(s.code!==Wr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r}),ht(`stored provided protocols for ${e.toB58String()}`)}finally{ht("set release write lock"),n()}this._emit(Qu,{peerId:e,protocols:i.protocols})}async add(e,r){if(!qh.isPeerId(e))throw ht.error("peerId must be an instance of peer-id to store data"),Co(new Error("peerId must be an instance of peer-id"),Wr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ht.error("protocols must be provided to store data"),Co(new Error("protocols must be provided"),Wr.ERR_INVALID_PARAMETERS);ht("add await write lock");let n=await this._store.lock.writeLock();ht("add got write lock");let i;try{try{let s=await this._store.load(e);if(new Set([...s.protocols,...r]).size===s.protocols.length)return}catch(s){if(s.code!==Wr.ERR_NOT_FOUND)throw s}i=await this._store.mergeOrCreate(e,{protocols:r}),ht(`added provided protocols for ${e.toB58String()}`)}finally{ht("add release write lock"),n()}this._emit(Qu,{peerId:e,protocols:i.protocols})}async remove(e,r){if(!qh.isPeerId(e))throw ht.error("peerId must be an instance of peer-id to store data"),Co(new Error("peerId must be an instance of peer-id"),Wr.ERR_INVALID_PARAMETERS);if(!Array.isArray(r))throw ht.error("protocols must be provided to store data"),Co(new Error("protocols must be provided"),Wr.ERR_INVALID_PARAMETERS);ht("remove await write lock");let n=await this._store.lock.writeLock();ht("remove got write lock");let i;try{try{let s=await this._store.load(e),o=new Set(s.protocols);for(let a of r)o.delete(a);if(s.protocols.length===o.size)return;r=Array.from(o)}catch(s){if(s.code!==Wr.ERR_NOT_FOUND)throw s}i=await this._store.patchOrCreate(e,{protocols:r})}finally{ht("remove release write lock"),n()}this._emit(Qu,{peerId:e,protocols:i.protocols})}async delete(e){ht("delete await write lock");let r=await this._store.lock.writeLock();ht("delete got write lock");let n;try{n=await this._store.has(e),await this._store.patchOrCreate(e,{protocols:[]})}catch(i){if(i.code!==Wr.ERR_NOT_FOUND)throw i}finally{ht("delete release write lock"),r()}n&&this._emit(Qu,{peerId:e,protocols:[]})}};Fx.exports=Mx});var jx=b((CV,Vx)=>{"use strict";var wi=Sn(),Io=wi.Reader,Uh=wi.Writer,He=wi.util,Et=wi.roots["libp2p-peer"]||(wi.roots["libp2p-peer"]={});Et.Peer=function(){function t(r){if(this.addresses=[],this.protocols=[],this.metadata=[],r)for(var n=Object.keys(r),i=0;i>>3){case 1:o.addresses&&o.addresses.length||(o.addresses=[]),o.addresses.push(Et.Address.decode(n,n.uint32()));break;case 2:o.protocols&&o.protocols.length||(o.protocols=[]),o.protocols.push(n.string());break;case 3:o.metadata&&o.metadata.length||(o.metadata=[]),o.metadata.push(Et.Metadata.decode(n,n.uint32()));break;case 4:o.pubKey=n.bytes();break;case 5:o.peerRecordEnvelope=n.bytes();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof Et.Peer)return n;var i=new Et.Peer;if(n.addresses){if(!Array.isArray(n.addresses))throw TypeError(".Peer.addresses: array expected");i.addresses=[];for(var s=0;s>>3){case 1:o.multiaddr=n.bytes();break;case 2:o.isCertified=n.bool();break;default:n.skipType(a&7);break}}return o},t.fromObject=function(n){if(n instanceof Et.Address)return n;var i=new Et.Address;return n.multiaddr!=null&&(typeof n.multiaddr=="string"?He.base64.decode(n.multiaddr,i.multiaddr=He.newBuffer(He.base64.length(n.multiaddr)),0):n.multiaddr.length&&(i.multiaddr=n.multiaddr)),n.isCertified!=null&&(i.isCertified=Boolean(n.isCertified)),i},t.toObject=function(n,i){i||(i={});var s={};return i.defaults&&(i.bytes===String?s.multiaddr="":(s.multiaddr=[],i.bytes!==Array&&(s.multiaddr=He.newBuffer(s.multiaddr)))),n.multiaddr!=null&&n.hasOwnProperty("multiaddr")&&(s.multiaddr=i.bytes===String?He.base64.encode(n.multiaddr,0,n.multiaddr.length):i.bytes===Array?Array.prototype.slice.call(n.multiaddr):n.multiaddr),n.isCertified!=null&&n.hasOwnProperty("isCertified")&&(s.isCertified=n.isCertified,i.oneofs&&(s._isCertified="isCertified")),s},t.prototype.toJSON=function(){return this.constructor.toObject(this,wi.util.toJSONOptions)},t}();Et.Metadata=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.key=r.string();break;case 2:s.value=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof Et.Metadata)return r;var n=new Et.Metadata;return r.key!=null&&(n.key=String(r.key)),r.value!=null&&(typeof r.value=="string"?He.base64.decode(r.value,n.value=He.newBuffer(He.base64.length(r.value)),0):r.value.length&&(n.value=r.value)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.key="",n.bytes===String?i.value="":(i.value=[],n.bytes!==Array&&(i.value=He.newBuffer(i.value)))),r.key!=null&&r.hasOwnProperty("key")&&(i.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(i.value=n.bytes===String?He.base64.encode(r.value,0,r.value.length):n.bytes===Array?Array.prototype.slice.call(r.value):r.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,wi.util.toJSONOptions)},t}();Vx.exports=Et});var Mh=b((IV,$x)=>{$x.exports={WORKER_REQUEST_READ_LOCK:"lock:worker:request-read",WORKER_RELEASE_READ_LOCK:"lock:worker:release-read",MASTER_GRANT_READ_LOCK:"lock:master:grant-read",WORKER_REQUEST_WRITE_LOCK:"lock:worker:request-write",WORKER_RELEASE_WRITE_LOCK:"lock:worker:release-write",MASTER_GRANT_WRITE_LOCK:"lock:master:grant-write"}});var Hx=b(()=>{});var tA=b((BV,eA)=>{var mk=rr().EventEmitter,{nanoid:vk}=(ru(),id),{WORKER_REQUEST_READ_LOCK:zx,WORKER_RELEASE_READ_LOCK:Gx,MASTER_GRANT_READ_LOCK:Wx,WORKER_REQUEST_WRITE_LOCK:Yx,WORKER_RELEASE_WRITE_LOCK:Qx,MASTER_GRANT_WRITE_LOCK:Xx}=Mh(),Ka,Zx=(t,e,r,n,i)=>(s,o)=>{o&&o.type===r&&t.emit(e,o.name,()=>(s.send({type:i,name:o.name,identifier:o.identifier}),new Promise(a=>{let c=u=>{u&&u.type===n&&u.identifier===o.identifier&&(s.removeListener("message",c),a())};s.on("message",c)})))},Jx=(t,e,r,n)=>()=>{let i=vk();return process.send({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{a&&a.type===r&&a.identifier===i&&(process.removeListener("message",o),s(()=>{process.send({type:n,identifier:i,name:t})}))};process.on("message",o)})};eA.exports=t=>{try{if(Ka=Hx(),!Object.keys(Ka).length)return}catch(e){return}if(Ka.isMaster||t.singleProcess){let e=new mk;return Ka.on("message",Zx(e,"requestReadLock",zx,Gx,Wx)),Ka.on("message",Zx(e,"requestWriteLock",Yx,Qx,Xx)),e}return{isWorker:!0,readLock:e=>Jx(e,zx,Wx,Gx),writeLock:e=>Jx(e,Yx,Xx,Qx)}}});var Fh=b((PV,rA)=>{var _i={},To=t=>{t.addEventListener("message",e=>{To.dispatchEvent("message",t,e)}),t.port&&t.port.addEventListener("message",e=>{To.dispatchEvent("message",t,e)})};To.addEventListener=(t,e)=>{_i[t]||(_i[t]=[]),_i[t].push(e)};To.removeEventListener=(t,e)=>{!_i[t]||(_i[t]=_i[t].filter(r=>r===e))};To.dispatchEvent=function(){let t=Array.prototype.slice.call(arguments),e=t.shift();!_i[e]||_i[e].forEach(r=>r.apply(null,t))};rA.exports=To});var hA=b((NV,dA)=>{var Ek=rr().EventEmitter,{nanoid:bk}=(ru(),id),{WORKER_REQUEST_READ_LOCK:nA,WORKER_RELEASE_READ_LOCK:iA,MASTER_GRANT_READ_LOCK:sA,WORKER_REQUEST_WRITE_LOCK:oA,WORKER_RELEASE_WRITE_LOCK:aA,MASTER_GRANT_WRITE_LOCK:cA}=Mh(),uA=Fh(),lA=(t,e,r,n,i)=>(s,o)=>{if(!o||!o.data||o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.emit(e,a.name,()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),new Promise(c=>{let u=l=>{if(!l||!l.data)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f&&f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})))},fA=(t,e,r,n)=>()=>{let i=bk();return globalThis.postMessage({type:e,identifier:i,name:t}),new Promise(s=>{let o=a=>{if(!a||!a.data)return;let c={type:a.data.type,identifier:a.data.identifier};c&&c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},wk={singleProcess:!1};dA.exports=t=>{if(t=Object.assign({},wk,t),!!globalThis.document||t.singleProcess){let r=new Ek;return uA.addEventListener("message",lA(r,"requestReadLock",nA,iA,sA)),uA.addEventListener("message",lA(r,"requestWriteLock",oA,aA,cA)),r}return{isWorker:!0,readLock:r=>fA(r,nA,sA,iA),writeLock:r=>fA(r,oA,cA,aA)}}});var yA=b((OV,Kh)=>{"use strict";var _k=Object.prototype.hasOwnProperty,Zt="~";function Va(){}Object.create&&(Va.prototype=Object.create(null),new Va().__proto__||(Zt=!1));function Sk(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function pA(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new Sk(r,n||t,i),o=Zt?Zt+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}function Xu(t,e){--t._eventsCount==0?t._events=new Va:delete t._events[e]}function zt(){this._events=new Va,this._eventsCount=0}zt.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)_k.call(r,n)&&e.push(Zt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};zt.prototype.listeners=function(e){var r=Zt?Zt+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i{"use strict";gA.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var EA=b((LV,Zu)=>{"use strict";var xk=mA(),Vh=class extends Error{constructor(e){super(e);this.name="TimeoutError"}},vA=(t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,a=r instanceof Error?r:new Vh(o);typeof t.cancel=="function"&&t.cancel(),i(a)},e);xk(t.then(n,i),()=>{clearTimeout(s)})});Zu.exports=vA;Zu.exports.default=vA;Zu.exports.TimeoutError=Vh});var bA=b(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});function Ak(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}jh.default=Ak});var _A=b($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var Ck=bA(),wA=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=Ck.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};$h.default=wA});var AA=b(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Ik=yA(),SA=EA(),Tk=_A(),Ju=()=>{},Rk=new SA.TimeoutError,xA=class extends Ik{constructor(e){var r,n,i,s;super();if(this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Ju,this._resolveIdle=Ju,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Tk.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():SA.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(Rk)});n(await o)}catch(o){i(o)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Hh.default=xA});var CA=b((FV,zh)=>{"use strict";var el,MV=zh.exports.timeout=function(t,e){var r=new el,n;return Promise.race([t,new Promise(function(i,s){n=setTimeout(function(){s(r)},e)})]).then(function(i){return clearTimeout(n),i},function(i){throw clearTimeout(n),i})};el=zh.exports.TimeoutError=function(){Error.call(this),this.stack=Error().stack,this.message="Timeout"};el.prototype=Object.create(Error.prototype);el.prototype.name="TimeoutError"});var TA=b((KV,Wh)=>{var Bk=tA(),Pk=hA(),{default:IA}=AA(),{timeout:Nk}=CA(),Ok=Fh(),ls={},Si;function Gh(t,e){let r,n=new Promise(i=>{r=i});return t.add(()=>Nk((()=>new Promise(i=>{r(()=>{i()})}))(),e.timeout)),n}var Dk=(t,e)=>{if(Si.isWorker)return{readLock:Si.readLock(t,e),writeLock:Si.writeLock(t,e)};let r=new IA({concurrency:1}),n=null;return{readLock:()=>{if(n)return Gh(n,e);n=new IA({concurrency:e.concurrency,autoStart:!1});let i=n,s=Gh(n,e);return r.add(()=>(i.start(),i.onIdle().then(()=>{n===i&&(n=null)}))),s},writeLock:()=>(n=null,Gh(r,e))}},Lk={concurrency:1/0,timeout:846e5,global:globalThis,singleProcess:!1};Wh.exports=(t,e)=>(e||(e={}),typeof t=="object"&&(e=t,t="lock"),t||(t="lock"),e=Object.assign({},Lk,e),Si||(Si=Bk(e)||Pk(e),Si.isWorker||(Si.on("requestReadLock",(r,n)=>{!ls[r]||ls[r].readLock().then(i=>n().finally(()=>i()))}),Si.on("requestWriteLock",async(r,n)=>{!ls[r]||ls[r].writeLock().then(i=>n().finally(()=>i()))}))),ls[t]||(ls[t]=Dk(t,e)),ls[t]);Wh.exports.Worker=function(t,e){e=e||globalThis.Worker;let r;try{r=new e(t)}catch(n){n.message.includes("not a constructor")&&(r=e(t))}if(!r)throw new Error("Could not create Worker from",e);return Ok(r),r}});var UA=b((VV,qA)=>{"use strict";var RA=Oe(),BA=qt(),PA=ge(),{codes:tl}=Ye(),{Key:kk}=(iu(),sd),{base32:qk}=(Ii(),Ci),{keys:{unmarshalPublicKey:Uk,marshalPublicKey:Mk}}=Lu(),{Multiaddr:NA}=$t(),{Peer:OA}=jx(),Fk=TA(),{equals:Kk}=(Sr(),_r),DA=Object.assign(RA("libp2p:peer-store:store"),{error:RA("libp2p:peer-store:store:err")}),LA="/peers/",kA=class{constructor(e){this._datastore=e,this.lock=Fk("peer-store",{singleProcess:!0})}_peerIdToDatastoreKey(e){if(!BA.isPeerId(e))throw DA.error("peerId must be an instance of peer-id to store data"),PA(new Error("peerId must be an instance of peer-id"),tl.ERR_INVALID_PARAMETERS);let r=e.toString();return new kk(`${LA}${r}`)}async has(e){return this._datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this._datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let r=await this._datastore.get(this._peerIdToDatastoreKey(e)),n=OA.decode(r),i=n.pubKey?Uk(n.pubKey):e.pubKey,s=new Map;for(let o of n.metadata)s.set(o.key,o.value);return{...n,id:e,pubKey:i,addresses:n.addresses.map(({multiaddr:o,isCertified:a})=>({multiaddr:new NA(o),isCertified:a||!1})),metadata:s,peerRecordEnvelope:n.peerRecordEnvelope||void 0}}async save(e){if(e.pubKey!=null&&e.id.pubKey!=null&&!Kk(e.pubKey.bytes,e.id.pubKey.bytes))throw DA.error("peer publicKey bytes do not match peer id publicKey bytes"),PA(new Error("publicKey bytes do not match peer id publicKey bytes"),tl.ERR_INVALID_PARAMETERS);let r=new Set,n=OA.encode({addresses:e.addresses.filter(i=>r.has(i.multiaddr.toString())?!1:(r.add(i.multiaddr.toString()),!0)).sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({multiaddr:i,isCertified:s})=>({multiaddr:i.bytes,isCertified:s})),protocols:e.protocols.sort(),pubKey:e.pubKey?Mk(e.pubKey):void 0,metadata:[...e.metadata.keys()].sort().map(i=>({key:i,value:e.metadata.get(i)})),peerRecordEnvelope:e.peerRecordEnvelope}).finish();return await this._datastore.put(this._peerIdToDatastoreKey(e.id),n),this.load(e.id)}async patch(e,r){let n=await this.load(e);return await this._patch(e,r,n)}async patchOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==tl.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,r,n)}async _patch(e,r,n){return await this.save({...n,...r,id:e})}async merge(e,r){let n=await this.load(e);return this._merge(e,r,n)}async mergeOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==tl.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,r,n)}async _merge(e,r,n){let i=new Map;return(r.addresses||[]).forEach(s=>{i.set(s.multiaddr.toString(),s.isCertified)}),n.addresses.forEach(({multiaddr:s,isCertified:o})=>{let a=s.toString();i.set(a,Boolean(i.get(a)||o))}),await this.save({id:e,addresses:Array.from(i.entries()).map(([s,o])=>({multiaddr:new NA(s),isCertified:o})),protocols:Array.from(new Set([...n.protocols||[],...r.protocols||[]])),metadata:new Map([...n.metadata?n.metadata.entries():[],...r.metadata?r.metadata.entries():[]]),pubKey:r.pubKey||(n!=null?n.pubKey:void 0),peerRecordEnvelope:r.peerRecordEnvelope||(n!=null?n.peerRecordEnvelope:void 0)})}async*all(){for await(let e of this._datastore.queryKeys({prefix:LA})){let r=e.toString().split("/")[2],n=qk.decode(r);yield this.load(BA.createFromBytes(n))}}};qA.exports=kA});var VA=b((jV,KA)=>{"use strict";var MA=Oe(),{EventEmitter:Vk}=rr(),jk=Tx(),$k=Ox(),Hk=qx(),zk=Kx(),Gk=UA(),Lr=Object.assign(MA("libp2p:peer-store"),{error:MA("libp2p:peer-store:err")}),FA=class extends Vk{constructor({peerId:e,datastore:r,addressFilter:n}){super();this._peerId=e,this._store=new Gk(r),this.addressBook=new jk(this.emit.bind(this),this._store,n),this.keyBook=new $k(this.emit.bind(this),this._store),this.metadataBook=new Hk(this.emit.bind(this),this._store),this.protoBook=new zk(this.emit.bind(this),this._store)}async*getPeers(){Lr("getPeers await read lock");let e=await this._store.lock.readLock();Lr("getPeers got read lock");try{for await(let r of this._store.all())r.id.toB58String()!==this._peerId.toB58String()&&(yield r)}finally{Lr("getPeers release read lock"),e()}}async delete(e){Lr("delete await write lock");let r=await this._store.lock.writeLock();Lr("delete got write lock");try{await this._store.delete(e)}finally{Lr("delete release write lock"),r()}}async get(e){Lr("get await read lock");let r=await this._store.lock.readLock();Lr("get got read lock");try{return this._store.load(e)}finally{Lr("get release read lock"),r()}}async has(e){Lr("has await read lock");let r=await this._store.lock.readLock();Lr("has got read lock");try{return this._store.has(e)}finally{Lr("has release read lock"),r()}}};KA.exports=FA});var $A=b(($V,jA)=>{"use strict";function Wk(t,e,r){let n=new t(e,r);n._subscribeAdapter=n.subscribe,n._unsubscribeAdapter=n.unsubscribe;function i(o,a){a&&n.on(o,a),n._subscribeAdapter(o)}function s(o,a){a?n.removeListener(o,a):n.removeAllListeners(o),n.listenerCount(o)===0&&n._unsubscribeAdapter(o)}return n.subscribe=i,n.unsubscribe=s,n}jA.exports=Wk});var YA=b((HV,WA)=>{"use strict";var HA=()=>{},zA=Symbol.for("@libp2p/js-interfaces/topology"),GA=class{constructor({min:e=0,max:r=1/0,handlers:n={}}){this.min=e,this.max=r,this._onConnect=n.onConnect||HA,this._onDisconnect=n.onDisconnect||HA,this.peers=new Set}get[Symbol.toStringTag](){return"Topology"}get[zA](){return!0}static isTopology(e){return Boolean(e&&e[zA])}async setRegistrar(e){this._registrar=e}disconnect(e){this._onDisconnect(e)}};WA.exports=GA});var JA=b((zV,ZA)=>{"use strict";var QA=Oe(),Yk=Object.assign(QA("libp2p:registrar"),{error:QA("libp2p:registrar:err")}),Qk=ge(),{codes:{ERR_INVALID_PARAMETERS:Xk}}=Ye(),Zk=YA(),XA=class{constructor({peerStore:e,connectionManager:r}){this.peerStore=e,this.connectionManager=r,this.topologies=new Map,this._handle=void 0,this._onDisconnect=this._onDisconnect.bind(this),this.connectionManager.on("peer:disconnect",this._onDisconnect)}get handle(){return this._handle}set handle(e){this._handle=e}getConnection(e){return this.connectionManager.get(e)}async register(e){if(!Zk.isTopology(e))throw Yk.error("topology must be an instance of interfaces/topology"),Qk(new Error("topology must be an instance of interfaces/topology"),Xk);let r=(Math.random()*1e9).toString(36)+Date.now();return this.topologies.set(r,e),await e.setRegistrar(this),r}unregister(e){return this.topologies.delete(e)}_onDisconnect(e){for(let[,r]of this.topologies)r.disconnect(e.remotePeer)}};ZA.exports=XA});var Yh=b((GV,ja)=>{"use strict";var{Buffer:rl}=pi(),nl=rs();ja.exports=async function*(t){for await(let e of t)rl.isBuffer(e)?yield e:nl.isBufferList(e)?yield e.slice():yield rl.from(e)};ja.exports.toBuffer=ja.exports;ja.exports.toList=async function*(t){for await(let e of t)rl.isBuffer(e)?yield new nl().append(e):nl.isBufferList(e)?yield e:yield new nl().append(rl.from(e))}});var rC=b((WV,tC)=>{"use strict";var Ro=Sn(),eC=Ro.Reader,Jk=Ro.Writer,lt=Ro.util,$a=Ro.roots["libp2p-identify"]||(Ro.roots["libp2p-identify"]={});$a.Identify=function(){function t(e){if(this.listenAddrs=[],this.protocols=[],e)for(var r=Object.keys(e),n=0;n>>3){case 5:s.protocolVersion=r.string();break;case 6:s.agentVersion=r.string();break;case 1:s.publicKey=r.bytes();break;case 2:s.listenAddrs&&s.listenAddrs.length||(s.listenAddrs=[]),s.listenAddrs.push(r.bytes());break;case 4:s.observedAddr=r.bytes();break;case 3:s.protocols&&s.protocols.length||(s.protocols=[]),s.protocols.push(r.string());break;case 8:s.signedPeerRecord=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof $a.Identify)return r;var n=new $a.Identify;if(r.protocolVersion!=null&&(n.protocolVersion=String(r.protocolVersion)),r.agentVersion!=null&&(n.agentVersion=String(r.agentVersion)),r.publicKey!=null&&(typeof r.publicKey=="string"?lt.base64.decode(r.publicKey,n.publicKey=lt.newBuffer(lt.base64.length(r.publicKey)),0):r.publicKey.length&&(n.publicKey=r.publicKey)),r.listenAddrs){if(!Array.isArray(r.listenAddrs))throw TypeError(".Identify.listenAddrs: array expected");n.listenAddrs=[];for(var i=0;i{"use strict";var nC=Oe(),mr=Object.assign(nC("libp2p:identify"),{error:nC("libp2p:identify:err")}),Qh=ge(),il=uo(),{pipe:sl}=fr(),{collect:iC,take:sC,consume:oC}=Fu(),{fromString:Bo}=(Dt(),Ft),e5=qt(),{Multiaddr:Xh}=$t(),{toBuffer:aC}=Yh(),Ha=rC(),cC=mu(),uC=Eu(),{MULTICODEC_IDENTIFY:t5,MULTICODEC_IDENTIFY_PUSH:r5,IDENTIFY_PROTOCOL_VERSION:n5,MULTICODEC_IDENTIFY_PROTOCOL_NAME:i5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME:s5,MULTICODEC_IDENTIFY_PROTOCOL_VERSION:o5,MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION:a5}=wd(),{codes:Zh}=Ye(),fs=class{static getProtocolStr(e){return{identifyProtocolStr:`/${e._config.protocolPrefix}/${i5}/${o5}`,identifyPushProtocolStr:`/${e._config.protocolPrefix}/${s5}/${a5}`}}constructor({libp2p:e}){this._libp2p=e,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.handleMessage=this.handleMessage.bind(this);let r=fs.getProtocolStr(e);this.identifyProtocolStr=r.identifyProtocolStr,this.identifyPushProtocolStr=r.identifyPushProtocolStr,this._host={protocolVersion:`${e._config.protocolPrefix}/${n5}`,...e._options.host},this.connectionManager.on("peer:connect",n=>{this.identify(n).catch(mr.error)}),this.peerStore.on("change:multiaddrs",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>mr.error(i))}),this.peerStore.on("change:protocols",({peerId:n})=>{n.toString()===this.peerId.toString()&&this.pushToPeerStore().catch(i=>mr.error(i))})}async start(){await this.peerStore.metadataBook.setValue(this.peerId,"AgentVersion",Bo(this._host.agentVersion)),await this.peerStore.metadataBook.setValue(this.peerId,"ProtocolVersion",Bo(this._host.protocolVersion))}async stop(){}async push(e){let r=await this.peerStore.addressBook.getRawEnvelope(this.peerId),n=this._libp2p.multiaddrs.map(o=>o.bytes),i=await this.peerStore.protoBook.get(this.peerId),s=e.map(async o=>{try{let{stream:a}=await o.newStream(this.identifyPushProtocolStr);await sl([Ha.Identify.encode({listenAddrs:n,signedPeerRecord:r,protocols:i}).finish()],il.encode(),a,oC)}catch(a){mr.error("could not push identify update to peer",a)}});return Promise.all(s)}async pushToPeerStore(){if(!this._libp2p.isStarted())return;let e=[],r;for await(let n of this.peerStore.getPeers())n.protocols.includes(this.identifyPushProtocolStr)&&(r=this.connectionManager.get(n.id))&&e.push(r);await this.push(e)}async identify(e){let{stream:r}=await e.newStream(this.identifyProtocolStr),[n]=await sl([],r,il.decode(),sC(1),aC,iC);if(!n)throw Qh(new Error("No data could be retrieved"),Zh.ERR_CONNECTION_ENDED);let i;try{i=Ha.Identify.decode(n)}catch(d){throw Qh(d,Zh.ERR_INVALID_MESSAGE)}let{publicKey:s,listenAddrs:o,protocols:a,observedAddr:c,signedPeerRecord:u}=i,l=await e5.createFromPubKey(s);if(e.remotePeer.toB58String()!==l.toB58String())throw Qh(new Error("identified peer does not match the expected peer"),Zh.ERR_INVALID_PEER);let f=fs.getCleanMultiaddr(c);try{let d=await cC.openAndCertify(u,uC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(d)){await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Bo(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Bo(i.protocolVersion));return}}catch(d){mr("received invalid envelope, discard it and fallback to listenAddrs is available",d)}try{await this.peerStore.addressBook.set(l,o.map(d=>new Xh(d)))}catch(d){mr.error("received invalid addrs",d)}await this.peerStore.protoBook.set(l,a),await this.peerStore.metadataBook.setValue(l,"AgentVersion",Bo(i.agentVersion)),await this.peerStore.metadataBook.setValue(l,"ProtocolVersion",Bo(i.protocolVersion)),mr("received observed address of %s",f)}handleMessage({connection:e,stream:r,protocol:n}){switch(n){case this.identifyProtocolStr:return this._handleIdentify({connection:e,stream:r});case this.identifyPushProtocolStr:return this._handlePush({connection:e,stream:r});default:mr.error("cannot handle unknown protocol %s",n)}}async _handleIdentify({connection:e,stream:r}){try{let n=new Uint8Array(0);this.peerId.pubKey&&(n=this.peerId.pubKey.bytes);let i=await this.peerStore.addressBook.getRawEnvelope(this.peerId),s=await this.peerStore.protoBook.get(this.peerId),o=Ha.Identify.encode({protocolVersion:this._host.protocolVersion,agentVersion:this._host.agentVersion,publicKey:n,listenAddrs:this._libp2p.multiaddrs.map(a=>a.bytes),signedPeerRecord:i,observedAddr:e.remoteAddr.bytes,protocols:s}).finish();await sl([o],il.encode(),r,oC)}catch(n){mr.error("could not respond to identify request",n)}}async _handlePush({connection:e,stream:r}){let n;try{let[s]=await sl([],r,il.decode(),sC(1),aC,iC);n=Ha.Identify.decode(s)}catch(s){return mr.error("received invalid message",s)}let i=e.remotePeer;try{let s=await cC.openAndCertify(n.signedPeerRecord,uC.DOMAIN);if(await this.peerStore.addressBook.consumePeerRecord(s)){await this.peerStore.protoBook.set(i,n.protocols);return}}catch(s){mr("received invalid envelope, discard it and fallback to listenAddrs is available",s)}try{await this.peerStore.addressBook.set(i,n.listenAddrs.map(s=>new Xh(s)))}catch(s){mr.error("received invalid addrs",s)}try{await this.peerStore.protoBook.set(i,n.protocols)}catch(s){mr.error("received invalid protocols",s)}}static getCleanMultiaddr(e){if(e&&e.length>0)try{return new Xh(e)}catch(r){return null}return null}},c5={IDENTIFY:t5,IDENTIFY_PUSH:r5};fs.multicodecs=c5;fs.Messsage=Ha;lC.exports=fs});var pC=b((QV,hC)=>{"use strict";var ds=Sn(),ol=ds.Reader,dC=ds.Writer,Po=ds.util,bn=ds.roots["libp2p-fetch"]||(ds.roots["libp2p-fetch"]={});bn.FetchRequest=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.identifier=r.string();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof bn.FetchRequest)return r;var n=new bn.FetchRequest;return r.identifier!=null&&(n.identifier=String(r.identifier)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.identifier=""),r.identifier!=null&&r.hasOwnProperty("identifier")&&(i.identifier=r.identifier),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,ds.util.toJSONOptions)},t}();bn.FetchResponse=function(){function t(e){if(e)for(var r=Object.keys(e),n=0;n>>3){case 1:s.status=r.int32();break;case 2:s.data=r.bytes();break;default:r.skipType(o&7);break}}return s},t.fromObject=function(r){if(r instanceof bn.FetchResponse)return r;var n=new bn.FetchResponse;switch(r.status){case"OK":case 0:n.status=0;break;case"NOT_FOUND":case 1:n.status=1;break;case"ERROR":case 2:n.status=2;break}return r.data!=null&&(typeof r.data=="string"?Po.base64.decode(r.data,n.data=Po.newBuffer(Po.base64.length(r.data)),0):r.data.length&&(n.data=r.data)),n},t.toObject=function(r,n){n||(n={});var i={};return n.defaults&&(i.status=n.enums===String?"OK":0,n.bytes===String?i.data="":(i.data=[],n.bytes!==Array&&(i.data=Po.newBuffer(i.data)))),r.status!=null&&r.hasOwnProperty("status")&&(i.status=n.enums===String?bn.FetchResponse.StatusCode[r.status]:r.status),r.data!=null&&r.hasOwnProperty("data")&&(i.data=n.bytes===String?Po.base64.encode(r.data,0,r.data.length):n.bytes===Array?Array.prototype.slice.call(r.data):r.data),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,ds.util.toJSONOptions)},t.StatusCode=function(){var e={},r=Object.create(e);return r[e[0]="OK"]=0,r[e[1]="NOT_FOUND"]=1,r[e[2]="ERROR"]=2,r}(),t}();hC.exports=bn});var gC=b((XV,yC)=>{"use strict";yC.exports={PROTOCOL:"/libp2p/fetch/0.0.1"}});var wC=b((EC,bC)=>{"use strict";var mC=Oe(),u5=Object.assign(mC("libp2p:fetch"),{error:mC("libp2p:fetch:err")}),Jh=ge(),{codes:e0}=Ye(),al=uo(),{FetchRequest:t0,FetchResponse:Yr}=pC(),vC=lo(),{PROTOCOL:l5}=gC(),za=class{constructor(e){this._lookupFunctions=new Map,this._libp2p=e,this.handleMessage=this.handleMessage.bind(this)}async fetch(e,r){u5("dialing %s to %s",this._protocol,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(za.PROTOCOL),s=vC(i),o=new t0({identifier:r});s.write(al.encode.single(t0.encode(o).finish()));let a=Yr.decode((await al.decode.fromReader(s.reader).next()).value.slice());switch(a.status){case Yr.StatusCode.OK:return a.data;case Yr.StatusCode.NOT_FOUND:return null;case Yr.StatusCode.ERROR:{let c=new TextDecoder().decode(a.data);throw Jh(new Error("Error in fetch protocol response: "+c),e0.ERR_INVALID_PARAMETERS)}default:throw Jh(new Error("Unknown response status"),e0.ERR_INVALID_MESSAGE)}}async handleMessage(e){let{stream:r}=e,n=vC(r),i=t0.decode((await al.decode.fromReader(n.reader).next()).value.slice()),s,o=this._getLookupFunction(i.identifier);if(o){let a=await o(i.identifier);a?s=new Yr({status:Yr.StatusCode.OK,data:a}):s=new Yr({status:Yr.StatusCode.NOT_FOUND})}else{let a=new TextEncoder().encode("No lookup function registered for key: "+i.identifier);s=new Yr({status:Yr.StatusCode.ERROR,data:a})}n.write(al.encode.single(Yr.encode(s).finish()))}_getLookupFunction(e){for(let r of this._lookupFunctions.keys())if(e.startsWith(r))return this._lookupFunctions.get(r);return null}registerLookupFunction(e,r){if(this._lookupFunctions.has(e))throw Jh(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),e0.ERR_KEY_ALREADY_EXISTS);this._lookupFunctions.set(e,r)}unregisterLookupFunction(e,r){r!=null&&this._lookupFunctions.get(e)!==r||this._lookupFunctions.delete(e)}};za.PROTOCOL=l5;EC=bC.exports=za});var SC=b((ZV,_C)=>{"use strict";_C.exports={PROTOCOL:"/ipfs/ping/1.0.0",PING_LENGTH:32,PROTOCOL_VERSION:"1.0.0",PROTOCOL_NAME:"ping"}});var BC=b((JV,RC)=>{"use strict";var xC=Oe(),f5=Object.assign(xC("libp2p:ping"),{error:xC("libp2p:ping:err")}),d5=ge(),{codes:h5}=Ye(),p5=Lu(),{pipe:AC}=fr(),{toBuffer:y5}=Yh(),{collect:g5,take:m5}=Fu(),{equals:v5}=(Sr(),_r),{PROTOCOL_NAME:CC,PING_LENGTH:E5,PROTOCOL_VERSION:IC}=SC(),TC=class{static getProtocolStr(e){return`/${e._config.protocolPrefix}/${CC}/${IC}`}constructor(e){this._libp2p=e}handleMessage({stream:e}){return AC(e,e)}async ping(e){let r=`/${this._libp2p._config.protocolPrefix}/${CC}/${IC}`;f5("dialing %s to %s",r,e.toB58String?e.toB58String():e);let n=await this._libp2p.dial(e),{stream:i}=await n.newStream(r),s=Date.now(),o=p5.randomBytes(E5),[a]=await AC([o],i,u=>m5(1,u),y5,g5),c=Date.now();if(!v5(o,a))throw d5(new Error("Received wrong ping ack"),h5.ERR_WRONG_PING_ACK);return c-s}};RC.exports=TC});var PC=b(()=>{});var NC=b(r0=>{"use strict";Object.defineProperty(r0,"__esModule",{value:!0}),r0.promisify=cl;var b5="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__";function cl(t){if(typeof t!="function")throw new TypeError("Argument to promisify must be a function");var e=t[b5],r=cl.Promise||Promise;if(typeof r!="function")throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,i=arguments.length,s=Array(i),o=0;o{function w5(){return typeof window!="undefined"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process!="undefined"&&typeof process.versions=="object"&&!!process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0}OC.exports=w5});var kC=b((i9,LC)=>{"use strict";var _5=DC(),ul=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Ga=_5(),S5=ul&&!Ga,x5=Ga&&!ul,A5=Ga&&ul,C5=typeof d0=="function"&&typeof globalThis.process!="undefined"&&typeof globalThis.process.release!="undefined"&&globalThis.process.release.name==="node"&&!Ga,I5=typeof importScripts=="function"&&typeof self!="undefined"&&typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope,T5=typeof globalThis.process!="undefined"&&typeof globalThis.process.env!="undefined"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",R5=typeof navigator!="undefined"&&navigator.product==="ReactNative";LC.exports={isTest:T5,isElectron:Ga,isElectronMain:x5,isElectronRenderer:A5,isNode:C5,isBrowser:S5,isWebWorker:I5,isEnvWithDom:ul,isReactNative:R5}});var UC=b((s9,qC)=>{function kr(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}qC.exports=kr;kr.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};kr.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};kr.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};kr.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};kr.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};kr.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};kr.prototype.start=kr.prototype.try;kr.prototype.errors=function(){return this._errors};kr.prototype.attempts=function(){return this._attempts};kr.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,r=0,n=0;n=r&&(e=i,r=o)}return e}});var MC=b(hs=>{var B5=UC();hs.operation=function(t){var e=hs.timeouts(t);return new B5(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};hs.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i{FC.exports=MC()});var jC=b((c9,ll)=>{"use strict";var P5=KC(),N5=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],n0=class extends Error{constructor(e){super();e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},O5=(t,e,r)=>{let n=r.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=n,t},D5=t=>N5.includes(t),VC=(t,e)=>new Promise((r,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=P5.operation(e);i.attempt(async s=>{try{r(await t(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof n0)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!D5(o.message))i.stop(),n(o);else{O5(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}})});ll.exports=VC;ll.exports.default=VC;ll.exports.AbortError=n0});var HC=b((u9,$C)=>{"use strict";function L5(t){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^::1$/.test(t)}$C.exports=L5});var GC=b((l9,zC)=>{"use strict";var k5=HC();function q5(t){let{address:e}=t.nodeAddress();return k5(e)}zC.exports=q5});var JC=b((f9,ZC)=>{"use strict";var U5=PC(),WC=Oe(),{promisify:i0}=NC(),{Multiaddr:M5}=$t(),No=Object.assign(WC("libp2p:nat"),{error:WC("libp2p:nat:err")}),{isBrowser:YC}=kC(),s0=jC(),F5=_d(),QC=bd(),K5=ge(),{codes:{ERR_INVALID_PARAMETERS:V5}}=Ye(),j5=GC(),o0=7200;function $5(t=1024,e=65535){return Math.floor(Math.random()*(e-t+1)+t)}var XC=class{constructor({peerId:e,addressManager:r,transportManager:n,...i}){if(this._peerId=e,this._addressManager=r,this._transportManager=n,this._enabled=i.enabled,this._externalIp=i.externalIp,this._options={description:i.description||`${QC.name}@${QC.version} ${this._peerId}`,ttl:i.ttl||o0,autoUpdate:i.keepAlive||!0,gateway:i.gateway,enablePMP:Boolean(i.pmp&&i.pmp.enabled)},this._options.ttl{No.error(e)})}async _start(){let e=this._transportManager.getAddrs();for(let r of e){let{family:n,host:i,port:s,transport:o}=r.toOptions();if(!r.isThinWaistAddress()||o!=="tcp"||j5(r)||n!==4)continue;let a=this._getClient(),c=this._externalIp||await a.externalIp();if(F5(c))throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);let u=$5();No(`opening uPnP connection from ${c}:${u} to ${i}:${s}`),await a.map({publicPort:u,privatePort:s,protocol:o.toUpperCase()}),this._addressManager.addObservedAddr(M5.fromNodeAddress({family:4,address:c,port:u},o))}}_getClient(){if(this._client)return this._client;let e=new U5(this._options),r=i0(e.map.bind(e)),n=i0(e.destroy.bind(e)),i=i0(e.externalIp.bind(e));return this._client={map:(...s)=>s0(()=>r(...s),{onFailedAttempt:No.error,unref:!0}),destroy:(...s)=>s0(()=>n(...s),{onFailedAttempt:No.error,unref:!0}),externalIp:(...s)=>s0(()=>i(...s),{onFailedAttempt:No.error,unref:!0})},this._client}async stop(){if(!(YC||!this._client))try{await this._client.destroy(),this._client=null}catch(e){No.error(e)}}};ZC.exports=XC});var dq=b((d9,iI)=>{"use strict";var eI=Oe(),Gt=Object.assign(eI("libp2p"),{error:eI("libp2p:err")}),{EventEmitter:H5}=rr(),a0=ge(),z5=qt(),{Multiaddr:G5}=$t(),{MemoryDatastore:W5}=(v1(),m1),Y5=W1(),Q5=eE(),c0=md(),{validate:X5}=mb(),{codes:fl,messages:Z5}=Ye(),J5=bb(),eq=qb(),tq=$b(),tI=B2(),rq=V2(),nq=w_(),rI=bS(),iq=qS(),sq=Pd(),oq=Ex(),aq=VA(),cq=$A(),uq=JA(),nI=fC(),u0=wC(),l0=BC(),lq=JC(),{updateSelfPeerRecord:fq}=Rd(),Wa=class extends H5{static async create(e){if(e.peerId)return new Wa(e);let r=await z5.create();return e.peerId=r,new Wa(e)}constructor(e){super();if(this._options=X5(e),this.peerId=this._options.peerId,this.datastore=this._options.datastore,this._options.metrics.enabled){let n=new iq({...this._options.metrics});this.metrics=n}if(this.connectionGater={denyDialPeer:async()=>Promise.resolve(!1),denyDialMultiaddr:async()=>Promise.resolve(!1),denyInboundConnection:async()=>Promise.resolve(!1),denyOutboundConnection:async()=>Promise.resolve(!1),denyInboundEncryptedConnection:async()=>Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>Promise.resolve(!1),denyInboundUpgradedConnection:async()=>Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>Promise.resolve(!1),filterMultiaddrForPeer:async()=>Promise.resolve(!0),...this._options.connectionGater},this.peerStore=new aq({peerId:this.peerId,datastore:this.datastore&&this._options.peerStore.persistence?this.datastore:new W5,addressFilter:this.connectionGater.filterMultiaddrForPeer}),this.addresses=this._options.addresses,this.addressManager=new J5(this.peerId,this._options.addresses),this.addressManager.on("change:addresses",()=>{fq(this).catch(n=>{Gt.error("Error updating self peer record",n)})}),this._modules=this._options.modules,this._config=this._options.config,this._transport=[],this._discovery=new Map,this.connectionManager=new eq(this,{...this._options.connectionManager}),this._autodialler=new tq(this,{enabled:this._config.peerDiscovery.autoDial,minConnections:this._options.connectionManager.minConnections,autoDialInterval:this._options.connectionManager.autoDialInterval}),this._options.keychain&&this._options.keychain.datastore){Gt("creating keychain");let n=rI.generateOptions();this.keychain=new rI(this._options.keychain.datastore,{...n,...this._options.keychain}),Gt("keychain constructed")}if(this.upgrader=new oq({connectionGater:this.connectionGater,localPeer:this.peerId,metrics:this.metrics,onConnection:n=>this.connectionManager.onConnect(n),onConnectionEnd:n=>this.connectionManager.onDisconnect(n)}),this.transportManager=new sq({libp2p:this,upgrader:this.upgrader,faultTolerance:this._options.transportManager.faultTolerance}),this.natManager=new lq({peerId:this.peerId,addressManager:this.addressManager,transportManager:this.transportManager,...this._options.config.nat}),this.registrar=new uq({peerStore:this.peerStore,connectionManager:this.connectionManager}),this.handle=this.handle.bind(this),this.registrar.handle=this.handle,!this._modules.connEncryption||!this._modules.connEncryption.length)throw a0(new Error(Z5.CONN_ENCRYPTION_REQUIRED),fl.CONN_ENCRYPTION_REQUIRED);if(this._modules.connEncryption.forEach(n=>{this.upgrader.cryptos.set(n.protocol,n)}),this.dialer=new nq({transportManager:this.transportManager,connectionGater:this.connectionGater,peerStore:this.peerStore,metrics:this.metrics,...this._options.dialer}),this._modules.transport.forEach(n=>{let i=n.prototype[Symbol.toStringTag],s=this._config.transport[i];this.transportManager.add(i,n,s)}),this._config.relay.enabled&&(this.transportManager.add(tI.prototype[Symbol.toStringTag],tI),this.relay=new rq(this)),this._modules.streamMuxer&&(this._modules.streamMuxer.forEach(i=>{this.upgrader.muxers.set(i.multicodec,i)}),this.identifyService=new nI({libp2p:this})),this._modules.connProtector)this.upgrader.protector=this._modules.connProtector;else if(globalThis.process!==void 0&&globalThis.process.env&&globalThis.process.env.LIBP2P_FORCE_PNET)throw new Error("Private network is enforced, but no protector was provided");if(this._modules.dht){let n=this._modules.dht;this._dht=n.create({libp2p:this,...this._config.dht})}if(this._modules.pubsub){let n=this._modules.pubsub;this.pubsub=cq(n,this,this._config.pubsub)}this.peerRouting=new Y5(this),this.contentRouting=new Q5(this),this._onDiscoveryPeer=this._onDiscoveryPeer.bind(this),this.fetchService=new u0(this),this.pingService=new l0(this)}emit(e,...r){return e==="error"&&!this._events.error?(Gt.error(r),!1):super.emit(e,...r)}async start(){Gt("libp2p is starting"),this.identifyService&&await this.handle(Object.values(nI.getProtocolStr(this)),this.identifyService.handleMessage),this.fetchService&&await this.handle(u0.PROTOCOL,this.fetchService.handleMessage),this.pingService&&await this.handle(l0.getProtocolStr(this),this.pingService.handleMessage);try{await this._onStarting(),await this._onDidStart(),Gt("libp2p has started")}catch(e){throw this.emit("error",e),Gt.error("An error occurred starting libp2p",e),await this.stop(),e}}async stop(){Gt("libp2p is stopping");try{this._isStarted=!1,this.identifyService&&await this.identifyService.stop(),this.relay&&this.relay.stop(),this.peerRouting.stop(),await this._autodialler.stop(),await(this._dht&&this._dht.stop());for(let e of this._discovery.values())e.removeListener("peer",this._onDiscoveryPeer);await Promise.all(Array.from(this._discovery.values(),e=>e.stop())),this._discovery=new Map,await this.connectionManager.stop(),await Promise.all([this.pubsub&&this.pubsub.stop(),this.metrics&&this.metrics.stop()]),await this.natManager.stop(),await this.transportManager.close(),await this.unhandle(u0.PROTOCOL),await this.unhandle(l0.getProtocolStr(this)),this.dialer.destroy()}catch(e){e&&(Gt.error(e),this.emit("error",e))}Gt("libp2p has stopped")}async loadKeychain(){if(!!this.keychain)try{await this.keychain.findKeyByName("self")}catch(e){await this.keychain.importPeer("self",this.peerId)}}isStarted(){return this._isStarted}get connections(){return this.connectionManager.connections}dial(e,r){return this._dial(e,r)}async dialProtocol(e,r,n){if(!r||!r.length)throw a0(new Error("no protocols were provided to open a stream"),fl.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this._dial(e,n)).newStream(r)}async _dial(e,r){let{id:n,multiaddrs:i}=c0(e);if(n.equals(this.peerId))throw a0(new Error("Cannot dial self"),fl.ERR_DIALED_SELF);let s=this.connectionManager.get(n);return s?i&&await this.peerStore.addressBook.add(n,i):s=await this.dialer.connectToPeer(e,r),s}get multiaddrs(){let e=this.addressManager.getAnnounceAddrs().map(i=>i.toString());e.length||(e=this.transportManager.getAddrs().map(i=>i.toString())),e=e.concat(this.addressManager.getObservedAddrs().map(i=>i.toString()));let r=this._options.addresses.announceFilter,n=new Set(e);return r(Array.from(n).map(i=>new G5(i)))}async hangUp(e){let{id:r}=c0(e),n=this.connectionManager.connections.get(r.toB58String());!n||await Promise.all(n.map(i=>i.close()))}fetch(e,r){return this.fetchService.fetch(e,r)}ping(e){let{id:r,multiaddrs:n}=c0(e);return n?this.pingService.ping(n[0]):this.pingService.ping(r)}async handle(e,r){e=Array.isArray(e)?e:[e],e.forEach(n=>{this.upgrader.protocols.set(n,r)}),await this.peerStore.protoBook.add(this.peerId,e)}async unhandle(e){e=Array.isArray(e)?e:[e],e.forEach(r=>{this.upgrader.protocols.delete(r)}),await this.peerStore.protoBook.remove(this.peerId,e)}async _onStarting(){let e=this.addressManager.getListenAddrs();await this.transportManager.listen(e),this.natManager.start(),this._config.pubsub.enabled&&this.pubsub&&await this.pubsub.start(),this._config.dht.enabled&&(this._dht&&await this._dht.start(),this._dht.on("peer",this._onDiscoveryPeer)),this.metrics&&this.metrics.start(),this.identifyService&&await this.identifyService.start()}async _onDidStart(){this._isStarted=!0,this.peerStore.on("peer",e=>{this.emit("peer:discovery",e),this._maybeConnect(e).catch(r=>{Gt.error(r)})});for await(let e of this.peerStore.getPeers())this.emit("peer:discovery",e.id);this.connectionManager.start(),await this._autodialler.start(),await this._setupPeerDiscovery(),this.relay&&this.relay.start(),this.peerRouting.start()}_onDiscoveryPeer(e){if(e.id.toB58String()===this.peerId.toB58String()){Gt.error(new Error(fl.ERR_DISCOVERED_SELF));return}e.multiaddrs&&this.peerStore.addressBook.add(e.id,e.multiaddrs).catch(r=>Gt.error(r)),e.protocols&&this.peerStore.protoBook.set(e.id,e.protocols).catch(r=>Gt.error(r))}async _maybeConnect(e){if(this._config.peerDiscovery.autoDial===!0&&!this.connectionManager.get(e)&&(this._options.connectionManager.minConnections||0)>this.connectionManager.size){Gt("connecting to discovered peer %s",e.toB58String());try{await this.dialer.connectToPeer(e)}catch(n){Gt.error(`could not connect to discovered peer ${e.toB58String()} with ${n}`)}}}async _setupPeerDiscovery(){let e=r=>{let n={enabled:!0};if(r.tag&&this._config.peerDiscovery&&this._config.peerDiscovery[r.tag]&&(n={...n,...this._config.peerDiscovery[r.tag]}),n.enabled&&!this._discovery.has(r.tag)){let i;typeof r=="function"?i=new r(Object.assign({},n,{peerId:this.peerId,libp2p:this})):i=r,i.on("peer",this._onDiscoveryPeer),this._discovery.set(r.tag,i)}};for(let r of this._modules.peerDiscovery||[])e(r);for(let r of this.transportManager.getTransports())r.discovery&&e(r.discovery);await Promise.all(Array.from(this._discovery.values(),r=>r.start()))}};iI.exports=Wa});return dq();})(); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +return Libp2p})); diff --git a/dist/src/address-manager/index.d.ts b/dist/src/address-manager/index.d.ts new file mode 100644 index 0000000000..cc010a2eba --- /dev/null +++ b/dist/src/address-manager/index.d.ts @@ -0,0 +1,72 @@ +export = AddressManager; +/** + * @typedef {Object} AddressManagerOptions + * @property {string[]} [listen = []] - list of multiaddrs string representation to listen. + * @property {string[]} [announce = []] - list of multiaddrs string representation to announce. + */ +/** + * @fires AddressManager#change:addresses Emitted when a addresses change. + */ +declare class AddressManager extends EventEmitter { + /** + * Responsible for managing the peer addresses. + * Peers can specify their listen and announce addresses. + * The listen addresses will be used by the libp2p transports to listen for new connections, + * while the announce addresses will be used for the peer addresses' to other peers in the network. + * + * @class + * @param {PeerId} peerId - The Peer ID of the node + * @param {object} [options] + * @param {Array} [options.listen = []] - list of multiaddrs string representation to listen. + * @param {Array} [options.announce = []] - list of multiaddrs string representation to announce. + */ + constructor(peerId: PeerId, { listen, announce }?: { + listen?: string[] | undefined; + announce?: string[] | undefined; + } | undefined); + peerId: PeerId; + listen: Set; + announce: Set; + observed: Set; + /** + * Get peer listen multiaddrs. + * + * @returns {Multiaddr[]} + */ + getListenAddrs(): Multiaddr[]; + /** + * Get peer announcing multiaddrs. + * + * @returns {Multiaddr[]} + */ + getAnnounceAddrs(): Multiaddr[]; + /** + * Get observed multiaddrs. + * + * @returns {Array} + */ + getObservedAddrs(): Array; + /** + * Add peer observed addresses + * + * @param {string | Multiaddr} addr + */ + addObservedAddr(addr: string | Multiaddr): void; +} +declare namespace AddressManager { + export { AddressManagerOptions }; +} +import { EventEmitter } from "events"; +import PeerId = require("peer-id"); +import { Multiaddr } from "multiaddr"; +type AddressManagerOptions = { + /** + * - list of multiaddrs string representation to listen. + */ + listen?: string[] | undefined; + /** + * - list of multiaddrs string representation to announce. + */ + announce?: string[] | undefined; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/address-manager/index.d.ts.map b/dist/src/address-manager/index.d.ts.map new file mode 100644 index 0000000000..c435d4a539 --- /dev/null +++ b/dist/src/address-manager/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/address-manager/index.js"],"names":[],"mappings":";AAMA;;;;GAIG;AAEH;;GAEG;AACH;IACE;;;;;;;;;;;OAWG;IACH,oBALW,MAAM;;;mBAYhB;IAJC,eAAoB;IACpB,oBAAsD;IACtD,sBAA0D;IAC1D,mBAAyB;IAG3B;;;;OAIG;IACH,kBAFa,SAAS,EAAE,CAIvB;IAED;;;;OAIG;IACH,oBAFa,SAAS,EAAE,CAIvB;IAED;;;;OAIG;IACH,oBAFa,MAAM,SAAS,CAAC,CAI5B;IAED;;;;OAIG;IACH,sBAFW,MAAM,GAAG,SAAS,QAyB5B;CACF"} \ No newline at end of file diff --git a/dist/src/circuit/auto-relay.d.ts b/dist/src/circuit/auto-relay.d.ts new file mode 100644 index 0000000000..1b100438ef --- /dev/null +++ b/dist/src/circuit/auto-relay.d.ts @@ -0,0 +1,107 @@ +export = AutoRelay; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('../peer-store/types').Address} Address + * @typedef {import('peer-id')} PeerId + */ +/** + * @typedef {Object} AutoRelayProperties + * @property {import('../')} libp2p + * + * @typedef {Object} AutoRelayOptions + * @property {number} [maxListeners = 1] - maximum number of relays to listen. + * @property {(error: Error, msg?: string) => {}} [onError] + */ +declare class AutoRelay { + /** + * Creates an instance of AutoRelay. + * + * @class + * @param {AutoRelayProperties & AutoRelayOptions} props + */ + constructor({ libp2p, maxListeners, onError }: AutoRelayProperties & AutoRelayOptions); + _libp2p: import("../"); + _peerId: import("peer-id"); + _peerStore: import("../peer-store/types").PeerStore; + _connectionManager: import("../connection-manager"); + _transportManager: import("../transport-manager"); + _addressSorter: (addresses: import("../peer-store/types").Address[]) => import("../peer-store/types").Address[]; + maxListeners: number; + /** + * @type {Set} + */ + _listenRelays: Set; + /** + * Check if a peer supports the relay protocol. + * If the protocol is not supported, check if it was supported before and remove it as a listen relay. + * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if + * inside the threshold. + * + * @param {Object} props + * @param {PeerId} props.peerId + * @param {string[]} props.protocols + * @returns {Promise} + */ + _onProtocolChange({ peerId, protocols }: { + peerId: PeerId; + protocols: string[]; + }): Promise; + /** + * Peer disconnects. + * + * @param {Connection} connection - connection to the peer + */ + _onPeerDisconnected(connection: Connection): void; + /** + * @param {Error} error + * @param {string} [msg] + */ + _onError: (error: Error, msg?: string | undefined) => void; + /** + * Attempt to listen on the given relay connection. + * + * @private + * @param {Connection} connection - connection to the peer + * @param {string} id - peer identifier string + * @returns {Promise} + */ + private _addListenRelay; + /** + * Remove listen relay. + * + * @private + * @param {string} id - peer identifier string. + */ + private _removeListenRelay; + /** + * Try to listen on available hop relay connections. + * The following order will happen while we do not have enough relays. + * 1. Check the metadata store for known relays, try to listen on the ones we are already connected. + * 2. Dial and try to listen on the peers we know that support hop but are not connected. + * 3. Search the network. + * + * @param {string[]} [peersToIgnore] + */ + _listenOnAvailableHopRelays(peersToIgnore?: string[] | undefined): Promise; + /** + * @param {PeerId} peerId + */ + _tryToListenOnRelay(peerId: PeerId): Promise; +} +declare namespace AutoRelay { + export { Connection, Address, PeerId, AutoRelayProperties, AutoRelayOptions }; +} +type PeerId = import('peer-id'); +type Connection = import("libp2p-interfaces/src/connection/connection"); +type AutoRelayProperties = { + libp2p: import('../'); +}; +type AutoRelayOptions = { + /** + * - maximum number of relays to listen. + */ + maxListeners?: number | undefined; + onError?: ((error: Error, msg?: string | undefined) => {}) | undefined; +}; +type Address = import('../peer-store/types').Address; +//# sourceMappingURL=auto-relay.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/auto-relay.d.ts.map b/dist/src/circuit/auto-relay.d.ts.map new file mode 100644 index 0000000000..5069467d17 --- /dev/null +++ b/dist/src/circuit/auto-relay.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auto-relay.d.ts","sourceRoot":"","sources":["../../../src/circuit/auto-relay.js"],"names":[],"mappings":";AAsBA;;;;GAIG;AAEH;;;;;;;GAOG;AAEH;IACE;;;;;OAKG;IACH,+CAFW,mBAAmB,GAAG,gBAAgB,EA+BhD;IA5BC,uBAAqB;IACrB,2BAA4B;IAC5B,oDAAkC;IAClC,oDAAkD;IAClD,kDAAgD;IAChD,gHAAiD;IAEjD,qBAAgC;IAEhC;;OAEG;IACH,eAFU,IAAI,MAAM,CAAC,CAES;IAkBhC;;;;;;;;;;OAUG;IACH;QAJyB,MAAM,EAApB,MAAM;QACU,SAAS,EAAzB,MAAM,EAAE;QACN,QAAQ,IAAI,CAAC,CAsCzB;IAED;;;;OAIG;IACH,gCAFW,UAAU,QAcpB;IA5EC;;;OAGG;IACH,kBAHW,KAAK,oCAMf;IAuEH;;;;;;;OAOG;IACH,wBAkCC;IAED;;;;;OAKG;IACH,2BAKC;IAED;;;;;;;;OAQG;IACH,iFA6EC;IAED;;OAEG;IACH,4BAFW,MAAM,iBAShB;CACF;;;;cAlRY,OAAO,SAAS,CAAC;;;YAKhB,OAAO,KAAK,CAAC;;;;;;;uBAIL,KAAK,+BAAmB,EAAE;;eAVnC,OAAO,qBAAqB,EAAE,OAAO"} \ No newline at end of file diff --git a/dist/src/circuit/circuit/hop.d.ts b/dist/src/circuit/circuit/hop.d.ts new file mode 100644 index 0000000000..aabee15879 --- /dev/null +++ b/dist/src/circuit/circuit/hop.d.ts @@ -0,0 +1,67 @@ +export type ICircuitRelay = import('../protocol').ICircuitRelay; +export type Connection = import("libp2p-interfaces/src/connection/connection"); +export type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +export type Transport = import('../transport'); +export type HopRequest = { + connection: Connection; + request: ICircuitRelay; + streamHandler: StreamHandler; + circuit: Transport; +}; +/** + * @typedef {import('../protocol').ICircuitRelay} ICircuitRelay + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + * @typedef {import('../transport')} Transport + */ +/** + * @typedef {Object} HopRequest + * @property {Connection} connection + * @property {ICircuitRelay} request + * @property {StreamHandler} streamHandler + * @property {Transport} circuit + */ +/** + * @param {HopRequest} options + * @returns {Promise} + */ +export function handleHop({ connection, request, streamHandler, circuit }: HopRequest): Promise; +/** + * Performs a HOP request to a relay peer, to request a connection to another + * peer. A new, virtual, connection will be created between the two via the relay. + * + * @param {object} options + * @param {Connection} options.connection - Connection to the relay + * @param {ICircuitRelay} options.request + * @returns {Promise} + */ +export function hop({ connection, request }: { + connection: Connection; + request: ICircuitRelay; +}): Promise; +/** + * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities. + * + * @param {object} options + * @param {Connection} options.connection - Connection to the relay + * @returns {Promise} + */ +export function canHop({ connection }: { + connection: Connection; +}): Promise; +/** + * Creates an unencoded CAN_HOP response based on the Circuits configuration + * + * @param {Object} options + * @param {Connection} options.connection + * @param {StreamHandler} options.streamHandler + * @param {Transport} options.circuit + * @private + */ +export function handleCanHop({ connection, streamHandler, circuit }: { + connection: Connection; + streamHandler: StreamHandler; + circuit: Transport; +}): void; +import StreamHandler = require("./stream-handler"); +//# sourceMappingURL=hop.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/circuit/hop.d.ts.map b/dist/src/circuit/circuit/hop.d.ts.map new file mode 100644 index 0000000000..0e79880e4c --- /dev/null +++ b/dist/src/circuit/circuit/hop.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hop.d.ts","sourceRoot":"","sources":["../../../../src/circuit/circuit/hop.js"],"names":[],"mappings":"4BAoBa,OAAO,aAAa,EAAE,aAAa;;0BAEnC,OAAO,0CAA0C,EAAE,WAAW;wBAC9D,OAAO,cAAc,CAAC;;gBAKrB,UAAU;aACV,aAAa;mBACb,aAAa;aACb,SAAS;;AAZvB;;;;;GAKG;AAEH;;;;;;GAMG;AAEH;;;GAGG;AACH,2EAHW,UAAU,GACR,QAAQ,IAAI,CAAC,CA4EzB;AAED;;;;;;;;GAQG;AACH;IAJ+B,UAAU,EAA9B,UAAU;IACa,OAAO,EAA9B,aAAa;IACX,QAAQ,WAAW,CAAC,CA0BhC;AAED;;;;;;GAMG;AACH;IAH+B,UAAU,EAA9B,UAAU;IACR,QAAQ,OAAO,CAAC,CAqB5B;AAED;;;;;;;;GAQG;AACH;IAL+B,UAAU,EAA9B,UAAU;IACa,aAAa,EAApC,aAAa;IACM,OAAO,EAA1B,SAAS;SAcnB"} \ No newline at end of file diff --git a/dist/src/circuit/circuit/stop.d.ts b/dist/src/circuit/circuit/stop.d.ts new file mode 100644 index 0000000000..2b4d909138 --- /dev/null +++ b/dist/src/circuit/circuit/stop.d.ts @@ -0,0 +1,14 @@ +export function handleStop({ connection, request, streamHandler }: { + connection: Connection; + request: ICircuitRelay; + streamHandler: StreamHandler; +}): Promise | void; +export function stop({ connection, request }: { + connection: Connection; + request: ICircuitRelay; +}): Promise; +export type Connection = import("libp2p-interfaces/src/connection/connection"); +export type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +export type ICircuitRelay = import('../protocol').ICircuitRelay; +import StreamHandler = require("./stream-handler"); +//# sourceMappingURL=stop.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/circuit/stop.d.ts.map b/dist/src/circuit/circuit/stop.d.ts.map new file mode 100644 index 0000000000..e8cd7a4c09 --- /dev/null +++ b/dist/src/circuit/circuit/stop.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stop.d.ts","sourceRoot":"","sources":["../../../../src/circuit/circuit/stop.js"],"names":[],"mappings":"AA4B4B;IALG,UAAU,EAA9B,UAAU;IACa,OAAO,EAA9B,aAAa;IACU,aAAa,EAApC,aAAa;IACX,QAAQ,WAAW,CAAC,GAAC,IAAI,CAqBrC;AAWqB;IAJS,UAAU,EAA9B,UAAU;IACa,OAAO,EAA9B,aAAa;IACX,QAAQ,WAAW,GAAC,IAAI,CAAC,CAwBrC;;0BAlEY,OAAO,0CAA0C,EAAE,WAAW;4BAC9D,OAAO,aAAa,EAAE,aAAa"} \ No newline at end of file diff --git a/dist/src/circuit/circuit/stream-handler.d.ts b/dist/src/circuit/circuit/stream-handler.d.ts new file mode 100644 index 0000000000..c1fa53ce9e --- /dev/null +++ b/dist/src/circuit/circuit/stream-handler.d.ts @@ -0,0 +1,58 @@ +export = StreamHandler; +/** + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + * @typedef {import('../protocol').ICircuitRelay} ICircuitRelay + */ +declare class StreamHandler { + /** + * Create a stream handler for connection + * + * @class + * @param {object} options + * @param {MuxedStream} options.stream - A duplex iterable + * @param {number} [options.maxLength = 4096] - max bytes length of message + */ + constructor({ stream, maxLength }: { + stream: MuxedStream; + maxLength?: number | undefined; + }); + stream: import("libp2p-interfaces/src/stream-muxer/types").MuxedStream; + shake: any; + decoder: AsyncGenerator; + /** + * Read and decode message + * + * @async + */ + read(): Promise; + /** + * Encode and write array of buffers + * + * @param {ICircuitRelay} msg - An unencoded CircuitRelay protobuf message + * @returns {void} + */ + write(msg: ICircuitRelay): void; + /** + * Return the handshake rest stream and invalidate handler + * + * @returns {*} A duplex iterable + */ + rest(): any; + /** + * @param {ICircuitRelay} msg - An unencoded CircuitRelay protobuf message + */ + end(msg: ICircuitRelay): void; + /** + * Close the stream + * + * @returns {void} + */ + close(): void; +} +declare namespace StreamHandler { + export { MuxedStream, ICircuitRelay }; +} +import { CircuitRelay } from "../protocol"; +type ICircuitRelay = import('../protocol').ICircuitRelay; +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +//# sourceMappingURL=stream-handler.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/circuit/stream-handler.d.ts.map b/dist/src/circuit/circuit/stream-handler.d.ts.map new file mode 100644 index 0000000000..f2bcab520a --- /dev/null +++ b/dist/src/circuit/circuit/stream-handler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stream-handler.d.ts","sourceRoot":"","sources":["../../../../src/circuit/circuit/stream-handler.js"],"names":[],"mappings":";AAYA;;;GAGG;AAEH;IACE;;;;;;;OAOG;IACH;QAHgC,MAAM,EAA3B,WAAW;QACM,SAAS;OAQpC;IALC,uEAAoB;IAEpB,WAAmC;IAEnC,4CAAoF;IAGtF;;;;OAIG;IACH,0CAWC;IAED;;;;;OAKG;IACH,WAHW,aAAa,GACX,IAAI,CAMhB;IAED;;;;OAIG;IACH,YAGC;IAED;;OAEG;IACH,SAFW,aAAa,QAKvB;IAED;;;;OAIG;IACH,SAFa,IAAI,CAKhB;CACF;;;;;qBA7EY,OAAO,aAAa,EAAE,aAAa;mBADnC,OAAO,0CAA0C,EAAE,WAAW"} \ No newline at end of file diff --git a/dist/src/circuit/circuit/utils.d.ts b/dist/src/circuit/circuit/utils.d.ts new file mode 100644 index 0000000000..0076087c02 --- /dev/null +++ b/dist/src/circuit/circuit/utils.d.ts @@ -0,0 +1,10 @@ +export type StreamHandler = import('./stream-handler'); +export type ICircuitRelay = import('../protocol').ICircuitRelay; +/** + * Validate incomming HOP/STOP message + * + * @param {ICircuitRelay} msg - A CircuitRelay unencoded protobuf message + * @param {StreamHandler} streamHandler + */ +export function validateAddrs(msg: ICircuitRelay, streamHandler: StreamHandler): void; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/circuit/utils.d.ts.map b/dist/src/circuit/circuit/utils.d.ts.map new file mode 100644 index 0000000000..60811e494d --- /dev/null +++ b/dist/src/circuit/circuit/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../src/circuit/circuit/utils.js"],"names":[],"mappings":"4BAMa,OAAO,kBAAkB,CAAC;4BAC1B,OAAO,aAAa,EAAE,aAAa;AAgBhD;;;;;GAKG;AACH,mCAHW,aAAa,iBACb,aAAa,QA4BvB"} \ No newline at end of file diff --git a/dist/src/circuit/constants.d.ts b/dist/src/circuit/constants.d.ts new file mode 100644 index 0000000000..56df991a3a --- /dev/null +++ b/dist/src/circuit/constants.d.ts @@ -0,0 +1,7 @@ +export const ADVERTISE_BOOT_DELAY: number; +export const ADVERTISE_TTL: number; +export const CIRCUIT_PROTO_CODE: number; +export const HOP_METADATA_KEY: string; +export const HOP_METADATA_VALUE: string; +export const RELAY_RENDEZVOUS_NS: string; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/constants.d.ts.map b/dist/src/circuit/constants.d.ts.map new file mode 100644 index 0000000000..634b461cfa --- /dev/null +++ b/dist/src/circuit/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/circuit/constants.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/circuit/index.d.ts b/dist/src/circuit/index.d.ts new file mode 100644 index 0000000000..6de792f3f7 --- /dev/null +++ b/dist/src/circuit/index.d.ts @@ -0,0 +1,85 @@ +export = Relay; +/** + * @typedef {import('../')} Libp2p + * + * @typedef {Object} RelayAdvertiseOptions + * @property {number} [bootDelay = ADVERTISE_BOOT_DELAY] + * @property {boolean} [enabled = true] + * @property {number} [ttl = ADVERTISE_TTL] + * + * @typedef {Object} HopOptions + * @property {boolean} [enabled = false] + * @property {boolean} [active = false] + * + * @typedef {Object} AutoRelayOptions + * @property {number} [maxListeners = 2] - maximum number of relays to listen. + * @property {boolean} [enabled = false] + */ +declare class Relay { + /** + * Creates an instance of Relay. + * + * @class + * @param {Libp2p} libp2p + */ + constructor(libp2p: Libp2p); + _libp2p: import("../"); + _options: { + enabled: boolean; + advertise: { + bootDelay: number; + enabled: boolean; + ttl: number; + } & RelayAdvertiseOptions; + hop: { + enabled: boolean; + active: boolean; + } & HopOptions; + autoRelay: { + enabled: boolean; + maxListeners: number; + } & AutoRelayOptions; + }; + _autoRelay: false | AutoRelay; + /** + * Advertise hop relay service in the network. + * + * @returns {Promise} + */ + _advertiseService(): Promise; + /** + * Start Relay service. + * + * @returns {void} + */ + start(): void; + _timeout: any; + /** + * Stop Relay service. + * + * @returns {void} + */ + stop(): void; +} +declare namespace Relay { + export { Libp2p, RelayAdvertiseOptions, HopOptions, AutoRelayOptions }; +} +import AutoRelay = require("./auto-relay"); +type Libp2p = import('../'); +type RelayAdvertiseOptions = { + bootDelay?: number | undefined; + enabled?: boolean | undefined; + ttl?: number | undefined; +}; +type HopOptions = { + enabled?: boolean | undefined; + active?: boolean | undefined; +}; +type AutoRelayOptions = { + /** + * - maximum number of relays to listen. + */ + maxListeners?: number | undefined; + enabled?: boolean | undefined; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/index.d.ts.map b/dist/src/circuit/index.d.ts.map new file mode 100644 index 0000000000..79c051337b --- /dev/null +++ b/dist/src/circuit/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/circuit/index.js"],"names":[],"mappings":";AAmBA;;;;;;;;;;;;;;;GAeG;AAEH;IACE;;;;;OAKG;IACH,oBAFW,MAAM,EAYhB;IATC,uBAAqB;IACrB;;;;;;;;;;;;;;;MAEC;IAGD,8BAA0G;IA8B5G;;;;OAIG;IACH,qBAFa,QAAQ,IAAI,CAAC,CAezB;IA3CD;;;;OAIG;IACH,SAFa,IAAI,CAWhB;IAJG,cAEC;IAIL;;;;OAIG;IACH,QAFa,IAAI,CAIhB;CAqBF;;;;;cA/EY,OAAO,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/src/circuit/listener.d.ts b/dist/src/circuit/listener.d.ts new file mode 100644 index 0000000000..85e0b4c7fe --- /dev/null +++ b/dist/src/circuit/listener.d.ts @@ -0,0 +1,4 @@ +declare function _exports(libp2p: import('../')): Listener; +export = _exports; +export type Listener = import('libp2p-interfaces/src/transport/types').Listener; +//# sourceMappingURL=listener.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/listener.d.ts.map b/dist/src/circuit/listener.d.ts.map new file mode 100644 index 0000000000..39cc6c19e7 --- /dev/null +++ b/dist/src/circuit/listener.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"listener.d.ts","sourceRoot":"","sources":["../../../src/circuit/listener.js"],"names":[],"mappings":"AAaiB,kCAHN,OAAO,KAAK,CAAC,GACX,QAAQ,CA+DpB;;uBApEY,OAAO,uCAAuC,EAAE,QAAQ"} \ No newline at end of file diff --git a/dist/src/circuit/multicodec.d.ts b/dist/src/circuit/multicodec.d.ts new file mode 100644 index 0000000000..c78b406cdb --- /dev/null +++ b/dist/src/circuit/multicodec.d.ts @@ -0,0 +1,2 @@ +export const relay: string; +//# sourceMappingURL=multicodec.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/multicodec.d.ts.map b/dist/src/circuit/multicodec.d.ts.map new file mode 100644 index 0000000000..53249c22dd --- /dev/null +++ b/dist/src/circuit/multicodec.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multicodec.d.ts","sourceRoot":"","sources":["../../../src/circuit/multicodec.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/circuit/protocol/index.d.ts b/dist/src/circuit/protocol/index.d.ts new file mode 100644 index 0000000000..68e4880b95 --- /dev/null +++ b/dist/src/circuit/protocol/index.d.ts @@ -0,0 +1,173 @@ +import * as $protobuf from "protobufjs"; +/** Properties of a CircuitRelay. */ +export interface ICircuitRelay { + + /** CircuitRelay type */ + type?: (CircuitRelay.Type|null); + + /** CircuitRelay srcPeer */ + srcPeer?: (CircuitRelay.IPeer|null); + + /** CircuitRelay dstPeer */ + dstPeer?: (CircuitRelay.IPeer|null); + + /** CircuitRelay code */ + code?: (CircuitRelay.Status|null); +} + +/** Represents a CircuitRelay. */ +export class CircuitRelay implements ICircuitRelay { + + /** + * Constructs a new CircuitRelay. + * @param [p] Properties to set + */ + constructor(p?: ICircuitRelay); + + /** CircuitRelay type. */ + public type: CircuitRelay.Type; + + /** CircuitRelay srcPeer. */ + public srcPeer?: (CircuitRelay.IPeer|null); + + /** CircuitRelay dstPeer. */ + public dstPeer?: (CircuitRelay.IPeer|null); + + /** CircuitRelay code. */ + public code: CircuitRelay.Status; + + /** + * Encodes the specified CircuitRelay message. Does not implicitly {@link CircuitRelay.verify|verify} messages. + * @param m CircuitRelay message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: ICircuitRelay, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CircuitRelay message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns CircuitRelay + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): CircuitRelay; + + /** + * Creates a CircuitRelay message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns CircuitRelay + */ + public static fromObject(d: { [k: string]: any }): CircuitRelay; + + /** + * Creates a plain object from a CircuitRelay message. Also converts values to other types if specified. + * @param m CircuitRelay + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: CircuitRelay, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CircuitRelay to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +export namespace CircuitRelay { + + /** Status enum. */ + enum Status { + SUCCESS = 100, + HOP_SRC_ADDR_TOO_LONG = 220, + HOP_DST_ADDR_TOO_LONG = 221, + HOP_SRC_MULTIADDR_INVALID = 250, + HOP_DST_MULTIADDR_INVALID = 251, + HOP_NO_CONN_TO_DST = 260, + HOP_CANT_DIAL_DST = 261, + HOP_CANT_OPEN_DST_STREAM = 262, + HOP_CANT_SPEAK_RELAY = 270, + HOP_CANT_RELAY_TO_SELF = 280, + STOP_SRC_ADDR_TOO_LONG = 320, + STOP_DST_ADDR_TOO_LONG = 321, + STOP_SRC_MULTIADDR_INVALID = 350, + STOP_DST_MULTIADDR_INVALID = 351, + STOP_RELAY_REFUSED = 390, + MALFORMED_MESSAGE = 400 + } + + /** Type enum. */ + enum Type { + HOP = 1, + STOP = 2, + STATUS = 3, + CAN_HOP = 4 + } + + /** Properties of a Peer. */ + interface IPeer { + + /** Peer id */ + id: Uint8Array; + + /** Peer addrs */ + addrs?: (Uint8Array[]|null); + } + + /** Represents a Peer. */ + class Peer implements IPeer { + + /** + * Constructs a new Peer. + * @param [p] Properties to set + */ + constructor(p?: CircuitRelay.IPeer); + + /** Peer id. */ + public id: Uint8Array; + + /** Peer addrs. */ + public addrs: Uint8Array[]; + + /** + * Encodes the specified Peer message. Does not implicitly {@link CircuitRelay.Peer.verify|verify} messages. + * @param m Peer message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: CircuitRelay.IPeer, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Peer message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Peer + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): CircuitRelay.Peer; + + /** + * Creates a Peer message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Peer + */ + public static fromObject(d: { [k: string]: any }): CircuitRelay.Peer; + + /** + * Creates a plain object from a Peer message. Also converts values to other types if specified. + * @param m Peer + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: CircuitRelay.Peer, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Peer to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } +} diff --git a/dist/src/circuit/transport.d.ts b/dist/src/circuit/transport.d.ts new file mode 100644 index 0000000000..22d64e74a5 --- /dev/null +++ b/dist/src/circuit/transport.d.ts @@ -0,0 +1,93 @@ +export = Circuit; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + */ +declare class Circuit { + /** + * Checks if the given value is a Transport instance. + * + * @param {any} other + * @returns {other is Transport} + */ + static isTransport(other: any): other is any; + /** + * Creates an instance of the Circuit Transport. + * + * @class + * @param {object} options + * @param {import('../')} options.libp2p + * @param {import('../upgrader')} options.upgrader + */ + constructor({ libp2p, upgrader }: { + libp2p: import('../'); + upgrader: import('../upgrader'); + }); + _dialer: import("../dialer"); + _registrar: import("../registrar"); + _connectionManager: import("../connection-manager"); + _upgrader: import("../upgrader"); + _options: { + enabled: boolean; + advertise: { + bootDelay: number; + enabled: boolean; + ttl: number; + }; + hop: { + enabled: boolean; + active: boolean; + }; + autoRelay: { + enabled: boolean; + maxListeners: number; + }; + } & import("../").RelayOptions; + _libp2p: import("../"); + peerId: PeerId; + /** + * @param {Object} props + * @param {Connection} props.connection + * @param {MuxedStream} props.stream + */ + _onProtocol({ connection, stream }: { + connection: Connection; + stream: MuxedStream; + }): Promise; + /** + * Dial a peer over a relay + * + * @param {Multiaddr} ma - the multiaddr of the peer to dial + * @param {Object} options - dial options + * @param {AbortSignal} [options.signal] - An optional abort signal + * @returns {Promise} - the connection + */ + dial(ma: Multiaddr, options: { + signal?: AbortSignal | undefined; + }): Promise; + /** + * Create a listener + * + * @param {any} options + * @param {Function} handler + * @returns {import('libp2p-interfaces/src/transport/types').Listener} + */ + createListener(options: any, handler: Function): import('libp2p-interfaces/src/transport/types').Listener; + handler: Function | undefined; + /** + * Filter check for all Multiaddrs that this transport can dial on + * + * @param {Multiaddr[]} multiaddrs + * @returns {Multiaddr[]} + */ + filter(multiaddrs: Multiaddr[]): Multiaddr[]; + get [Symbol.toStringTag](): string; +} +declare namespace Circuit { + export { Connection, MuxedStream }; +} +import PeerId = require("peer-id"); +type Connection = import("libp2p-interfaces/src/connection/connection"); +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +import { Multiaddr } from "multiaddr"; +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/transport.d.ts.map b/dist/src/circuit/transport.d.ts.map new file mode 100644 index 0000000000..110df1ace5 --- /dev/null +++ b/dist/src/circuit/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/circuit/transport.js"],"names":[],"mappings":";AAwBA;;;GAGG;AAEH;IA4LE;;;;;OAKG;IACH,0BAHW,GAAG,gBAKb;IAnMD;;;;;;;OAOG;IACH;QAHkC,MAAM,EAA7B,OAAO,KAAK,CAAC;QACkB,QAAQ,EAAvC,OAAO,aAAa,CAAC;OAY/B;IATC,6BAA4B;IAC5B,mCAAkC;IAClC,oDAAkD;IAClD,iCAAyB;IACzB;;;;;;;;;;;;;;;mCAAoC;IACpC,uBAAqB;IACrB,eAA2B;IAK7B;;;;OAIG;IACH;QAH6B,UAAU,EAA5B,UAAU;QACS,MAAM,EAAzB,WAAW;sBA6DrB;IAED;;;;;;;OAOG;IACH,SALW,SAAS;QAEa,MAAM;QAC1B,QAAQ,UAAU,CAAC,CAwD/B;IAED;;;;;;OAMG;IACH,wBAJW,GAAG,sBAED,OAAO,uCAAuC,EAAE,QAAQ,CAYpE;IAHC,8BAAsB;IAKxB;;;;;OAKG;IACH,mBAHW,SAAS,EAAE,GACT,SAAS,EAAE,CAQvB;IAED,mCAEC;CAWF;;;;;;mBAxMY,OAAO,0CAA0C,EAAE,WAAW"} \ No newline at end of file diff --git a/dist/src/circuit/utils.d.ts b/dist/src/circuit/utils.d.ts new file mode 100644 index 0000000000..a9228256f6 --- /dev/null +++ b/dist/src/circuit/utils.d.ts @@ -0,0 +1,3 @@ +export function namespaceToCid(namespace: string): Promise; +import { CID } from "multiformats/cid"; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/dist/src/circuit/utils.d.ts.map b/dist/src/circuit/utils.d.ts.map new file mode 100644 index 0000000000..b8c53717cf --- /dev/null +++ b/dist/src/circuit/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/circuit/utils.js"],"names":[],"mappings":"AAWgC,0CAHrB,MAAM,GACJ,QAAQ,GAAG,CAAC,CAOxB"} \ No newline at end of file diff --git a/dist/src/config.d.ts b/dist/src/config.d.ts new file mode 100644 index 0000000000..5b1b7ada46 --- /dev/null +++ b/dist/src/config.d.ts @@ -0,0 +1,86 @@ +export function validate(opts: Libp2pOptions): { + addresses: { + listen: never[]; + announce: never[]; + noAnnounce: never[]; + announceFilter: (multiaddrs: Multiaddr[]) => import("multiaddr").Multiaddr[]; + }; + connectionManager: { + minConnections: number; + }; + connectionGater: {}; + transportManager: { + faultTolerance: number; + }; + dialer: { + maxParallelDials: number; + maxDialsPerPeer: number; + dialTimeout: number; + resolvers: { + dnsaddr: any; + }; + addressSorter: typeof publicAddressesFirst; + }; + host: { + agentVersion: string; + }; + metrics: { + enabled: boolean; + }; + peerStore: { + persistence: boolean; + threshold: number; + }; + peerRouting: { + refreshManager: { + enabled: boolean; + interval: number; + bootDelay: number; + }; + }; + config: { + protocolPrefix: string; + dht: { + enabled: boolean; + kBucketSize: number; + }; + nat: { + enabled: boolean; + ttl: number; + keepAlive: boolean; + gateway: null; + externalIp: null; + pmp: { + enabled: boolean; + }; + }; + peerDiscovery: { + autoDial: boolean; + }; + pubsub: { + enabled: boolean; + }; + relay: { + enabled: boolean; + advertise: { + bootDelay: number; + enabled: boolean; + ttl: number; + }; + hop: { + enabled: boolean; + active: boolean; + }; + autoRelay: { + enabled: boolean; + maxListeners: number; + }; + }; + transport: {}; + }; +} & Libp2pOptions & constructorOptions; +export type Multiaddr = import('multiaddr').Multiaddr; +export type ConnectionGater = import('./types').ConnectionGater; +export type Libp2pOptions = import('.').Libp2pOptions; +export type constructorOptions = import('.').constructorOptions; +//# sourceMappingURL=config.d.ts.map \ No newline at end of file diff --git a/dist/src/config.d.ts.map b/dist/src/config.d.ts.map new file mode 100644 index 0000000000..d3ae0b7067 --- /dev/null +++ b/dist/src/config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.js"],"names":[],"mappings":"AA0G0B,+BAHf,aAAa,GACX;;;;;qCA/EmB,SAAS,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+Ed,aAAa,GAAG,kBAAkB,CAS9D;wBAnGY,OAAO,WAAW,EAAE,SAAS;8BAC7B,OAAO,SAAS,EAAE,eAAe;4BACjC,OAAO,GAAG,EAAE,aAAa;iCACzB,OAAO,GAAG,EAAE,kBAAkB"} \ No newline at end of file diff --git a/dist/src/connection-manager/auto-dialler.d.ts b/dist/src/connection-manager/auto-dialler.d.ts new file mode 100644 index 0000000000..aded73cb92 --- /dev/null +++ b/dist/src/connection-manager/auto-dialler.d.ts @@ -0,0 +1,56 @@ +export = AutoDialler; +/** + * @typedef {import('../index')} Libp2p + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + */ +/** + * @typedef {Object} AutoDiallerOptions + * @property {boolean} [enabled = true] - Should preemptively guarantee connections are above the low watermark + * @property {number} [minConnections = 0] - The minimum number of connections to avoid pruning + * @property {number} [autoDialInterval = 10000] - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark + */ +declare class AutoDialler { + /** + * Proactively tries to connect to known peers stored in the PeerStore. + * It will keep the number of connections below the upper limit and sort + * the peers to connect based on wether we know their keys and protocols. + * + * @class + * @param {Libp2p} libp2p + * @param {AutoDiallerOptions} options + */ + constructor(libp2p: Libp2p, options?: AutoDiallerOptions); + _options: any; + _libp2p: import("../index"); + _running: boolean; + _autoDialTimeout: any; + _autoDial(): Promise; + /** + * Starts the auto dialer + */ + start(): Promise; + /** + * Stops the auto dialler + */ + stop(): Promise; +} +declare namespace AutoDialler { + export { Libp2p, Connection, AutoDiallerOptions }; +} +type Libp2p = import('../index'); +type AutoDiallerOptions = { + /** + * - Should preemptively guarantee connections are above the low watermark + */ + enabled?: boolean | undefined; + /** + * - The minimum number of connections to avoid pruning + */ + minConnections?: number | undefined; + /** + * - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark + */ + autoDialInterval?: number | undefined; +}; +type Connection = import("libp2p-interfaces/src/connection/connection"); +//# sourceMappingURL=auto-dialler.d.ts.map \ No newline at end of file diff --git a/dist/src/connection-manager/auto-dialler.d.ts.map b/dist/src/connection-manager/auto-dialler.d.ts.map new file mode 100644 index 0000000000..be7a69385c --- /dev/null +++ b/dist/src/connection-manager/auto-dialler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auto-dialler.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/auto-dialler.js"],"names":[],"mappings":";AAqBA;;;GAGG;AAEH;;;;;GAKG;AAEH;IACE;;;;;;;;OAQG;IACH,oBAHW,MAAM,YACN,kBAAkB,EAU5B;IAPC,cAAqF;IACrF,4BAAqB;IACrB,kBAAqB;IACrB,sBAA4B;IAoC9B,2BA6CC;IA3ED;;OAEG;IACH,uBAWC;IAED;;OAEG;IACH,sBASC;CAgDF;;;;cA3GY,OAAO,UAAU,CAAC"} \ No newline at end of file diff --git a/dist/src/connection-manager/index.d.ts b/dist/src/connection-manager/index.d.ts new file mode 100644 index 0000000000..ecaaf1692a --- /dev/null +++ b/dist/src/connection-manager/index.d.ts @@ -0,0 +1,193 @@ +export = ConnectionManager; +/** + * @typedef {import('../')} Libp2p + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + */ +/** + * @typedef {Object} ConnectionManagerOptions + * @property {number} [maxConnections = Infinity] - The maximum number of connections allowed. + * @property {number} [minConnections = 0] - The minimum number of connections to avoid pruning. + * @property {number} [maxData = Infinity] - The max data (in and out), per average interval to allow. + * @property {number} [maxSentData = Infinity] - The max outgoing data, per average interval to allow. + * @property {number} [maxReceivedData = Infinity] - The max incoming data, per average interval to allow. + * @property {number} [maxEventLoopDelay = Infinity] - The upper limit the event loop can take to run. + * @property {number} [pollInterval = 2000] - How often, in milliseconds, metrics and latency should be checked. + * @property {number} [movingAverageInterval = 60000] - How often, in milliseconds, to compute averages. + * @property {number} [defaultPeerValue = 1] - The value of the peer. + * @property {boolean} [autoDial = true] - Should preemptively guarantee connections are above the low watermark. + * @property {number} [autoDialInterval = 10000] - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark. + */ +/** + * + * @fires ConnectionManager#peer:connect Emitted when a new peer is connected. + * @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected. + */ +declare class ConnectionManager extends EventEmitter { + /** + * Responsible for managing known connections. + * + * @class + * @param {Libp2p} libp2p + * @param {ConnectionManagerOptions} options + */ + constructor(libp2p: Libp2p, options?: ConnectionManagerOptions); + _libp2p: import("../"); + _peerId: string; + _options: any; + /** + * Map of peer identifiers to their peer value for pruning connections. + * + * @type {Map} + */ + _peerValues: Map; + /** + * Map of connections per peer + * + * @type {Map} + */ + connections: Map; + _started: boolean; + _timer: any; + /** + * Checks the libp2p metrics to determine if any values have exceeded + * the configured maximums. + * + * @private + */ + private _checkMetrics; + _latencyMonitor: LatencyMonitor; + /** + * Get current number of open connections. + */ + get size(): number; + /** + * Starts the Connection Manager. If Metrics are not enabled on libp2p + * only event loop and connection limits will be monitored. + */ + start(): void; + /** + * If the event loop is slow, maybe close a connection + * + * @private + * @param {*} summary - The LatencyMonitor summary + */ + private _onLatencyMeasure; + /** + * Stops the Connection Manager + * + * @async + */ + stop(): Promise; + /** + * Cleans up the connections + * + * @async + */ + _close(): Promise; + /** + * Sets the value of the given peer. Peers with lower values + * will be disconnected first. + * + * @param {PeerId} peerId + * @param {number} value - A number between 0 and 1 + * @returns {void} + */ + setPeerValue(peerId: PeerId, value: number): void; + /** + * Tracks the incoming connection and check the connection limit + * + * @param {Connection} connection + */ + onConnect(connection: Connection): Promise; + /** + * Removes the connection from tracking + * + * @param {Connection} connection + * @returns {void} + */ + onDisconnect(connection: Connection): void; + /** + * Get a connection with a peer. + * + * @param {PeerId} peerId + * @returns {Connection|null} + */ + get(peerId: PeerId): Connection | null; + /** + * Get all open connections with a peer. + * + * @param {PeerId} peerId + * @returns {Connection[]} + */ + getAll(peerId: PeerId): Connection[]; + /** + * If the `value` of `name` has exceeded its limit, maybe close a connection + * + * @private + * @param {string} name - The name of the field to check limits for + * @param {number} value - The current value of the field + */ + private _checkMaxLimit; + /** + * If we have more connections than our maximum, close a connection + * to the lowest valued peer. + * + * @private + */ + private _maybeDisconnectOne; +} +declare namespace ConnectionManager { + export { Libp2p, Connection, ConnectionManagerOptions }; +} +import { EventEmitter } from "events"; +type Connection = import("libp2p-interfaces/src/connection/connection"); +import LatencyMonitor = require("./latency-monitor"); +import PeerId = require("peer-id"); +type Libp2p = import('../'); +type ConnectionManagerOptions = { + /** + * - The maximum number of connections allowed. + */ + maxConnections?: number | undefined; + /** + * - The minimum number of connections to avoid pruning. + */ + minConnections?: number | undefined; + /** + * - The max data (in and out), per average interval to allow. + */ + maxData?: number | undefined; + /** + * - The max outgoing data, per average interval to allow. + */ + maxSentData?: number | undefined; + /** + * - The max incoming data, per average interval to allow. + */ + maxReceivedData?: number | undefined; + /** + * - The upper limit the event loop can take to run. + */ + maxEventLoopDelay?: number | undefined; + /** + * - How often, in milliseconds, metrics and latency should be checked. + */ + pollInterval?: number | undefined; + /** + * - How often, in milliseconds, to compute averages. + */ + movingAverageInterval?: number | undefined; + /** + * - The value of the peer. + */ + defaultPeerValue?: number | undefined; + /** + * - Should preemptively guarantee connections are above the low watermark. + */ + autoDial?: boolean | undefined; + /** + * - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark. + */ + autoDialInterval?: number | undefined; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/connection-manager/index.d.ts.map b/dist/src/connection-manager/index.d.ts.map new file mode 100644 index 0000000000..a1eb867f85 --- /dev/null +++ b/dist/src/connection-manager/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/index.js"],"names":[],"mappings":";AAsCA;;;GAGG;AAEH;;;;;;;;;;;;;GAaG;AAEH;;;;GAIG;AACH;IACE;;;;;;OAMG;IACH,oBAHW,MAAM,YACN,wBAAwB,EAgDlC;IA3CC,uBAAqB;IACrB,gBAA0C;IAE1C,cAAqF;IAOrF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,MAAM,CAAC,CAM3B;IAEF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,UAAU,EAAE,CAAC,CAMjC;IAEF,kBAAqB;IACrB,YAAkB;IAuFpB;;;;;OAKG;IACH,sBAiBC;IA3GC,gCAGE;IAMJ;;OAEG;IACH,mBAGC;IAED;;;OAGG;IACH,cAYC;IA2KD;;;;;OAKG;IACH,0BAKC;IApLD;;;;OAIG;IACH,sBASC;IAED;;;;OAIG;IACH,wBAWC;IAED;;;;;;;OAOG;IACH,qBAJW,MAAM,SACN,MAAM,GACJ,IAAI,CAOhB;IA2BD;;;;OAIG;IACH,sBAFW,UAAU,iBA4BpB;IAED;;;;;OAKG;IACH,yBAHW,UAAU,GACR,IAAI,CAqBhB;IAED;;;;;OAKG;IACH,YAHW,MAAM,GACJ,UAAU,GAAC,IAAI,CAQ3B;IAED;;;;;OAKG;IACH,eAHW,MAAM,GACJ,UAAU,EAAE,CAexB;IAeD;;;;;;OAMG;IACH,uBAOC;IAED;;;;;OAKG;IACH,4BAqBC;CACF;;;;;;;;cA5UY,OAAO,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/src/connection-manager/latency-monitor.d.ts b/dist/src/connection-manager/latency-monitor.d.ts new file mode 100644 index 0000000000..74ef2f198f --- /dev/null +++ b/dist/src/connection-manager/latency-monitor.d.ts @@ -0,0 +1,145 @@ +export = LatencyMonitor; +/** + * @typedef {Object} SummaryObject + * @property {number} events How many events were called + * @property {number} minMS What was the min time for a cb to be called + * @property {number} maxMS What was the max time for a cb to be called + * @property {number} avgMs What was the average time for a cb to be called + * @property {number} lengthMs How long this interval was in ms + * + * @typedef {Object} LatencyMonitorOptions + * @property {number} [latencyCheckIntervalMs=500] - How often to add a latency check event (ms) + * @property {number} [dataEmitIntervalMs=5000] - How often to summarize latency check events. null or 0 disables event firing + * @property {Function} [asyncTestFn] - What cb-style async function to use + * @property {number} [latencyRandomPercentage=5] - What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events. + */ +/** + * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling + * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this. + * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0. + * + * @extends {EventEmitter} + * + * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop + * and timing how long it takes to get back. + * + * @example + * const monitor = new LatencyMonitor(); + * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary)); + * + * @example + * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping}); + * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary)); + */ +declare class LatencyMonitor extends EventEmitter { + /** + * @class + * @param {LatencyMonitorOptions} [options] + */ + constructor({ latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage }?: LatencyMonitorOptions | undefined); + latencyCheckIntervalMs: number; + latencyRandomPercentage: number; + _latecyCheckMultiply: number; + _latecyCheckSubtract: number; + dataEmitIntervalMs: number | undefined; + asyncTestFn: Function | undefined; + start(): void; + now: (() => number) | NodeJS.HRTime | undefined; + getDeltaMS: ((startTime: any) => number) | undefined; + _latencyData: { + startTime: number | [number, number]; + minMs: number; + maxMs: number; + events: number; + totalMs: number; + } | undefined; + _visibilityChangeEmitter: VisibilityChangeEmitter | undefined; + stop(): void; + /** + * Start internal timers + * + * @private + */ + private _startTimers; + _emitIntervalID: NodeJS.Timer | undefined; + /** + * Stop internal timers + * + * @private + */ + private _stopTimers; + _checkLatencyID: NodeJS.Timeout | undefined; + /** + * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show + * + * @private + */ + private _emitSummary; + /** + * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue, + * it will not count for this time period + * + * @returns {SummaryObject} + */ + getSummary(): SummaryObject; + /** + * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found, + * it will simply report on event loop latency. + * + * @private + */ + private _checkLatency; + _initLatencyData(): { + startTime: number | [number, number]; + minMs: number; + maxMs: number; + events: number; + totalMs: number; + }; +} +declare namespace LatencyMonitor { + export { SummaryObject, LatencyMonitorOptions }; +} +import { EventEmitter } from "events"; +import VisibilityChangeEmitter = require("./visibility-change-emitter"); +type SummaryObject = { + /** + * How many events were called + */ + events: number; + /** + * What was the min time for a cb to be called + */ + minMS: number; + /** + * What was the max time for a cb to be called + */ + maxMS: number; + /** + * What was the average time for a cb to be called + */ + avgMs: number; + /** + * How long this interval was in ms + */ + lengthMs: number; +}; +type LatencyMonitorOptions = { + /** + * - How often to add a latency check event (ms) + */ + latencyCheckIntervalMs?: number | undefined; + /** + * - How often to summarize latency check events. null or 0 disables event firing + */ + dataEmitIntervalMs?: number | undefined; + /** + * - What cb-style async function to use + */ + asyncTestFn?: Function | undefined; + /** + * - What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events. + */ + latencyRandomPercentage?: number | undefined; +}; +//# sourceMappingURL=latency-monitor.d.ts.map \ No newline at end of file diff --git a/dist/src/connection-manager/latency-monitor.d.ts.map b/dist/src/connection-manager/latency-monitor.d.ts.map new file mode 100644 index 0000000000..023fc944fc --- /dev/null +++ b/dist/src/connection-manager/latency-monitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"latency-monitor.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/latency-monitor.js"],"names":[],"mappings":";AAWA;;;;;;;;;;;;;GAaG;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH;IACE;;;OAGG;IACH,sIAsBC;IAjBC,+BAA2D;IAC3D,gCAA4D;IAC5D,6BAAoG;IACpG,6BAAyD;IAEzD,uCAEkC;IASlC,kCAA8B;IAGhC,cAyCC;IArCG,gDAAoC;IACpC,qDAGC;IAYH;;;;;;kBAA2C;IAMzC,8DAA6D;IAiBjE,aAEC;IAED;;;;OAIG;IACH,qBAYC;IALG,0CAAsF;IAO1F;;;;OAIG;IACH,oBASC;IANG,4CAAgC;IAQpC;;;;OAIG;IACH,qBAKC;IAED;;;;;OAKG;IACH,cAFa,aAAa,CAmBzB;IAED;;;;;OAKG;IACH,sBAgDC;IAED;;;;;;MAQC;CACF;;;;;;;;;;YApPa,MAAM;;;;WACN,MAAM;;;;WACN,MAAM;;;;WACN,MAAM;;;;cACN,MAAM"} \ No newline at end of file diff --git a/dist/src/connection-manager/visibility-change-emitter.d.ts b/dist/src/connection-manager/visibility-change-emitter.d.ts new file mode 100644 index 0000000000..39db9574b0 --- /dev/null +++ b/dist/src/connection-manager/visibility-change-emitter.d.ts @@ -0,0 +1,67 @@ +export = VisibilityChangeEmitter; +/** + * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter. + * + * Warning: This does not work on all browsers, but should work on all modern browsers + * + * @example + * + * const myVisibilityEmitter = new VisibilityChangeEmitter(); + * + * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => { + * if ( pageInFocus ){ + * // Page is in focus + * console.log('In focus'); + * } + * else { + * // Page is blurred + * console.log('Out of focus'); + * } + * }); + * // To access the visibility state directly, call: + * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible()); + */ +declare class VisibilityChangeEmitter extends EventEmitter { + /** + * Creates a VisibilityChangeEmitter + * + * @class + */ + constructor(); + /** + * document.hidden and document.visibilityChange are the two variables we need to check for; + * Since these variables are named differently in different browsers, this function sets + * the appropriate name based on the browser being used. Once executed, tha actual names of + * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange + * respectively + * + * @private + */ + private _initializeVisibilityVarNames; + _hidden: string | undefined; + _visibilityChange: string | undefined; + /** + * Adds an event listener on the document that listens to changes in document.visibilityChange + * (or whatever name by which the visibilityChange variable is known in the browser) + * + * @private + */ + private _addVisibilityChangeListener; + /** + * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and + * ```undefined``` if the page visibility API is not supported by the browser. + * + * @returns {boolean | void} whether the page is now visible or not (undefined is unknown) + */ + isVisible(): boolean | void; + /** + * The function that is called when document.visibilityChange has changed + * It emits an event called visibilityChange and sends the value of document.hidden as a + * parameter + * + * @private + */ + private _handleVisibilityChange; +} +import { EventEmitter } from "events"; +//# sourceMappingURL=visibility-change-emitter.d.ts.map \ No newline at end of file diff --git a/dist/src/connection-manager/visibility-change-emitter.d.ts.map b/dist/src/connection-manager/visibility-change-emitter.d.ts.map new file mode 100644 index 0000000000..f15731805d --- /dev/null +++ b/dist/src/connection-manager/visibility-change-emitter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"visibility-change-emitter.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/visibility-change-emitter.js"],"names":[],"mappings":";AAYA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH;IACE;;;;OAIG;IACH,cAQC;IAED;;;;;;;;OAQG;IACH,sCAkBC;IAFC,4BAAqB;IACrB,sCAAyC;IAG3C;;;;;OAKG;IACH,qCAQC;IAED;;;;;OAKG;IACH,aAFa,OAAO,GAAG,IAAI,CAQ1B;IAED;;;;;;OAMG;IACH,gCAKC;CACF"} \ No newline at end of file diff --git a/dist/src/constants.d.ts b/dist/src/constants.d.ts new file mode 100644 index 0000000000..324ccc6d1d --- /dev/null +++ b/dist/src/constants.d.ts @@ -0,0 +1,11 @@ +export const DIAL_TIMEOUT: number; +export const MAX_PARALLEL_DIALS: number; +export const MAX_PER_PEER_DIALS: number; +export const MAX_ADDRS_TO_DIAL: number; +export namespace METRICS { + const computeThrottleMaxQueueSize: number; + const computeThrottleTimeout: number; + const movingAverageIntervals: number[]; + const maxOldPeersRetention: number; +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/dist/src/constants.d.ts.map b/dist/src/constants.d.ts.map new file mode 100644 index 0000000000..485d4f8e57 --- /dev/null +++ b/dist/src/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/content-routing/index.d.ts b/dist/src/content-routing/index.d.ts new file mode 100644 index 0000000000..042384dbca --- /dev/null +++ b/dist/src/content-routing/index.d.ts @@ -0,0 +1,97 @@ +export = ContentRouting; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('multiformats/cid').CID} CID + * @typedef {import('libp2p-interfaces/src/content-routing/types').ContentRouting} ContentRoutingModule + */ +/** + * @typedef {Object} GetData + * @property {PeerId} from + * @property {Uint8Array} val + */ +declare class ContentRouting { + /** + * @class + * @param {import('..')} libp2p + */ + constructor(libp2p: import('..')); + libp2p: import(".."); + /** @type {ContentRoutingModule[]} */ + routers: ContentRoutingModule[]; + dht: any; + /** + * Iterates over all content routers in parallel to find providers of the given key. + * + * @param {CID} key - The CID key of the content to find + * @param {object} [options] + * @param {number} [options.timeout] - How long the query should run + * @param {number} [options.maxNumProviders] - maximum number of providers to find + * @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} + */ + findProviders(key: CID, options?: { + timeout?: number | undefined; + maxNumProviders?: number | undefined; + } | undefined): AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; + }>; + /** + * Iterates over all content routers in parallel to notify it is + * a provider of the given key. + * + * @param {CID} key - The CID key of the content to find + * @returns {Promise} + */ + provide(key: CID): Promise; + /** + * Store the given key/value pair in the DHT. + * + * @param {Uint8Array} key + * @param {Uint8Array} value + * @param {Object} [options] - put options + * @param {number} [options.minPeers] - minimum number of peers required to successfully put + * @returns {Promise} + */ + put(key: Uint8Array, value: Uint8Array, options?: { + minPeers?: number | undefined; + } | undefined): Promise; + /** + * Get the value to the given key. + * Times out after 1 minute by default. + * + * @param {Uint8Array} key + * @param {Object} [options] - get options + * @param {number} [options.timeout] - optional timeout (default: 60000) + * @returns {Promise} + */ + get(key: Uint8Array, options?: { + timeout?: number | undefined; + } | undefined): Promise; + /** + * Get the `n` values to the given key without sorting. + * + * @param {Uint8Array} key + * @param {number} nVals + * @param {Object} [options] - get options + * @param {number} [options.timeout] - optional timeout (default: 60000) + */ + getMany(key: Uint8Array, nVals: number, options?: { + timeout?: number | undefined; + } | undefined): AsyncGenerator<{ + from: any; + val: any; + }, void, unknown>; +} +declare namespace ContentRouting { + export { PeerId, Multiaddr, CID, ContentRoutingModule, GetData }; +} +type ContentRoutingModule = import('libp2p-interfaces/src/content-routing/types').ContentRouting; +type CID = import('multiformats/cid').CID; +type PeerId = import('peer-id'); +type Multiaddr = import('multiaddr').Multiaddr; +type GetData = { + from: PeerId; + val: Uint8Array; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/content-routing/index.d.ts.map b/dist/src/content-routing/index.d.ts.map new file mode 100644 index 0000000000..326c518029 --- /dev/null +++ b/dist/src/content-routing/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/content-routing/index.js"],"names":[],"mappings":";AAeA;;;;;GAKG;AAEH;;;;GAIG;AAEH;IACE;;;OAGG;IACH,oBAFW,OAAO,IAAI,CAAC,EAYtB;IATC,qBAAoB;IACpB,qCAAqC;IACrC,SADW,oBAAoB,EAAE,CACkB;IACnD,SAAsB;IAQxB;;;;;;;;OAQG;IACH,mBANW,GAAG;;;oBAID,cAAc;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC,CAgBlE;IAED;;;;;;OAMG;IACH,aAHW,GAAG,GACD,QAAQ,IAAI,CAAC,CAQzB;IAED;;;;;;;;OAQG;IACH,SANW,UAAU,SACV,UAAU;;oBAGR,QAAQ,IAAI,CAAC,CAQzB;IAED;;;;;;;;OAQG;IACH,SALW,UAAU;;oBAGR,QAAQ,OAAO,CAAC,CAc5B;IAED;;;;;;;OAOG;IACH,aALW,UAAU,SACV,MAAM;;;;;sBA8BhB;CACF;;;;4BA7IY,OAAO,6CAA6C,EAAE,cAAc;WADpE,OAAO,kBAAkB,EAAE,GAAG;cAF9B,OAAO,SAAS,CAAC;iBACjB,OAAO,WAAW,EAAE,SAAS;;UAO5B,MAAM;SACN,UAAU"} \ No newline at end of file diff --git a/dist/src/content-routing/utils.d.ts b/dist/src/content-routing/utils.d.ts new file mode 100644 index 0000000000..a58b4b8aca --- /dev/null +++ b/dist/src/content-routing/utils.d.ts @@ -0,0 +1,59 @@ +export type PeerId = import('peer-id'); +export type Multiaddr = import('multiaddr').Multiaddr; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('multiaddr').Multiaddr} Multiaddr + */ +/** + * Store the multiaddrs from every peer in the passed peer store + * + * @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source + * @param {import('../peer-store/types').PeerStore} peerStore + */ +export function storeAddresses(source: AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}>, peerStore: import('../peer-store/types').PeerStore): AsyncGenerator<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}, void, undefined>; +/** + * Filter peers by unique peer id + * + * @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source + */ +export function uniquePeers(source: AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}>): AsyncGenerator<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}, void, unknown>; +/** + * Require at least `min` peers to be yielded from `source` + * + * @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source + * @param {number} min + */ +export function requirePeers(source: AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}>, min?: number): AsyncGenerator<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}, void, unknown>; +/** + * If `max` is passed, only take that number of peers from the source + * otherwise take all the peers + * + * @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source + * @param {number} [max] + */ +export function maybeLimitSource(source: AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}>, max?: number | undefined): AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; +}>; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/dist/src/content-routing/utils.d.ts.map b/dist/src/content-routing/utils.d.ts.map new file mode 100644 index 0000000000..42307e97c5 --- /dev/null +++ b/dist/src/content-routing/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/content-routing/utils.js"],"names":[],"mappings":"qBAQa,OAAO,SAAS,CAAC;wBACjB,OAAO,WAAW,EAAE,SAAS;AAF1C;;;GAGG;AAEH;;;;;GAKG;AACH,uCAHW,cAAc;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,CAAA;CAAE,CAAC,aACtD,OAAO,qBAAqB,EAAE,SAAS;QADnB,MAAM;gBAAc,SAAS,EAAE;oBAU7D;AAED;;;;GAIG;AACH,oCAFW,cAAc;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,CAAA;CAAE,CAAC;QAAlC,MAAM;gBAAc,SAAS,EAAE;kBAgB7D;AAED;;;;;GAKG;AACH,qCAHW,cAAc;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,CAAA;CAAE,CAAC,QACtD,MAAM;QADc,MAAM;gBAAc,SAAS,EAAE;kBAe7D;AAED;;;;;;GAMG;AACH,yCAHW,cAAc;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,CAAA;CAAE,CAAC;QAAlC,MAAM;gBAAc,SAAS,EAAE;GAS7D"} \ No newline at end of file diff --git a/dist/src/dht/dht-content-routing.d.ts b/dist/src/dht/dht-content-routing.d.ts new file mode 100644 index 0000000000..6f56186ec6 --- /dev/null +++ b/dist/src/dht/dht-content-routing.d.ts @@ -0,0 +1,30 @@ +export type PeerId = import('peer-id'); +export type ContentRoutingModule = import('libp2p-interfaces/src/content-routing/types').ContentRouting; +export type CID = import('multiformats/cid').CID; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/content-routing/types').ContentRouting} ContentRoutingModule + * @typedef {import('multiformats/cid').CID} CID + */ +/** + * Wrapper class to convert events into returned values + * + * @implements {ContentRoutingModule} + */ +export class DHTContentRouting implements ContentRoutingModule { + /** + * @param {import('libp2p-kad-dht').DHT} dht + */ + constructor(dht: import('libp2p-kad-dht').DHT); + _dht: import("libp2p-kad-dht/dist/src/types").DHT; + /** + * @param {CID} cid + */ + provide(cid: CID): Promise; + /** + * @param {CID} cid + * @param {*} options + */ + findProviders(cid: CID, options: any): AsyncGenerator; +} +//# sourceMappingURL=dht-content-routing.d.ts.map \ No newline at end of file diff --git a/dist/src/dht/dht-content-routing.d.ts.map b/dist/src/dht/dht-content-routing.d.ts.map new file mode 100644 index 0000000000..1df7c25d67 --- /dev/null +++ b/dist/src/dht/dht-content-routing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dht-content-routing.d.ts","sourceRoot":"","sources":["../../../src/dht/dht-content-routing.js"],"names":[],"mappings":"qBAKa,OAAO,SAAS,CAAC;mCACjB,OAAO,6CAA6C,EAAE,cAAc;kBACpE,OAAO,kBAAkB,EAAE,GAAG;AAH3C;;;;GAIG;AAEH;;;;GAIG;AACH;IACE;;OAEG;IACH,iBAFW,OAAO,gBAAgB,EAAE,GAAG,EAItC;IADC,kDAAe;IAGjB;;OAEG;IACH,aAFW,GAAG,iBAIb;IAED;;;OAGG;IACH,mBAHW,GAAG,mGASb;CACF"} \ No newline at end of file diff --git a/dist/src/dht/dht-peer-routing.d.ts b/dist/src/dht/dht-peer-routing.d.ts new file mode 100644 index 0000000000..95b08907f1 --- /dev/null +++ b/dist/src/dht/dht-peer-routing.d.ts @@ -0,0 +1,29 @@ +export type PeerId = import('peer-id'); +export type PeerRoutingModule = import('libp2p-interfaces/src/peer-routing/types').PeerRouting; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/peer-routing/types').PeerRouting} PeerRoutingModule + */ +/** + * Wrapper class to convert events into returned values + * + * @implements {PeerRoutingModule} + */ +export class DHTPeerRouting implements PeerRoutingModule { + /** + * @param {import('libp2p-kad-dht').DHT} dht + */ + constructor(dht: import('libp2p-kad-dht').DHT); + _dht: import("libp2p-kad-dht/dist/src/types").DHT; + /** + * @param {PeerId} peerId + * @param {any} options + */ + findPeer(peerId: PeerId, options?: any): Promise; + /** + * @param {Uint8Array} key + * @param {any} options + */ + getClosestPeers(key: Uint8Array, options?: any): AsyncGenerator; +} +//# sourceMappingURL=dht-peer-routing.d.ts.map \ No newline at end of file diff --git a/dist/src/dht/dht-peer-routing.d.ts.map b/dist/src/dht/dht-peer-routing.d.ts.map new file mode 100644 index 0000000000..13e931c218 --- /dev/null +++ b/dist/src/dht/dht-peer-routing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dht-peer-routing.d.ts","sourceRoot":"","sources":["../../../src/dht/dht-peer-routing.js"],"names":[],"mappings":"qBAMa,OAAO,SAAS,CAAC;gCACjB,OAAO,0CAA0C,EAAE,WAAW;AAF3E;;;GAGG;AAEH;;;;GAIG;AACH;IACE;;OAEG;IACH,iBAFW,OAAO,gBAAgB,EAAE,GAAG,EAItC;IADC,kDAAe;IAGjB;;;OAGG;IACH,iBAHW,MAAM,YACN,GAAG,6DAUb;IAED;;;OAGG;IACH,qBAHW,UAAU,YACV,GAAG,qFAQb;CACF"} \ No newline at end of file diff --git a/dist/src/dialer/dial-request.d.ts b/dist/src/dialer/dial-request.d.ts new file mode 100644 index 0000000000..3f745b2997 --- /dev/null +++ b/dist/src/dialer/dial-request.d.ts @@ -0,0 +1,55 @@ +export = DialRequest; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('./')} Dialer + * @typedef {import('multiaddr').Multiaddr} Multiaddr + */ +/** + * @typedef {Object} DialOptions + * @property {AbortSignal} signal + * + * @typedef {Object} DialRequestOptions + * @property {Multiaddr[]} addrs + * @property {(m: Multiaddr, options: DialOptions) => Promise} dialAction + * @property {Dialer} dialer + */ +declare class DialRequest { + /** + * Manages running the `dialAction` on multiple provided `addrs` in parallel + * up to a maximum determined by the number of tokens returned + * from `dialer.getTokens`. Once a DialRequest is created, it can be + * started using `DialRequest.run(options)`. Once a single dial has succeeded, + * all other dials in the request will be cancelled. + * + * @class + * @param {DialRequestOptions} options + */ + constructor({ addrs, dialAction, dialer }: DialRequestOptions); + addrs: import("multiaddr").Multiaddr[]; + dialer: import("./"); + dialAction: (m: Multiaddr, options: DialOptions) => Promise; + /** + * @async + * @param {object} [options] + * @param {AbortSignal} [options.signal] - An AbortController signal + * @returns {Promise} + */ + run(options?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; +} +declare namespace DialRequest { + export { Connection, Dialer, Multiaddr, DialOptions, DialRequestOptions }; +} +type Connection = import("libp2p-interfaces/src/connection/connection"); +type DialRequestOptions = { + addrs: Multiaddr[]; + dialAction: (m: Multiaddr, options: DialOptions) => Promise; + dialer: Dialer; +}; +type Dialer = import('./'); +type Multiaddr = import('multiaddr').Multiaddr; +type DialOptions = { + signal: AbortSignal; +}; +//# sourceMappingURL=dial-request.d.ts.map \ No newline at end of file diff --git a/dist/src/dialer/dial-request.d.ts.map b/dist/src/dialer/dial-request.d.ts.map new file mode 100644 index 0000000000..e589b33b58 --- /dev/null +++ b/dist/src/dialer/dial-request.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dial-request.d.ts","sourceRoot":"","sources":["../../../src/dialer/dial-request.js"],"names":[],"mappings":";AAWA;;;;GAIG;AAEH;;;;;;;;GAQG;AAEH;IACE;;;;;;;;;OASG;IACH,2CAFW,kBAAkB,EAU5B;IAHC,uCAAkB;IAClB,qBAAoB;IACpB,gBAtBc,SAAS,WAAW,WAAW,KAAK,QAAQ,UAAU,CAAC,CAsBzC;IAG9B;;;;;OAKG;IACH;;oBAFa,QAAQ,UAAU,CAAC,CAoD/B;CACF;;;;;;WAnFa,SAAS,EAAE;oBACP,SAAS,WAAW,WAAW,KAAK,QAAQ,UAAU,CAAC;YAC3D,MAAM;;cAXP,OAAO,IAAI,CAAC;iBACZ,OAAO,WAAW,EAAE,SAAS;;YAK5B,WAAW"} \ No newline at end of file diff --git a/dist/src/dialer/index.d.ts b/dist/src/dialer/index.d.ts new file mode 100644 index 0000000000..e938272c0e --- /dev/null +++ b/dist/src/dialer/index.d.ts @@ -0,0 +1,182 @@ +export = Dialer; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('peer-id')} PeerId + * @typedef {import('../peer-store/types').PeerStore} PeerStore + * @typedef {import('../peer-store/types').Address} Address + * @typedef {import('../transport-manager')} TransportManager + * @typedef {import('../types').ConnectionGater} ConnectionGater + */ +/** + * @typedef {Object} DialerProperties + * @property {PeerStore} peerStore + * @property {TransportManager} transportManager + * @property {ConnectionGater} connectionGater + * + * @typedef {(addr:Multiaddr) => Promise} Resolver + * + * @typedef {Object} DialerOptions + * @property {(addresses: Address[]) => Address[]} [options.addressSorter = publicAddressesFirst] - Sort the known addresses of a peer before trying to dial. + * @property {number} [maxParallelDials = MAX_PARALLEL_DIALS] - Number of max concurrent dials. + * @property {number} [maxAddrsToDial = MAX_ADDRS_TO_DIAL] - Number of max addresses to dial for a given peer. + * @property {number} [maxDialsPerPeer = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer. + * @property {number} [dialTimeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take. + * @property {Record} [resolvers = {}] - multiaddr resolvers to use when dialing + * @property {import('../metrics')} [metrics] + * + * @typedef DialTarget + * @property {string} id + * @property {Multiaddr[]} addrs + * + * @typedef PendingDial + * @property {import('./dial-request')} dialRequest + * @property {import('timeout-abort-controller').TimeoutController} controller + * @property {Promise} promise + * @property {function():void} destroy + */ +declare class Dialer { + /** + * @class + * @param {DialerProperties & DialerOptions} options + */ + constructor({ transportManager, peerStore, connectionGater, addressSorter, maxParallelDials, maxAddrsToDial, dialTimeout, maxDialsPerPeer, resolvers, metrics }: DialerProperties & DialerOptions); + connectionGater: import("../types").ConnectionGater; + transportManager: import("../transport-manager"); + peerStore: import("../peer-store/types").PeerStore; + addressSorter: (addresses: Address[]) => Address[]; + maxParallelDials: number; + maxAddrsToDial: number; + timeout: number; + maxDialsPerPeer: number; + tokens: number[]; + /** @type {Map} */ + _pendingDials: Map; + /** @type {Map void, reject: (err: Error) => void}>} */ + _pendingDialTargets: Map void; + reject: (err: Error) => void; + }>; + /** + * Clears any pending dials + */ + destroy(): void; + /** + * Connects to a given `peer` by dialing all of its known addresses. + * The dial to the first address that is successfully able to upgrade a connection + * will be used. + * + * @param {PeerId|Multiaddr|string} peer - The peer to dial + * @param {object} [options] + * @param {AbortSignal} [options.signal] - An AbortController signal + * @returns {Promise} + */ + connectToPeer(peer: PeerId | Multiaddr | string, options?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + /** + * Connects to a given `peer` by dialing all of its known addresses. + * The dial to the first address that is successfully able to upgrade a connection + * will be used. + * + * @param {PeerId|Multiaddr|string} peer - The peer to dial + * @returns {Promise} + */ + _createCancellableDialTarget(peer: PeerId | Multiaddr | string): Promise; + /** + * Creates a DialTarget. The DialTarget is used to create and track + * the DialRequest to a given peer. + * If a multiaddr is received it should be the first address attempted. + * Multiaddrs not supported by the available transports will be filtered out. + * + * @private + * @param {PeerId|Multiaddr|string} peer - A PeerId or Multiaddr + * @returns {Promise} + */ + private _createDialTarget; + /** + * Creates a PendingDial that wraps the underlying DialRequest + * + * @private + * @param {DialTarget} dialTarget + * @param {object} [options] + * @param {AbortSignal} [options.signal] - An AbortController signal + * @returns {PendingDial} + */ + private _createPendingDial; + /** + * @param {number} num + */ + getTokens(num: number): number[]; + /** + * @param {number} token + */ + releaseToken(token: number): void; + /** + * Resolve multiaddr recursively. + * + * @param {Multiaddr} ma + * @returns {Promise} + */ + _resolve(ma: Multiaddr): Promise; + /** + * Resolve a given multiaddr. If this fails, an empty array will be returned + * + * @param {Multiaddr} ma + * @returns {Promise} + */ + _resolveRecord(ma: Multiaddr): Promise; +} +declare namespace Dialer { + export { Connection, PeerId, PeerStore, Address, TransportManager, ConnectionGater, DialerProperties, Resolver, DialerOptions, DialTarget, PendingDial }; +} +type PendingDial = { + dialRequest: import('./dial-request'); + controller: import('timeout-abort-controller').TimeoutController; + promise: Promise; + destroy: () => void; +}; +type PeerId = import('peer-id'); +import { Multiaddr } from "multiaddr"; +type Connection = import("libp2p-interfaces/src/connection/connection"); +type DialTarget = { + id: string; + addrs: Multiaddr[]; +}; +type DialerProperties = { + peerStore: PeerStore; + transportManager: TransportManager; + connectionGater: ConnectionGater; +}; +type DialerOptions = { + /** + * - Sort the known addresses of a peer before trying to dial. + */ + addressSorter?: ((addresses: Address[]) => Address[]) | undefined; + /** + * - Number of max concurrent dials. + */ + maxParallelDials?: number | undefined; + /** + * - Number of max addresses to dial for a given peer. + */ + maxAddrsToDial?: number | undefined; + /** + * - Number of max concurrent dials per peer. + */ + maxDialsPerPeer?: number | undefined; + /** + * - How long a dial attempt is allowed to take. + */ + dialTimeout?: number | undefined; + /** + * - multiaddr resolvers to use when dialing + */ + resolvers?: Record | undefined; + metrics?: import("../metrics") | undefined; +}; +type PeerStore = import('../peer-store/types').PeerStore; +type Address = import('../peer-store/types').Address; +type TransportManager = import('../transport-manager'); +type ConnectionGater = import('../types').ConnectionGater; +type Resolver = (addr: Multiaddr) => Promise; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/dialer/index.d.ts.map b/dist/src/dialer/index.d.ts.map new file mode 100644 index 0000000000..4be2f5c867 --- /dev/null +++ b/dist/src/dialer/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/dialer/index.js"],"names":[],"mappings":";AAgCA;;;;;;;GAOG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;IACE;;;OAGG;IACH,iKAFW,gBAAgB,GAAG,aAAa,EAyC1C;IA3BC,oDAAsC;IACtC,iDAAwC;IACxC,mDAA0B;IAC1B,2BAvCsB,OAAO,EAAE,KAAK,OAAO,EAAE,CAuCX;IAClC,yBAAwC;IACxC,uBAAoC;IACpC,gBAA0B;IAC1B,wBAAsC;IACtC,iBAAuE;IAEvE,uCAAuC;IACvC,eADW,IAAI,MAAM,EAAE,WAAW,CAAC,CAKjC;IAEF,0FAA0F;IAC1F;yBAD0C,GAAG,KAAK,IAAI;sBAAgB,KAAK,KAAK,IAAI;OAKlF;IAOJ;;OAEG;IACH,gBAcC;IAED;;;;;;;;;OASG;IACH,oBALW,MAAM,GAAC,SAAS,GAAC,MAAM;;oBAGrB,QAAQ,UAAU,CAAC,CA8B/B;IAED;;;;;;;OAOG;IACH,mCAHW,MAAM,GAAC,SAAS,GAAC,MAAM,GACrB,QAAQ,UAAU,CAAC,CAmB/B;IAED;;;;;;;;;OASG;IACH,0BAyCC;IAED;;;;;;;;OAQG;IACH,2BA0CC;IAED;;OAEG;IACH,eAFW,MAAM,YAOhB;IAED;;OAEG;IACH,oBAFW,MAAM,QAOhB;IAED;;;;;OAKG;IACH,aAHW,SAAS,GACP,QAAQ,SAAS,EAAE,CAAC,CAwBhC;IAED;;;;;OAKG;IACH,mBAHW,SAAS,GACP,QAAQ,SAAS,EAAE,CAAC,CAWhC;CACF;;;;;iBAtTa,OAAO,gBAAgB,CAAC;gBACxB,OAAO,0BAA0B,EAAE,iBAAiB;aACpD,QAAQ,UAAU,CAAC;mBACR,IAAI;;cAhChB,OAAO,SAAS,CAAC;;;;QAyBhB,MAAM;WACN,SAAS,EAAE;;;eAjBX,SAAS;sBACT,gBAAgB;qBAChB,eAAe;;;;;;iCAKH,OAAO,EAAE,KAAK,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;iBAfpC,OAAO,qBAAqB,EAAE,SAAS;eACvC,OAAO,qBAAqB,EAAE,OAAO;wBACrC,OAAO,sBAAsB,CAAC;uBAC9B,OAAO,UAAU,EAAE,eAAe;uBAS5B,SAAS,KAAK,QAAQ,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/src/errors.d.ts b/dist/src/errors.d.ts new file mode 100644 index 0000000000..93917ae8e4 --- /dev/null +++ b/dist/src/errors.d.ts @@ -0,0 +1,66 @@ +export namespace messages { + const NOT_STARTED_YET: string; + const DHT_DISABLED: string; + const CONN_ENCRYPTION_REQUIRED: string; + const NOT_FOUND: string; +} +export namespace codes { + const DHT_DISABLED_1: string; + export { DHT_DISABLED_1 as DHT_DISABLED }; + export const PUBSUB_NOT_STARTED: string; + export const DHT_NOT_STARTED: string; + const CONN_ENCRYPTION_REQUIRED_1: string; + export { CONN_ENCRYPTION_REQUIRED_1 as CONN_ENCRYPTION_REQUIRED }; + export const ERR_PEER_DIAL_INTERCEPTED: string; + export const ERR_CONNECTION_INTERCEPTED: string; + export const ERR_INVALID_PROTOCOLS_FOR_STREAM: string; + export const ERR_CONNECTION_ENDED: string; + export const ERR_CONNECTION_FAILED: string; + export const ERR_NODE_NOT_STARTED: string; + export const ERR_ALREADY_ABORTED: string; + export const ERR_TOO_MANY_ADDRESSES: string; + export const ERR_NO_VALID_ADDRESSES: string; + export const ERR_RELAYED_DIAL: string; + export const ERR_DIALED_SELF: string; + export const ERR_DISCOVERED_SELF: string; + export const ERR_DUPLICATE_TRANSPORT: string; + export const ERR_ENCRYPTION_FAILED: string; + export const ERR_HOP_REQUEST_FAILED: string; + export const ERR_INVALID_KEY: string; + export const ERR_INVALID_MESSAGE: string; + export const ERR_INVALID_PARAMETERS: string; + export const ERR_INVALID_PEER: string; + export const ERR_MUXER_UNAVAILABLE: string; + export const ERR_NOT_FOUND: string; + export const ERR_TIMEOUT: string; + export const ERR_TRANSPORT_UNAVAILABLE: string; + export const ERR_TRANSPORT_DIAL_FAILED: string; + export const ERR_UNSUPPORTED_PROTOCOL: string; + export const ERR_INVALID_MULTIADDR: string; + export const ERR_SIGNATURE_NOT_VALID: string; + export const ERR_FIND_SELF: string; + export const ERR_NO_ROUTERS_AVAILABLE: string; + export const ERR_CONNECTION_NOT_MULTIPLEXED: string; + export const ERR_NO_DIAL_TOKENS: string; + export const ERR_KEYCHAIN_REQUIRED: string; + export const ERR_INVALID_CMS: string; + export const ERR_MISSING_KEYS: string; + export const ERR_NO_KEY: string; + export const ERR_INVALID_KEY_NAME: string; + export const ERR_INVALID_KEY_TYPE: string; + export const ERR_KEY_ALREADY_EXISTS: string; + export const ERR_INVALID_KEY_SIZE: string; + export const ERR_KEY_NOT_FOUND: string; + export const ERR_OLD_KEY_NAME_INVALID: string; + export const ERR_NEW_KEY_NAME_INVALID: string; + export const ERR_PASSWORD_REQUIRED: string; + export const ERR_PEM_REQUIRED: string; + export const ERR_CANNOT_READ_KEY: string; + export const ERR_MISSING_PRIVATE_KEY: string; + export const ERR_INVALID_OLD_PASS_TYPE: string; + export const ERR_INVALID_NEW_PASS_TYPE: string; + export const ERR_INVALID_PASS_LENGTH: string; + export const ERR_NOT_IMPLEMENTED: string; + export const ERR_WRONG_PING_ACK: string; +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/src/errors.d.ts.map b/dist/src/errors.d.ts.map new file mode 100644 index 0000000000..80c209d6f9 --- /dev/null +++ b/dist/src/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/fetch/constants.d.ts b/dist/src/fetch/constants.d.ts new file mode 100644 index 0000000000..fbd049a06a --- /dev/null +++ b/dist/src/fetch/constants.d.ts @@ -0,0 +1,2 @@ +export const PROTOCOL: string; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/dist/src/fetch/constants.d.ts.map b/dist/src/fetch/constants.d.ts.map new file mode 100644 index 0000000000..854f36e741 --- /dev/null +++ b/dist/src/fetch/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/fetch/constants.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/fetch/index.d.ts b/dist/src/fetch/index.d.ts new file mode 100644 index 0000000000..333415604c --- /dev/null +++ b/dist/src/fetch/index.d.ts @@ -0,0 +1,76 @@ +export = FetchProtocol; +/** + * @typedef {import('../')} Libp2p + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + * @typedef {(key: string) => Promise} LookupFunction + */ +/** + * A simple libp2p protocol for requesting a value corresponding to a key from a peer. + * Developers can register one or more lookup function for retrieving the value corresponding to + * a given key. Each lookup function must act on a distinct part of the overall key space, defined + * by a fixed prefix that all keys that should be routed to that lookup function will start with. + */ +declare class FetchProtocol { + /** + * @param {Libp2p} libp2p + */ + constructor(libp2p: Libp2p); + _lookupFunctions: Map; + _libp2p: import("../"); + /** + * Invoked when a fetch request is received. Reads the request message off the given stream and + * responds based on looking up the key in the request via the lookup callback that corresponds + * to the key's prefix. + * + * @param {object} options + * @param {MuxedStream} options.stream + * @param {string} options.protocol + */ + handleMessage(options: { + stream: MuxedStream; + protocol: string; + }): Promise; + /** + * Sends a request to fetch the value associated with the given key from the given peer. + * + * @param {PeerId|Multiaddr} peer + * @param {string} key + * @returns {Promise} + */ + fetch(peer: PeerId | Multiaddr, key: string): Promise; + /** + * Given a key, finds the appropriate function for looking up its corresponding value, based on + * the key's prefix. + * + * @param {string} key + */ + _getLookupFunction(key: string): any; + /** + * Registers a new lookup callback that can map keys to values, for a given set of keys that + * share the same prefix. + * + * @param {string} prefix + * @param {LookupFunction} lookup + */ + registerLookupFunction(prefix: string, lookup: LookupFunction): void; + /** + * Registers a new lookup callback that can map keys to values, for a given set of keys that + * share the same prefix. + * + * @param {string} prefix + * @param {LookupFunction} [lookup] + */ + unregisterLookupFunction(prefix: string, lookup?: LookupFunction | undefined): void; +} +declare namespace FetchProtocol { + export { PROTOCOL, Libp2p, Multiaddr, PeerId, MuxedStream, LookupFunction }; +} +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +type PeerId = import('peer-id'); +type Multiaddr = import('multiaddr').Multiaddr; +type LookupFunction = (key: string) => Promise; +type Libp2p = import('../'); +import { PROTOCOL } from "./constants"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/fetch/index.d.ts.map b/dist/src/fetch/index.d.ts.map new file mode 100644 index 0000000000..0020d917be --- /dev/null +++ b/dist/src/fetch/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/fetch/index.js"],"names":[],"mappings":";AAcA;;;;;;GAMG;AAEH;;;;;GAKG;AACH;IACE;;OAEG;IACH,oBAFW,MAAM,EAMhB;IAHC,gCAAiC;IACjC,uBAAqB;IA0CvB;;;;;;;;OAQG;IACH;QAHgC,MAAM,EAA3B,WAAW;QACK,QAAQ,EAAxB,MAAM;sBAsBhB;IAnED;;;;;;OAMG;IACH,YAJW,MAAM,GAAC,SAAS,OAChB,MAAM,GACJ,QAAQ,UAAU,GAAG,IAAI,CAAC,CA+BtC;IAiCD;;;;;OAKG;IACH,wBAFW,MAAM,OAShB;IAED;;;;;;OAMG;IACH,+BAHW,MAAM,gCAQhB;IAED;;;;;;OAMG;IACH,iCAHW,MAAM,6CAahB;CACF;;;;mBAxIY,OAAO,0CAA0C,EAAE,WAAW;cAD9D,OAAO,SAAS,CAAC;iBADjB,OAAO,WAAW,EAAE,SAAS;4BAGvB,MAAM,KAAK,QAAQ,UAAU,GAAG,IAAI,CAAC;cAJ3C,OAAO,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/src/fetch/proto.d.ts b/dist/src/fetch/proto.d.ts new file mode 100644 index 0000000000..bf022f516c --- /dev/null +++ b/dist/src/fetch/proto.d.ts @@ -0,0 +1,134 @@ +import * as $protobuf from "protobufjs"; +/** Properties of a FetchRequest. */ +export interface IFetchRequest { + + /** FetchRequest identifier */ + identifier?: (string|null); +} + +/** Represents a FetchRequest. */ +export class FetchRequest implements IFetchRequest { + + /** + * Constructs a new FetchRequest. + * @param [p] Properties to set + */ + constructor(p?: IFetchRequest); + + /** FetchRequest identifier. */ + public identifier: string; + + /** + * Encodes the specified FetchRequest message. Does not implicitly {@link FetchRequest.verify|verify} messages. + * @param m FetchRequest message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IFetchRequest, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FetchRequest message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns FetchRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchRequest; + + /** + * Creates a FetchRequest message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns FetchRequest + */ + public static fromObject(d: { [k: string]: any }): FetchRequest; + + /** + * Creates a plain object from a FetchRequest message. Also converts values to other types if specified. + * @param m FetchRequest + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: FetchRequest, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FetchRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Properties of a FetchResponse. */ +export interface IFetchResponse { + + /** FetchResponse status */ + status?: (FetchResponse.StatusCode|null); + + /** FetchResponse data */ + data?: (Uint8Array|null); +} + +/** Represents a FetchResponse. */ +export class FetchResponse implements IFetchResponse { + + /** + * Constructs a new FetchResponse. + * @param [p] Properties to set + */ + constructor(p?: IFetchResponse); + + /** FetchResponse status. */ + public status: FetchResponse.StatusCode; + + /** FetchResponse data. */ + public data: Uint8Array; + + /** + * Encodes the specified FetchResponse message. Does not implicitly {@link FetchResponse.verify|verify} messages. + * @param m FetchResponse message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IFetchResponse, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FetchResponse message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns FetchResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchResponse; + + /** + * Creates a FetchResponse message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns FetchResponse + */ + public static fromObject(d: { [k: string]: any }): FetchResponse; + + /** + * Creates a plain object from a FetchResponse message. Also converts values to other types if specified. + * @param m FetchResponse + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: FetchResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FetchResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +export namespace FetchResponse { + + /** StatusCode enum. */ + enum StatusCode { + OK = 0, + NOT_FOUND = 1, + ERROR = 2 + } +} diff --git a/dist/src/get-peer.d.ts b/dist/src/get-peer.d.ts new file mode 100644 index 0000000000..c9643ac529 --- /dev/null +++ b/dist/src/get-peer.d.ts @@ -0,0 +1,15 @@ +export = getPeer; +/** + * Converts the given `peer` to a `Peer` object. + * If a multiaddr is received, the addressBook is updated. + * + * @param {PeerId|Multiaddr|string} peer + * @returns {{ id: PeerId, multiaddrs: Multiaddr[]|undefined }} + */ +declare function getPeer(peer: PeerId | Multiaddr | string): { + id: PeerId; + multiaddrs: Multiaddr[] | undefined; +}; +import PeerId = require("peer-id"); +import { Multiaddr } from "multiaddr"; +//# sourceMappingURL=get-peer.d.ts.map \ No newline at end of file diff --git a/dist/src/get-peer.d.ts.map b/dist/src/get-peer.d.ts.map new file mode 100644 index 0000000000..6efefc51af --- /dev/null +++ b/dist/src/get-peer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"get-peer.d.ts","sourceRoot":"","sources":["../../src/get-peer.js"],"names":[],"mappings":";AAQA;;;;;;GAMG;AACH,+BAHW,MAAM,GAAC,SAAS,GAAC,MAAM,GACrB;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,GAAC,SAAS,CAAA;CAAE,CAiC7D"} \ No newline at end of file diff --git a/dist/src/identify/consts.d.ts b/dist/src/identify/consts.d.ts new file mode 100644 index 0000000000..db99794e59 --- /dev/null +++ b/dist/src/identify/consts.d.ts @@ -0,0 +1,10 @@ +export var PROTOCOL_VERSION: string; +export var AGENT_VERSION: string; +export var MULTICODEC_IDENTIFY: string; +export var MULTICODEC_IDENTIFY_PUSH: string; +export var IDENTIFY_PROTOCOL_VERSION: string; +export var MULTICODEC_IDENTIFY_PROTOCOL_NAME: string; +export var MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME: string; +export var MULTICODEC_IDENTIFY_PROTOCOL_VERSION: string; +export var MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION: string; +//# sourceMappingURL=consts.d.ts.map \ No newline at end of file diff --git a/dist/src/identify/consts.d.ts.map b/dist/src/identify/consts.d.ts.map new file mode 100644 index 0000000000..ed5f1691df --- /dev/null +++ b/dist/src/identify/consts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/identify/consts.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/identify/index.d.ts b/dist/src/identify/index.d.ts new file mode 100644 index 0000000000..c11781441c --- /dev/null +++ b/dist/src/identify/index.d.ts @@ -0,0 +1,120 @@ +export = IdentifyService; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + */ +/** + * @typedef {Object} HostProperties + * @property {string} agentVersion + */ +declare class IdentifyService { + /** + * @param {import('../')} libp2p + */ + static getProtocolStr(libp2p: import('../')): { + identifyProtocolStr: string; + identifyPushProtocolStr: string; + }; + /** + * Takes the `addr` and converts it to a Multiaddr if possible + * + * @param {Uint8Array | string} addr + * @returns {Multiaddr|null} + */ + static getCleanMultiaddr(addr: Uint8Array | string): Multiaddr | null; + /** + * @class + * @param {Object} options + * @param {import('../')} options.libp2p + */ + constructor({ libp2p }: { + libp2p: import('../'); + }); + _libp2p: import("../"); + peerStore: import("../peer-store/types").PeerStore; + addressManager: import("../address-manager"); + connectionManager: import("../connection-manager"); + peerId: PeerId; + /** + * A handler to register with Libp2p to process identify messages. + * + * @param {Object} options + * @param {Connection} options.connection + * @param {MuxedStream} options.stream + * @param {string} options.protocol + * @returns {Promise|undefined} + */ + handleMessage({ connection, stream, protocol }: { + connection: Connection; + stream: MuxedStream; + protocol: string; + }): Promise | undefined; + identifyProtocolStr: string; + identifyPushProtocolStr: string; + _host: { + agentVersion: string; + protocolVersion: string; + }; + start(): Promise; + stop(): Promise; + /** + * Send an Identify Push update to the list of connections + * + * @param {Connection[]} connections + * @returns {Promise} + */ + push(connections: Connection[]): Promise; + /** + * Calls `push` for all peers in the `peerStore` that are connected + */ + pushToPeerStore(): Promise; + /** + * Requests the `Identify` message from peer associated with the given `connection`. + * If the identified peer does not match the `PeerId` associated with the connection, + * an error will be thrown. + * + * @async + * @param {Connection} connection + * @returns {Promise} + */ + identify(connection: Connection): Promise; + /** + * Sends the `Identify` response with the Signed Peer Record + * to the requesting peer over the given `connection` + * + * @private + * @param {Object} options + * @param {MuxedStream} options.stream + * @param {Connection} options.connection + * @returns {Promise} + */ + private _handleIdentify; + /** + * Reads the Identify Push message from the given `connection` + * + * @private + * @param {object} options + * @param {MuxedStream} options.stream + * @param {Connection} options.connection + * @returns {Promise} + */ + private _handlePush; +} +declare namespace IdentifyService { + export { multicodecs, Message as Messsage, Connection, MuxedStream, HostProperties }; +} +import PeerId = require("peer-id"); +type Connection = import("libp2p-interfaces/src/connection/connection"); +import { Multiaddr } from "multiaddr"; +declare namespace multicodecs { + export { MULTICODEC_IDENTIFY as IDENTIFY }; + export { MULTICODEC_IDENTIFY_PUSH as IDENTIFY_PUSH }; +} +import Message = require("./message"); +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +type HostProperties = { + agentVersion: string; +}; +import { MULTICODEC_IDENTIFY } from "./consts"; +import { MULTICODEC_IDENTIFY_PUSH } from "./consts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/identify/index.d.ts.map b/dist/src/identify/index.d.ts.map new file mode 100644 index 0000000000..81f7f07251 --- /dev/null +++ b/dist/src/identify/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/identify/index.js"],"names":[],"mappings":";AAkCA;;;GAGG;AAEH;;;GAGG;AAEH;IACE;;OAEG;IACH,8BAFW,OAAO,KAAK,CAAC;;;MAOvB;IA2SD;;;;;OAKG;IACH,+BAHW,UAAU,GAAG,MAAM,GACjB,SAAS,GAAC,IAAI,CAW1B;IAxTD;;;;OAIG;IACH;QAFkC,MAAM,EAA7B,OAAO,KAAK,CAAC;OAuCvB;IApCC,uBAAqB;IACrB,mDAAiC;IACjC,6CAA2C;IAC3C,mDAAiD;IACjD,eAA2B;IA6K7B;;;;;;;;OAQG;IACH;oBALW,UAAU;gBACV,WAAW;kBACX,MAAM;QACJ,QAAQ,IAAI,CAAC,GAAC,SAAS,CAWnC;IA1LC,4BAA0D;IAC1D,gCAAkE;IAGlE;sBAjCU,MAAM;;MAoCf;IAsBH,uBAGC;IAED,sBAEC;IAED;;;;;OAKG;IACH,kBAHW,UAAU,EAAE,GACV,QAAQ,IAAI,EAAE,CAAC,CA4B3B;IAED;;OAEG;IACH,iCAeC;IAED;;;;;;;;OAQG;IACH,qBAHW,UAAU,GACR,QAAQ,IAAI,CAAC,CAmEzB;IAsBD;;;;;;;;;OASG;IACH,wBA6BC;IAED;;;;;;;;OAQG;IACH,oBA0CC;CAkBF;;;;;;;;;;;;mBA5UY,OAAO,0CAA0C,EAAE,WAAW;;kBAK7D,MAAM"} \ No newline at end of file diff --git a/dist/src/identify/message.d.ts b/dist/src/identify/message.d.ts new file mode 100644 index 0000000000..ba49c586aa --- /dev/null +++ b/dist/src/identify/message.d.ts @@ -0,0 +1,95 @@ +import * as $protobuf from "protobufjs"; +/** Properties of an Identify. */ +export interface IIdentify { + + /** Identify protocolVersion */ + protocolVersion?: (string|null); + + /** Identify agentVersion */ + agentVersion?: (string|null); + + /** Identify publicKey */ + publicKey?: (Uint8Array|null); + + /** Identify listenAddrs */ + listenAddrs?: (Uint8Array[]|null); + + /** Identify observedAddr */ + observedAddr?: (Uint8Array|null); + + /** Identify protocols */ + protocols?: (string[]|null); + + /** Identify signedPeerRecord */ + signedPeerRecord?: (Uint8Array|null); +} + +/** Represents an Identify. */ +export class Identify implements IIdentify { + + /** + * Constructs a new Identify. + * @param [p] Properties to set + */ + constructor(p?: IIdentify); + + /** Identify protocolVersion. */ + public protocolVersion: string; + + /** Identify agentVersion. */ + public agentVersion: string; + + /** Identify publicKey. */ + public publicKey: Uint8Array; + + /** Identify listenAddrs. */ + public listenAddrs: Uint8Array[]; + + /** Identify observedAddr. */ + public observedAddr: Uint8Array; + + /** Identify protocols. */ + public protocols: string[]; + + /** Identify signedPeerRecord. */ + public signedPeerRecord: Uint8Array; + + /** + * Encodes the specified Identify message. Does not implicitly {@link Identify.verify|verify} messages. + * @param m Identify message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IIdentify, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Identify message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Identify + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Identify; + + /** + * Creates an Identify message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Identify + */ + public static fromObject(d: { [k: string]: any }): Identify; + + /** + * Creates a plain object from an Identify message. Also converts values to other types if specified. + * @param m Identify + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Identify, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Identify to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} diff --git a/dist/src/index.d.ts b/dist/src/index.d.ts new file mode 100644 index 0000000000..d907d522f3 --- /dev/null +++ b/dist/src/index.d.ts @@ -0,0 +1,534 @@ +export = Libp2p; +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + * @typedef {import('libp2p-interfaces/src/transport/types').TransportFactory} TransportFactory + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxerFactory} MuxerFactory + * @typedef {import('libp2p-interfaces/src/content-routing/types').ContentRouting} ContentRoutingModule + * @typedef {import('libp2p-interfaces/src/peer-discovery/types').PeerDiscoveryFactory} PeerDiscoveryFactory + * @typedef {import('libp2p-interfaces/src/peer-routing/types').PeerRouting} PeerRoutingModule + * @typedef {import('libp2p-interfaces/src/crypto/types').Crypto} Crypto + * @typedef {import('libp2p-interfaces/src/pubsub')} Pubsub + * @typedef {import('libp2p-interfaces/src/pubsub').PubsubOptions} PubsubOptions + * @typedef {import('interface-datastore').Datastore} Datastore + * @typedef {import('./pnet')} Protector + * @typedef {import('./types').ConnectionGater} ConnectionGater + * @typedef {Object} PersistentPeerStoreOptions + * @property {number} [threshold] + */ +/** + * @typedef {Object} HandlerProps + * @property {Connection} connection + * @property {MuxedStream} stream + * @property {string} protocol + * + * @typedef {Object} DhtOptions + * @property {boolean} [enabled = false] + * @property {number} [kBucketSize = 20] + * @property {boolean} [clientMode] + * @property {import('libp2p-interfaces/src/types').DhtSelectors} [selectors] + * @property {import('libp2p-interfaces/src/types').DhtValidators} [validators] + * + * @typedef {Object} KeychainOptions + * @property {Datastore} [datastore] + * + * @typedef {Object} PeerStoreOptions + * @property {boolean} persistence + * + * @typedef {Object} PubsubLocalOptions + * @property {boolean} enabled + * + * @typedef {Object} MetricsOptions + * @property {boolean} enabled + * + * @typedef {Object} RelayOptions + * @property {boolean} [enabled = true] + * @property {import('./circuit').RelayAdvertiseOptions} [advertise] + * @property {import('./circuit').HopOptions} [hop] + * @property {import('./circuit').AutoRelayOptions} [autoRelay] + * + * @typedef {Object} Libp2pConfig + * @property {DhtOptions} [dht] dht module options + * @property {import('./nat-manager').NatManagerOptions} [nat] + * @property {Record} [peerDiscovery] + * @property {PubsubLocalOptions & PubsubOptions} [pubsub] pubsub module options + * @property {RelayOptions} [relay] + * @property {Record} [transport] transport options indexed by transport key + * + * @typedef {Object} Libp2pModules + * @property {TransportFactory[]} transport + * @property {MuxerFactory[]} streamMuxer + * @property {Crypto[]} connEncryption + * @property {PeerDiscoveryFactory[]} [peerDiscovery] + * @property {PeerRoutingModule[]} [peerRouting] + * @property {ContentRoutingModule[]} [contentRouting] + * @property {Object} [dht] + * @property {{new(...args: any[]): Pubsub}} [pubsub] + * @property {Protector} [connProtector] + * + * @typedef {Object} Libp2pOptions + * @property {Libp2pModules} modules libp2p modules to use + * @property {import('./address-manager').AddressManagerOptions} [addresses] + * @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager] + * @property {Partial} [connectionGater] + * @property {Datastore} [datastore] + * @property {import('./dialer').DialerOptions} [dialer] + * @property {import('./identify/index').HostProperties} [host] libp2p host + * @property {KeychainOptions & import('./keychain/index').KeychainOptions} [keychain] + * @property {MetricsOptions & import('./metrics').MetricsOptions} [metrics] + * @property {import('./peer-routing').PeerRoutingOptions} [peerRouting] + * @property {PeerStoreOptions} [peerStore] + * @property {import('./transport-manager').TransportManagerOptions} [transportManager] + * @property {Libp2pConfig} [config] + * + * @typedef {Object} constructorOptions + * @property {PeerId} peerId + * + * @typedef {Object} CreateOptions + * @property {PeerId} [peerId] + * + * @extends {EventEmitter} + * @fires Libp2p#error Emitted when an error occurs + * @fires Libp2p#peer:discovery Emitted when a peer is discovered + */ +declare class Libp2p extends EventEmitter { + /** + * Like `new Libp2p(options)` except it will create a `PeerId` + * instance if one is not provided in options. + * + * @param {Libp2pOptions & CreateOptions} options - Libp2p configuration options + * @returns {Promise} + */ + static create(options: Libp2pOptions & CreateOptions): Promise; + /** + * Libp2p node. + * + * @class + * @param {Libp2pOptions & constructorOptions} _options + */ + constructor(_options: Libp2pOptions & constructorOptions); + _options: { + addresses: { + listen: never[]; + announce: never[]; + noAnnounce: never[]; + announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]; + }; + connectionManager: { + minConnections: number; + }; + connectionGater: {}; + transportManager: { + faultTolerance: number; + }; + dialer: { + maxParallelDials: number; + maxDialsPerPeer: number; + dialTimeout: number; + resolvers: { + dnsaddr: any; + }; + addressSorter: typeof import("libp2p-utils/src/address-sort").publicAddressesFirst; + }; + host: { + agentVersion: string; + }; + metrics: { + enabled: boolean; + }; + peerStore: { + persistence: boolean; + threshold: number; + }; + peerRouting: { + refreshManager: { + enabled: boolean; + interval: number; + bootDelay: number; + }; + }; + config: { + protocolPrefix: string; + dht: { + enabled: boolean; + kBucketSize: number; + }; + nat: { + enabled: boolean; + ttl: number; + keepAlive: boolean; + gateway: null; + externalIp: null; + pmp: { + enabled: boolean; + }; + }; + peerDiscovery: { + autoDial: boolean; + }; + pubsub: { + enabled: boolean; + }; + relay: { + enabled: boolean; + advertise: { + bootDelay: number; + enabled: boolean; + ttl: number; + }; + hop: { + enabled: boolean; + active: boolean; + }; + autoRelay: { + enabled: boolean; + maxListeners: number; + }; + }; + transport: {}; + }; + } & Libp2pOptions & constructorOptions; + /** @type {PeerId} */ + peerId: PeerId; + datastore: import("interface-datastore").Datastore | undefined; + metrics: Metrics | undefined; + /** @type {ConnectionGater} */ + connectionGater: ConnectionGater; + /** @type {import('./peer-store/types').PeerStore} */ + peerStore: import('./peer-store/types').PeerStore; + addresses: { + listen: never[]; + announce: never[]; + noAnnounce: never[]; + announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]; + } & AddressManager.AddressManagerOptions; + addressManager: AddressManager; + _modules: Libp2pModules; + _config: { + protocolPrefix: string; + dht: { + enabled: boolean; + kBucketSize: number; + }; + nat: { + enabled: boolean; + ttl: number; + keepAlive: boolean; + gateway: null; + externalIp: null; + pmp: { + enabled: boolean; + }; + }; + peerDiscovery: { + autoDial: boolean; + }; + pubsub: { + enabled: boolean; + }; + relay: { + enabled: boolean; + advertise: { + bootDelay: number; + enabled: boolean; + ttl: number; + }; + hop: { + enabled: boolean; + active: boolean; + }; + autoRelay: { + enabled: boolean; + maxListeners: number; + }; + }; + transport: {}; + } & Libp2pConfig; + _transport: any[]; + _discovery: Map; + connectionManager: ConnectionManager; + _autodialler: AutoDialler; + keychain: Keychain | undefined; + upgrader: Upgrader; + transportManager: TransportManager; + natManager: NatManager; + registrar: Registrar; + /** + * Registers the `handler` for each protocol + * + * @param {string[]|string} protocols + * @param {(props: HandlerProps) => void} handler + */ + handle(protocols: string[] | string, handler: (props: HandlerProps) => void): Promise; + dialer: Dialer; + relay: Relay | undefined; + identifyService: IdentifyService | undefined; + _dht: any; + /** @type {Pubsub} */ + pubsub: import("libp2p-interfaces/src/pubsub"); + peerRouting: PeerRouting; + contentRouting: ContentRouting; + /** + * Called whenever peer discovery services emit `peer` events. + * Known peers may be emitted. + * + * @private + * @param {{ id: PeerId, multiaddrs: Multiaddr[], protocols: string[] }} peer + */ + private _onDiscoveryPeer; + fetchService: FetchService; + pingService: PingService; + /** + * Starts the libp2p node and all its subsystems + * + * @returns {Promise} + */ + start(): Promise; + /** + * Stop the libp2p node by closing its listeners and open connections + * + * @async + * @returns {Promise} + */ + stop(): Promise; + _isStarted: boolean | undefined; + /** + * Load keychain keys from the datastore. + * Imports the private key as 'self', if needed. + * + * @async + * @returns {Promise} + */ + loadKeychain(): Promise; + isStarted(): boolean | undefined; + /** + * Gets a Map of the current connections. The keys are the stringified + * `PeerId` of the peer. The value is an array of Connections to that peer. + * + * @returns {Map} + */ + get connections(): Map; + /** + * Dials to the provided peer. If successful, the known metadata of the + * peer will be added to the nodes `peerStore` + * + * @param {PeerId|Multiaddr|string} peer - The peer to dial + * @param {object} [options] + * @param {AbortSignal} [options.signal] + * @returns {Promise} + */ + dial(peer: PeerId | Multiaddr | string, options?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + /** + * Dials to the provided peer and tries to handshake with the given protocols in order. + * If successful, the known metadata of the peer will be added to the nodes `peerStore`, + * and the `MuxedStream` will be returned together with the successful negotiated protocol. + * + * @async + * @param {PeerId|Multiaddr|string} peer - The peer to dial + * @param {string[]|string} protocols + * @param {object} [options] + * @param {AbortSignal} [options.signal] + */ + dialProtocol(peer: PeerId | Multiaddr | string, protocols: string[] | string, options?: { + signal?: AbortSignal | undefined; + } | undefined): Promise<{ + stream: import("libp2p-interfaces/src/stream-muxer/types").MuxedStream; + protocol: string; + }>; + /** + * @async + * @param {PeerId|Multiaddr|string} peer - The peer to dial + * @param {object} [options] + * @returns {Promise} + */ + _dial(peer: PeerId | Multiaddr | string, options?: object | undefined): Promise; + /** + * Get a deduplicated list of peer advertising multiaddrs by concatenating + * the listen addresses used by transports with any configured + * announce addresses as well as observed addresses reported by peers. + * + * If Announce addrs are specified, configured listen addresses will be + * ignored though observed addresses will still be included. + * + * @returns {Multiaddr[]} + */ + get multiaddrs(): Multiaddr[]; + /** + * Disconnects all connections to the given `peer` + * + * @param {PeerId|Multiaddr|string} peer - the peer to close connections to + * @returns {Promise} + */ + hangUp(peer: PeerId | Multiaddr | string): Promise; + /** + * Sends a request to fetch the value associated with the given key from the given peer. + * + * @param {PeerId|Multiaddr} peer + * @param {string} key + * @returns {Promise} + */ + fetch(peer: PeerId | Multiaddr, key: string): Promise; + /** + * Pings the given peer in order to obtain the operation latency. + * + * @param {PeerId|Multiaddr|string} peer - The peer to ping + * @returns {Promise} + */ + ping(peer: PeerId | Multiaddr | string): Promise; + /** + * Removes the handler for each protocol. The protocol + * will no longer be supported on streams. + * + * @param {string[]|string} protocols + */ + unhandle(protocols: string[] | string): Promise; + _onStarting(): Promise; + /** + * Called when libp2p has started and before it returns + * + * @private + */ + private _onDidStart; + /** + * Will dial to the given `peerId` if the current number of + * connected peers is less than the configured `ConnectionManager` + * minConnections. + * + * @private + * @param {PeerId} peerId + */ + private _maybeConnect; + /** + * Initializes and starts peer discovery services + * + * @async + * @private + */ + private _setupPeerDiscovery; +} +declare namespace Libp2p { + export { Connection, MuxedStream, TransportFactory, MuxerFactory, ContentRoutingModule, PeerDiscoveryFactory, PeerRoutingModule, Crypto, Pubsub, PubsubOptions, Datastore, Protector, ConnectionGater, PersistentPeerStoreOptions, HandlerProps, DhtOptions, KeychainOptions, PeerStoreOptions, PubsubLocalOptions, MetricsOptions, RelayOptions, Libp2pConfig, Libp2pModules, Libp2pOptions, constructorOptions, CreateOptions }; +} +import { EventEmitter } from "events"; +type Libp2pOptions = { + /** + * libp2p modules to use + */ + modules: Libp2pModules; + addresses?: AddressManager.AddressManagerOptions | undefined; + connectionManager?: ConnectionManager.ConnectionManagerOptions | undefined; + connectionGater?: Partial | undefined; + datastore?: import("interface-datastore").Datastore | undefined; + dialer?: Dialer.DialerOptions | undefined; + /** + * libp2p host + */ + host?: IdentifyService.HostProperties | undefined; + keychain?: (KeychainOptions & Keychain.KeychainOptions) | undefined; + metrics?: (MetricsOptions & Metrics.MetricsOptions) | undefined; + peerRouting?: PeerRouting.PeerRoutingOptions | undefined; + peerStore?: PeerStoreOptions | undefined; + transportManager?: TransportManager.TransportManagerOptions | undefined; + config?: Libp2pConfig | undefined; +}; +type constructorOptions = { + peerId: PeerId; +}; +import PeerId = require("peer-id"); +import Metrics = require("./metrics"); +type ConnectionGater = import('./types').ConnectionGater; +import AddressManager = require("./address-manager"); +type Libp2pModules = { + transport: import("libp2p-interfaces/src/transport/types").TransportFactory[]; + streamMuxer: MuxerFactory[]; + connEncryption: Crypto[]; + peerDiscovery?: import("libp2p-interfaces/src/peer-discovery/types").PeerDiscoveryFactory[] | undefined; + peerRouting?: import("libp2p-interfaces/src/peer-routing/types").PeerRouting[] | undefined; + contentRouting?: import("libp2p-interfaces/src/content-routing/types").ContentRouting[] | undefined; + dht?: Object | undefined; + pubsub?: (new (...args: any[]) => Pubsub) | undefined; + connProtector?: import("./pnet") | undefined; +}; +type Libp2pConfig = { + /** + * dht module options + */ + dht?: DhtOptions | undefined; + nat?: NatManager.NatManagerOptions | undefined; + peerDiscovery?: Record | undefined; + /** + * pubsub module options + */ + pubsub?: (PubsubLocalOptions & import("libp2p-interfaces/src/pubsub").PubsubOptions) | undefined; + relay?: RelayOptions | undefined; + /** + * transport options indexed by transport key + */ + transport?: Record | undefined; +}; +import ConnectionManager = require("./connection-manager"); +import AutoDialler = require("./connection-manager/auto-dialler"); +import Keychain = require("./keychain"); +import Upgrader = require("./upgrader"); +import TransportManager = require("./transport-manager"); +import NatManager = require("./nat-manager"); +import Registrar = require("./registrar"); +type HandlerProps = { + connection: Connection; + stream: MuxedStream; + protocol: string; +}; +import Dialer = require("./dialer"); +import Relay = require("./circuit"); +import IdentifyService = require("./identify"); +import PeerRouting = require("./peer-routing"); +import ContentRouting = require("./content-routing"); +import FetchService = require("./fetch"); +import PingService = require("./ping"); +import { Multiaddr } from "multiaddr"; +type Connection = import("libp2p-interfaces/src/connection/connection"); +type CreateOptions = { + peerId?: PeerId | undefined; +}; +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +type TransportFactory = import('libp2p-interfaces/src/transport/types').TransportFactory; +type MuxerFactory = import('libp2p-interfaces/src/stream-muxer/types').MuxerFactory; +type ContentRoutingModule = import('libp2p-interfaces/src/content-routing/types').ContentRouting; +type PeerDiscoveryFactory = import('libp2p-interfaces/src/peer-discovery/types').PeerDiscoveryFactory; +type PeerRoutingModule = import('libp2p-interfaces/src/peer-routing/types').PeerRouting; +type Crypto = import('libp2p-interfaces/src/crypto/types').Crypto; +type Pubsub = import('libp2p-interfaces/src/pubsub'); +type PubsubOptions = import('libp2p-interfaces/src/pubsub').PubsubOptions; +type Datastore = import('interface-datastore').Datastore; +type Protector = import('./pnet'); +type PersistentPeerStoreOptions = { + threshold?: number | undefined; +}; +type DhtOptions = { + enabled?: boolean | undefined; + kBucketSize?: number | undefined; + clientMode?: boolean | undefined; + selectors?: import("libp2p-interfaces/src/types").DhtSelectors | undefined; + validators?: import("libp2p-interfaces/src/types").DhtValidators | undefined; +}; +type KeychainOptions = { + datastore?: import("interface-datastore").Datastore | undefined; +}; +type PeerStoreOptions = { + persistence: boolean; +}; +type PubsubLocalOptions = { + enabled: boolean; +}; +type MetricsOptions = { + enabled: boolean; +}; +type RelayOptions = { + enabled?: boolean | undefined; + advertise?: Relay.RelayAdvertiseOptions | undefined; + hop?: Relay.HopOptions | undefined; + autoRelay?: Relay.AutoRelayOptions | undefined; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/index.d.ts.map b/dist/src/index.d.ts.map new file mode 100644 index 0000000000..0427465d0c --- /dev/null +++ b/dist/src/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.js"],"names":[],"mappings":";AAqCA;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AACH;IACE;;;;;;OAMG;IACH,uBAHW,aAAa,GAAG,aAAa,GAC3B,QAAQ,MAAM,CAAC,CAa3B;IAED;;;;;OAKG;IACH,sBAFW,aAAa,GAAG,kBAAkB,EA8L5C;IAxLC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAAwC;IAExC,qBAAqB;IACrB,QADW,MAAM,CACiB;IAClC,+DAAwC;IAQtC,6BAAsB;IAGxB,8BAA8B;IAC9B,iBADW,eAAe,CAYzB;IAED,qDAAqD;IACrD,WADW,OAAO,oBAAoB,EAAE,SAAS,CAK/C;IAGF;;;;;6CAAwC;IACxC,+BAA8E;IAS9E,wBAAqC;IACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAAmC;IACnC,kBAAoB;IACpB,0BAA2B;IAG3B,qCAEE;IACF,0BAIE;IAQA,+BAGE;IAMJ,mBAME;IAGF,mCAIE;IAGF,uBAME;IAGF,qBAGE;IAiWJ;;;;;OAKG;IACH,kBAHW,MAAM,EAAE,GAAC,MAAM,mBACP,YAAY,KAAK,IAAI,iBAUvC;IAjWC,eAME;IAWA,yBAA4B;IAW5B,6CAA4D;IAc5D,UAGE;IAOF,qBAAqB;IACrB,+CAA8D;IAKhE,yBAAwC;IACxC,+BAA8C;IAsXhD;;;;;;OAMG;IACH,yBAQC;IAjYC,2BAA0C;IAC1C,yBAAwC;IAsB1C;;;;OAIG;IACH,SAFa,QAAQ,IAAI,CAAC,CA2BzB;IAED;;;;;OAKG;IACH,QAFa,QAAQ,IAAI,CAAC,CA8CzB;IAxCG,gCAAuB;IA0C3B;;;;;;OAMG;IACH,gBAFa,QAAQ,IAAI,CAAC,CAYzB;IAED,iCAEC;IAED;;;;;OAKG;IACH,wFAEC;IAED;;;;;;;;OAQG;IACH,WALW,MAAM,GAAC,SAAS,GAAC,MAAM;;oBAGrB,QAAQ,UAAU,CAAC,CAI/B;IAED;;;;;;;;;;OAUG;IACH,mBALW,MAAM,GAAC,SAAS,GAAC,MAAM,aACvB,MAAM,EAAE,GAAC,MAAM;;;;;OAWzB;IAED;;;;;OAKG;IACH,YAJW,MAAM,GAAC,SAAS,GAAC,MAAM,iCAErB,QAAQ,UAAU,CAAC,CAkB/B;IAED;;;;;;;;;OASG;IACH,8BAiBC;IAED;;;;;OAKG;IACH,aAHW,MAAM,GAAC,SAAS,GAAC,MAAM,GACrB,QAAQ,IAAI,CAAC,CAgBzB;IAED;;;;;;OAMG;IACH,YAJW,MAAM,GAAC,SAAS,OAChB,MAAM,GACJ,QAAQ,UAAU,GAAG,IAAI,CAAC,CAItC;IAED;;;;;OAKG;IACH,WAHW,MAAM,GAAC,SAAS,GAAC,MAAM,GACrB,QAAQ,MAAM,CAAC,CAW3B;IAkBD;;;;;OAKG;IACH,oBAFW,MAAM,EAAE,GAAC,MAAM,iBAUzB;IAED,6BA2BC;IAED;;;;OAIG;IACH,oBA0BC;IAmBD;;;;;;;OAOG;IACH,sBAaC;IAED;;;;;OAKG;IACH,4BAkDC;CACF;;;;;;;;;aAhsBa,aAAa;;;;;;;;;;;;;;;;;;YAeb,MAAM;;;;uBAvEP,OAAO,SAAS,EAAE,eAAe;;;eA6ChC,4EAAkB;iBAClB,YAAY,EAAE;oBACd,MAAM,EAAE;;;;;4BAKM,GAAG,EAAE,KAAG,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBA7C5B,UAAU;YACV,WAAW;cACX,MAAM;;;;;;;;;;;;;;mBApBP,OAAO,0CAA0C,EAAE,WAAW;wBAC9D,OAAO,uCAAuC,EAAE,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC;oBAC1E,OAAO,0CAA0C,EAAE,YAAY;4BAC/D,OAAO,6CAA6C,EAAE,cAAc;4BACpE,OAAO,4CAA4C,EAAE,oBAAoB;yBACzE,OAAO,0CAA0C,EAAE,WAAW;cAC9D,OAAO,oCAAoC,EAAE,MAAM;cACnD,OAAO,8BAA8B,CAAC;qBACtC,OAAO,8BAA8B,EAAE,aAAa;iBACpD,OAAO,qBAAqB,EAAE,SAAS;iBACvC,OAAO,QAAQ,CAAC;;;;;;;;;;;;;;;iBAuBf,OAAO;;;aAGP,OAAO;;;aAGP,OAAO"} \ No newline at end of file diff --git a/dist/src/insecure/plaintext.d.ts b/dist/src/insecure/plaintext.d.ts new file mode 100644 index 0000000000..d1ac2833bd --- /dev/null +++ b/dist/src/insecure/plaintext.d.ts @@ -0,0 +1,12 @@ +export type Connection = import("libp2p-interfaces/src/connection/connection"); +export const protocol: "/plaintext/2.0.0"; +import PeerId = require("peer-id"); +export declare function secureInbound(localId: PeerId, conn: import("libp2p-interfaces/src/connection/connection"), remoteId: PeerId | undefined): Promise<{ + conn: any; + remotePeer: PeerId; +}>; +export declare function secureOutbound(localId: PeerId, conn: import("libp2p-interfaces/src/connection/connection"), remoteId: PeerId | undefined): Promise<{ + conn: any; + remotePeer: PeerId; +}>; +//# sourceMappingURL=plaintext.d.ts.map \ No newline at end of file diff --git a/dist/src/insecure/plaintext.d.ts.map b/dist/src/insecure/plaintext.d.ts.map new file mode 100644 index 0000000000..232800445b --- /dev/null +++ b/dist/src/insecure/plaintext.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"plaintext.d.ts","sourceRoot":"","sources":["../../../src/insecure/plaintext.js"],"names":[],"mappings":";AAaA,0CAAmC;;AAsEjB;;;GAEd;AAMe;;;GAEf"} \ No newline at end of file diff --git a/dist/src/insecure/proto.d.ts b/dist/src/insecure/proto.d.ts new file mode 100644 index 0000000000..a4fbac0610 --- /dev/null +++ b/dist/src/insecure/proto.d.ts @@ -0,0 +1,128 @@ +import * as $protobuf from "protobufjs"; +/** Properties of an Exchange. */ +export interface IExchange { + + /** Exchange id */ + id?: (Uint8Array|null); + + /** Exchange pubkey */ + pubkey?: (IPublicKey|null); +} + +/** Represents an Exchange. */ +export class Exchange implements IExchange { + + /** + * Constructs a new Exchange. + * @param [p] Properties to set + */ + constructor(p?: IExchange); + + /** Exchange id. */ + public id: Uint8Array; + + /** Exchange pubkey. */ + public pubkey?: (IPublicKey|null); + + /** + * Encodes the specified Exchange message. Does not implicitly {@link Exchange.verify|verify} messages. + * @param m Exchange message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IExchange, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Exchange message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Exchange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Exchange; + + /** + * Creates an Exchange message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Exchange + */ + public static fromObject(d: { [k: string]: any }): Exchange; + + /** + * Creates a plain object from an Exchange message. Also converts values to other types if specified. + * @param m Exchange + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Exchange, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Exchange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** KeyType enum. */ +export enum KeyType { + RSA = 0, + Ed25519 = 1, + Secp256k1 = 2, + ECDSA = 3 +} + +/** Represents a PublicKey. */ +export class PublicKey implements IPublicKey { + + /** + * Constructs a new PublicKey. + * @param [p] Properties to set + */ + constructor(p?: IPublicKey); + + /** PublicKey Type. */ + public Type: KeyType; + + /** PublicKey Data. */ + public Data: Uint8Array; + + /** + * Encodes the specified PublicKey message. Does not implicitly {@link PublicKey.verify|verify} messages. + * @param m PublicKey message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IPublicKey, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PublicKey message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns PublicKey + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): PublicKey; + + /** + * Creates a PublicKey message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns PublicKey + */ + public static fromObject(d: { [k: string]: any }): PublicKey; + + /** + * Creates a plain object from a PublicKey message. Also converts values to other types if specified. + * @param m PublicKey + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: PublicKey, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PublicKey to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} diff --git a/dist/src/keychain/cms.d.ts b/dist/src/keychain/cms.d.ts new file mode 100644 index 0000000000..cf716f80c8 --- /dev/null +++ b/dist/src/keychain/cms.d.ts @@ -0,0 +1,41 @@ +export = CMS; +/** + * Cryptographic Message Syntax (aka PKCS #7) + * + * CMS describes an encapsulation syntax for data protection. It + * is used to digitally sign, digest, authenticate, or encrypt + * arbitrary message content. + * + * See RFC 5652 for all the details. + */ +declare class CMS { + /** + * Creates a new instance with a keychain + * + * @param {import('./index')} keychain - the available keys + * @param {string} dek + */ + constructor(keychain: import('./index'), dek: string); + keychain: import("./index"); + /** + * Creates some protected data. + * + * The output Uint8Array contains the PKCS #7 message in DER. + * + * @param {string} name - The local key name. + * @param {Uint8Array} plain - The data to encrypt. + * @returns {Promise} + */ + encrypt(name: string, plain: Uint8Array): Promise; + /** + * Reads some protected data. + * + * The keychain must contain one of the keys used to encrypt the data. If none of the keys + * exists, an Error is returned with the property 'missingKeys'. It is array of key ids. + * + * @param {Uint8Array} cmsData - The CMS encrypted data to decrypt. + * @returns {Promise} + */ + decrypt(cmsData: Uint8Array): Promise; +} +//# sourceMappingURL=cms.d.ts.map \ No newline at end of file diff --git a/dist/src/keychain/cms.d.ts.map b/dist/src/keychain/cms.d.ts.map new file mode 100644 index 0000000000..445fe8ef2f --- /dev/null +++ b/dist/src/keychain/cms.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cms.d.ts","sourceRoot":"","sources":["../../../src/keychain/cms.js"],"names":[],"mappings":";AAgBA;;;;;;;;GAQG;AACH;IACE;;;;;OAKG;IACH,sBAHW,OAAO,SAAS,CAAC,OACjB,MAAM,EAShB;IAFC,4BAAwB;IAI1B;;;;;;;;OAQG;IACH,cAJW,MAAM,SACN,UAAU,GACR,QAAQ,UAAU,CAAC,CAuB/B;IAED;;;;;;;;OAQG;IACH,iBAHW,UAAU,GACR,QAAQ,UAAU,CAAC,CA8D/B;CACF"} \ No newline at end of file diff --git a/dist/src/keychain/index.d.ts b/dist/src/keychain/index.d.ts new file mode 100644 index 0000000000..b484b707e3 --- /dev/null +++ b/dist/src/keychain/index.d.ts @@ -0,0 +1,158 @@ +export = Keychain; +/** + * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8. + * + * A key in the store has two entries + * - '/info/*key-name*', contains the KeyInfo for the key + * - '/pkcs8/*key-name*', contains the PKCS #8 for the key + * + */ +declare class Keychain { + /** + * Generates the options for a keychain. A random salt is produced. + * + * @returns {Object} + */ + static generateOptions(): Object; + /** + * Gets an object that can encrypt/decrypt protected data. + * The default options for a keychain. + * + * @returns {Object} + */ + static get options(): Object; + /** + * Creates a new instance of a key chain. + * + * @param {Datastore} store - where the key are. + * @param {KeychainOptions} options + * @class + */ + constructor(store: Datastore, options: KeychainOptions); + store: import("interface-datastore").Datastore; + opts: any; + /** + * Gets an object that can encrypt/decrypt protected data + * using the Cryptographic Message Syntax (CMS). + * + * CMS describes an encapsulation syntax for data protection. It + * is used to digitally sign, digest, authenticate, or encrypt + * arbitrary message content. + * + * @returns {CMS} + */ + get cms(): CMS; + /** + * Create a new key. + * + * @param {string} name - The local key name; cannot already exist. + * @param {string} type - One of the key types; 'rsa'. + * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only. + * @returns {Promise} + */ + createKey(name: string, type: string, size?: number | undefined): Promise; + /** + * List all the keys. + * + * @returns {Promise} + */ + listKeys(): Promise; + /** + * Find a key by it's id. + * + * @param {string} id - The universally unique key identifier. + * @returns {Promise} + */ + findKeyById(id: string): Promise; + /** + * Find a key by it's name. + * + * @param {string} name - The local key name. + * @returns {Promise} + */ + findKeyByName(name: string): Promise; + /** + * Remove an existing key. + * + * @param {string} name - The local key name; must already exist. + * @returns {Promise} + */ + removeKey(name: string): Promise; + /** + * Rename a key + * + * @param {string} oldName - The old local key name; must already exist. + * @param {string} newName - The new local key name; must not already exist. + * @returns {Promise} + */ + renameKey(oldName: string, newName: string): Promise; + /** + * Export an existing key as a PEM encrypted PKCS #8 string + * + * @param {string} name - The local key name; must already exist. + * @param {string} password - The password + * @returns {Promise} + */ + exportKey(name: string, password: string): Promise; + /** + * Import a new key from a PEM encoded PKCS #8 string + * + * @param {string} name - The local key name; must not already exist. + * @param {string} pem - The PEM encoded PKCS #8 string + * @param {string} password - The password. + * @returns {Promise} + */ + importKey(name: string, pem: string, password: string): Promise; + /** + * Import a peer key + * + * @param {string} name - The local key name; must not already exist. + * @param {PeerId} peer - The PEM encoded PKCS #8 string + * @returns {Promise} + */ + importPeer(name: string, peer: PeerId): Promise; + /** + * Gets the private key as PEM encoded PKCS #8 string. + * + * @param {string} name + * @returns {Promise} + */ + _getPrivateKey(name: string): Promise; + /** + * Rotate keychain password and re-encrypt all assosciated keys + * + * @param {string} oldPass - The old local keychain password + * @param {string} newPass - The new local keychain password + */ + rotateKeychainPass(oldPass: string, newPass: string): Promise; +} +declare namespace Keychain { + export { PeerId, Datastore, DekOptions, KeychainOptions, KeyInfo }; +} +import CMS = require("./cms"); +/** + * Information about a key. + */ +type KeyInfo = { + /** + * - The universally unique key id. + */ + id: string; + /** + * - The local key name. + */ + name: string; +}; +type PeerId = import('peer-id'); +type Datastore = import('interface-datastore').Datastore; +type KeychainOptions = { + pass?: string | undefined; + dek?: DekOptions | undefined; +}; +type DekOptions = { + hash: string; + salt: string; + iterationCount: number; + keyLength: number; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/keychain/index.d.ts.map b/dist/src/keychain/index.d.ts.map new file mode 100644 index 0000000000..c92ffb9ccb --- /dev/null +++ b/dist/src/keychain/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/keychain/index.js"],"names":[],"mappings":";AAmHA;;;;;;;GAOG;AACH;IAwDE;;;;OAIG;IACH,0BAFa,MAAM,CAOlB;IAED;;;;;OAKG;IACH,6BAEC;IA3ED;;;;;;OAMG;IACH,mBAJW,SAAS,WACT,eAAe,EAmCzB;IA5BC,+CAAkB;IAElB,UAAiD;IA4BnD;;;;;;;;;OASG;IACH,eAEC;IAwBD;;;;;;;OAOG;IACH,gBALW,MAAM,QACN,MAAM,8BAEJ,QAAQ,OAAO,CAAC,CAiD5B;IAED;;;;OAIG;IACH,YAFa,QAAQ,OAAO,EAAE,CAAC,CAc9B;IAED;;;;;OAKG;IACH,gBAHW,MAAM,GACJ,QAAQ,OAAO,GAAC,SAAS,CAAC,CAStC;IAED;;;;;OAKG;IACH,oBAHW,MAAM,GACJ,QAAQ,OAAO,CAAC,CAc5B;IAED;;;;;OAKG;IACH,gBAHW,MAAM,GACJ,QAAQ,OAAO,CAAC,CAc5B;IAED;;;;;;OAMG;IACH,mBAJW,MAAM,WACN,MAAM,GACJ,QAAQ,OAAO,CAAC,CAkC5B;IAED;;;;;;OAMG;IACH,gBAJW,MAAM,YACN,MAAM,GACJ,QAAQ,MAAM,CAAC,CAqB3B;IAED;;;;;;;OAOG;IACH,gBALW,MAAM,OACN,MAAM,YACN,MAAM,GACJ,QAAQ,OAAO,CAAC,CAyC5B;IAED;;;;;;OAMG;IACH,iBAJW,MAAM,QACN,MAAM,GACJ,QAAQ,OAAO,CAAC,CAiC5B;IAED;;;;;OAKG;IACH,qBAHW,MAAM,GACJ,QAAQ,MAAM,CAAC,CAc3B;IAED;;;;;OAKG;IACH,4BAHW,MAAM,WACN,MAAM,sBA2ChB;CACF;;;;;;;;;;;;QAtgBa,MAAM;;;;UACN,MAAM;;cArBP,OAAO,SAAS,CAAC;iBACjB,OAAO,qBAAqB,EAAE,SAAS;;;;;;UAKtC,MAAM;UACN,MAAM;oBACN,MAAM;eACN,MAAM"} \ No newline at end of file diff --git a/dist/src/keychain/util.d.ts b/dist/src/keychain/util.d.ts new file mode 100644 index 0000000000..378ff4ea55 --- /dev/null +++ b/dist/src/keychain/util.d.ts @@ -0,0 +1,24 @@ +/** + * Gets a self-signed X.509 certificate for the key. + * + * The output Uint8Array contains the PKCS #7 message in DER. + * + * TODO: move to libp2p-crypto package + * + * @param {KeyInfo} key - The id and name of the key + * @param {RsaPrivateKey} privateKey - The naked key + * @returns {Uint8Array} + */ +export function certificateForKey(key: any, privateKey: any): Uint8Array; +/** + * Finds the first item in a collection that is matched in the + * `asyncCompare` function. + * + * `asyncCompare` is an async function that must + * resolve to either `true` or `false`. + * + * @param {Array} array + * @param {function(*)} asyncCompare - An async function that returns a boolean + */ +export function findAsync(array: any[], asyncCompare: (arg0: any) => any): Promise; +//# sourceMappingURL=util.d.ts.map \ No newline at end of file diff --git a/dist/src/keychain/util.d.ts.map b/dist/src/keychain/util.d.ts.map new file mode 100644 index 0000000000..d9af810f04 --- /dev/null +++ b/dist/src/keychain/util.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../../src/keychain/util.js"],"names":[],"mappings":"AAOA;;;;;;;;;;GAUG;AACH,8DAFa,UAAU,CAqDtB;AAED;;;;;;;;;GASG;AACH,wFAKC"} \ No newline at end of file diff --git a/dist/src/metrics/index.d.ts b/dist/src/metrics/index.d.ts new file mode 100644 index 0000000000..17c3328dcf --- /dev/null +++ b/dist/src/metrics/index.d.ts @@ -0,0 +1,151 @@ +export = Metrics; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/transport/types').MultiaddrConnection} MultiaddrConnection + */ +/** + * @typedef MetricsOptions + * @property {number} [computeThrottleMaxQueueSize = defaultOptions.computeThrottleMaxQueueSize] + * @property {number} [computeThrottleTimeout = defaultOptions.computeThrottleTimeout] + * @property {number[]} [movingAverageIntervals = defaultOptions.movingAverageIntervals] + * @property {number} [maxOldPeersRetention = defaultOptions.maxOldPeersRetention] + */ +declare class Metrics { + /** + * Merges `other` into `target`. `target` will be modified + * and returned. + * + * @param {Stats} target + * @param {Stats} other + * @returns {Stats} + */ + static mergeStats(target: Stats, other: Stats): Stats; + /** + * @class + * @param {MetricsOptions} options + */ + constructor(options: MetricsOptions); + _options: any; + _globalStats: Stats; + _peerStats: Map; + _protocolStats: Map; + _oldPeers: any; + _running: boolean; + /** + * Takes the metadata for a message and tracks it in the + * appropriate categories. If the protocol is present, protocol + * stats will also be tracked. + * + * @private + * @param {object} params + * @param {PeerId} params.remotePeer - Remote peer + * @param {string} [params.protocol] - Protocol string the stream is running + * @param {string} params.direction - One of ['in','out'] + * @param {number} params.dataLength - Size of the message + * @returns {void} + */ + private _onMessage; + _systems: Map; + /** + * Must be called for stats to saved. Any data pushed for tracking + * will be ignored. + */ + start(): void; + /** + * Stops all averages timers and prevents new data from being tracked. + * Once `stop` is called, `start` must be called to resume stats tracking. + */ + stop(): void; + /** + * Gets the global `Stats` object + * + * @returns {Stats} + */ + get global(): Stats; + /** + * Returns a list of `PeerId` strings currently being tracked + * + * @returns {string[]} + */ + get peers(): string[]; + /** + * @returns {Map>>} + */ + getComponentMetrics(): Map>>; + updateComponentMetric({ system, component, metric, value }: { + system?: string | undefined; + component: any; + metric: any; + value: any; + }): void; + /** + * Returns the `Stats` object for the given `PeerId` whether it + * is a live peer, or in the disconnected peer LRU cache. + * + * @param {PeerId} peerId + * @returns {Stats} + */ + forPeer(peerId: PeerId): Stats; + /** + * Returns a list of all protocol strings currently being tracked. + * + * @returns {string[]} + */ + get protocols(): string[]; + /** + * Returns the `Stats` object for the given `protocol`. + * + * @param {string} protocol + * @returns {Stats} + */ + forProtocol(protocol: string): Stats; + /** + * Should be called when all connections to a given peer + * have closed. The `Stats` collection for the peer will + * be stopped and moved to an LRU for temporary retention. + * + * @param {PeerId} peerId + */ + onPeerDisconnected(peerId: PeerId): void; + /** + * Replaces the `PeerId` string with the given `peerId`. + * If stats are already being tracked for the given `peerId`, the + * placeholder stats will be merged with the existing stats. + * + * @param {PeerId} placeholder - A peerId string + * @param {PeerId} peerId + * @returns {void} + */ + updatePlaceholder(placeholder: PeerId, peerId: PeerId): void; + /** + * Tracks data running through a given Duplex Iterable `stream`. If + * the `peerId` is not provided, a placeholder string will be created and + * returned. This allows lazy tracking of a peer when the peer is not yet known. + * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called + * with the placeholder string returned from here, and the known `PeerId`. + * + * @param {Object} options + * @param {MultiaddrConnection} options.stream - A duplex iterable stream + * @param {PeerId} [options.remotePeer] - The id of the remote peer that's connected + * @param {string} [options.protocol] - The protocol the stream is running + * @returns {MultiaddrConnection} The peerId string or placeholder string + */ + trackStream({ stream, remotePeer, protocol }: { + stream: MultiaddrConnection; + remotePeer?: import("peer-id") | undefined; + protocol?: string | undefined; + }): MultiaddrConnection; +} +declare namespace Metrics { + export { PeerId, MultiaddrConnection, MetricsOptions }; +} +import Stats = require("./stats"); +type PeerId = import('peer-id'); +type MultiaddrConnection = import('libp2p-interfaces/src/transport/types').MultiaddrConnection; +type MetricsOptions = { + computeThrottleMaxQueueSize?: number | undefined; + computeThrottleTimeout?: number | undefined; + movingAverageIntervals?: number[] | undefined; + maxOldPeersRetention?: number | undefined; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/metrics/index.d.ts.map b/dist/src/metrics/index.d.ts.map new file mode 100644 index 0000000000..8f035ab7f9 --- /dev/null +++ b/dist/src/metrics/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/metrics/index.js"],"names":[],"mappings":";AAoBA;;;GAGG;AAEH;;;;;;GAMG;AAEH;IA4OE;;;;;;;OAOG;IACH,0BAJW,KAAK,SACL,KAAK,GACH,KAAK,CAWjB;IA5PD;;;OAGG;IACH,qBAFW,cAAc,EAWxB;IARC,cAAqD;IACrD,oBAA6D;IAC7D,0BAA2B;IAC3B,8BAA+B;IAC/B,eAA+D;IAC/D,kBAAqB;IAqHvB;;;;;;;;;;;;OAYG;IACH,mBAwBC;IAxJC,wBAAyB;IAG3B;;;OAGG;IACH,cAEC;IAED;;;OAGG;IACH,aASC;IAED;;;;OAIG;IACH,oBAEC;IAED;;;;OAIG;IACH,sBAEC;IAED;;OAEG;IACH,uBAFa,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAItD;IAED;;;;;aAcC;IAED;;;;;;OAMG;IACH,gBAHW,MAAM,GACJ,KAAK,CAKjB;IAED;;;;OAIG;IACH,0BAEC;IAED;;;;;OAKG;IACH,sBAHW,MAAM,GACJ,KAAK,CAIjB;IAED;;;;;;OAMG;IACH,2BAFW,MAAM,QAUhB;IAyCD;;;;;;;;OAQG;IACH,+BAJW,MAAM,UACN,MAAM,GACJ,IAAI,CAoBhB;IAED;;;;;;;;;;;;OAYG;IACH;QALwC,MAAM,EAAnC,mBAAmB;QACF,UAAU;QACV,QAAQ;QACvB,mBAAmB,CA2B/B;CAoBF;;;;;cA1QY,OAAO,SAAS,CAAC;2BACjB,OAAO,uCAAuC,EAAE,mBAAmB"} \ No newline at end of file diff --git a/dist/src/metrics/old-peers.d.ts b/dist/src/metrics/old-peers.d.ts new file mode 100644 index 0000000000..b96556f9f8 --- /dev/null +++ b/dist/src/metrics/old-peers.d.ts @@ -0,0 +1,3 @@ +declare function _exports(maxSize: number): any; +export = _exports; +//# sourceMappingURL=old-peers.d.ts.map \ No newline at end of file diff --git a/dist/src/metrics/old-peers.d.ts.map b/dist/src/metrics/old-peers.d.ts.map new file mode 100644 index 0000000000..f9f888980c --- /dev/null +++ b/dist/src/metrics/old-peers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"old-peers.d.ts","sourceRoot":"","sources":["../../../src/metrics/old-peers.js"],"names":[],"mappings":"AAUiB,mCAHN,MAAM,GACJ,GAAG,CAOf"} \ No newline at end of file diff --git a/dist/src/metrics/stats.d.ts b/dist/src/metrics/stats.d.ts new file mode 100644 index 0000000000..da72faa92e --- /dev/null +++ b/dist/src/metrics/stats.d.ts @@ -0,0 +1,139 @@ +export = Stats; +/** + * @typedef {import('@vascosantos/moving-average').IMovingAverage} IMovingAverage + * @typedef {import('bignumber.js').BigNumber} Big + */ +declare class Stats extends EventEmitter { + /** + * A queue based manager for stat processing + * + * @class + * @param {string[]} initialCounters + * @param {any} options + */ + constructor(initialCounters: string[], options: any); + _options: any; + _queue: any[]; + /** @type {{ dataReceived: Big, dataSent: Big }} */ + _stats: { + dataReceived: Big; + dataSent: Big; + }; + _frequencyLastTime: number; + _frequencyAccumulators: {}; + /** @type {{ dataReceived: IMovingAverage[], dataSent: IMovingAverage[] }} */ + _movingAverages: { + dataReceived: IMovingAverage[]; + dataSent: IMovingAverage[]; + }; + /** + * If there are items in the queue, they will will be processed and + * the frequency for all items will be updated based on the Timestamp + * of the last item in the queue. The `update` event will also be emitted + * with the latest stats. + * + * If there are no items in the queue, no action is taken. + * + * @private + * @returns {void} + */ + private _update; + /** + * Initializes the internal timer if there are items in the queue. This + * should only need to be called if `Stats.stop` was previously called, as + * `Stats.push` will also start the processing. + * + * @returns {void} + */ + start(): void; + /** + * Stops processing and computing of stats by clearing the internal + * timer. + * + * @returns {void} + */ + stop(): void; + _timeout: any; + /** + * Returns a clone of the current stats. + */ + get snapshot(): { + dataReceived: Big; + dataSent: Big; + }; + /** + * Returns a clone of the internal movingAverages + */ + get movingAverages(): { + dataReceived: IMovingAverage[]; + dataSent: IMovingAverage[]; + }; + /** + * Returns a plain JSON object of the stats + * + * @returns {*} + */ + toJSON(): any; + /** + * Pushes the given operation data to the queue, along with the + * current Timestamp, then resets the update timer. + * + * @param {string} counter + * @param {number} inc + * @returns {void} + */ + push(counter: string, inc: number): void; + /** + * Resets the timeout for triggering updates. + * + * @private + * @returns {void} + */ + private _resetComputeTimeout; + /** + * Calculates and returns the timeout for the next update based on + * the urgency of the update. + * + * @private + * @returns {number} + */ + private _nextTimeout; + /** + * For each key in the stats, the frequency and moving averages + * will be updated via Stats._updateFrequencyFor based on the time + * difference between calls to this method. + * + * @private + * @param {Timestamp} latestTime + * @returns {void} + */ + private _updateFrequency; + /** + * Updates the `movingAverages` for the given `key` and also + * resets the `frequencyAccumulator` for the `key`. + * + * @private + * @param {string} key + * @param {number} timeDiffMS - Time in milliseconds + * @param {Timestamp} latestTime - Time in ticks + * @returns {void} + */ + private _updateFrequencyFor; + /** + * For the given operation, `op`, the stats and `frequencyAccumulator` + * will be updated or initialized if they don't already exist. + * + * @private + * @param {{string, number}[]} op + * @throws {InvalidNumber} + * @returns {void} + */ + private _applyOp; +} +declare namespace Stats { + export { IMovingAverage, Big }; +} +import { EventEmitter } from "events"; +type IMovingAverage = import('@vascosantos/moving-average').IMovingAverage; +type Big = import('bignumber.js').BigNumber; +//# sourceMappingURL=stats.d.ts.map \ No newline at end of file diff --git a/dist/src/metrics/stats.d.ts.map b/dist/src/metrics/stats.d.ts.map new file mode 100644 index 0000000000..0c0f5097e5 --- /dev/null +++ b/dist/src/metrics/stats.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../../src/metrics/stats.js"],"names":[],"mappings":";AAQA;;;GAGG;AAEH;IACE;;;;;;OAMG;IACH,6BAHW,MAAM,EAAE,WACR,GAAG,EAkCb;IA7BC,cAAuB;IACvB,cAAgB;IAEhB,mDAAmD;IACnD;sBAD2B,GAAG;kBAAY,GAAG;MAI5C;IAED,2BAAoC;IACpC,2BAAgC;IAEhC,6EAA6E;IAC7E;sBAD2B,cAAc,EAAE;kBAAY,cAAc,EAAE;MAC9C;IAwH3B;;;;;;;;;;OAUG;IACH,gBAaC;IA9HD;;;;;;OAMG;IACH,SAFa,IAAI,CAMhB;IAED;;;;;OAKG;IACH,QAFa,IAAI,CAOhB;IAFG,cAAoB;IAIxB;;OAEG;IACH;sBAzD6B,GAAG;kBAAY,GAAG;MA2D9C;IAED;;OAEG;IACH;sBAvD6B,cAAc,EAAE;kBAAY,cAAc,EAAE;MAyDxE;IAED;;;;OAIG;IACH,cAkBC;IAED;;;;;;;OAOG;IACH,cAJW,MAAM,OACN,MAAM,GACJ,IAAI,CAKhB;IAED;;;;;OAKG;IACH,6BAEC;IAED;;;;;;OAMG;IACH,qBAKC;IA4BD;;;;;;;;OAQG;IACH,yBAQC;IAED;;;;;;;;;OASG;IACH,4BAsBC;IAED;;;;;;;;OAQG;IACH,iBAqBC;CACF;;;;;sBAlQY,OAAO,6BAA6B,EAAE,cAAc;WACpD,OAAO,cAAc,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/metrics/tracked-map.d.ts b/dist/src/metrics/tracked-map.d.ts new file mode 100644 index 0000000000..5501ae0041 --- /dev/null +++ b/dist/src/metrics/tracked-map.d.ts @@ -0,0 +1,8 @@ +declare function _exports({ system, component, metric, metrics }: { + system?: string | undefined; + component: string; + metric: string; + metrics?: import(".") | undefined; +}): Map; +export = _exports; +//# sourceMappingURL=tracked-map.d.ts.map \ No newline at end of file diff --git a/dist/src/metrics/tracked-map.d.ts.map b/dist/src/metrics/tracked-map.d.ts.map new file mode 100644 index 0000000000..22958b11d4 --- /dev/null +++ b/dist/src/metrics/tracked-map.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tracked-map.d.ts","sourceRoot":"","sources":["../../../src/metrics/tracked-map.js"],"names":[],"mappings":"AAkFiB;IANW,MAAM;IACP,SAAS,EAAzB,MAAM;IACU,MAAM,EAAtB,MAAM;IACgB,OAAO;cAcvC"} \ No newline at end of file diff --git a/dist/src/nat-manager.d.ts b/dist/src/nat-manager.d.ts new file mode 100644 index 0000000000..718b5fdac4 --- /dev/null +++ b/dist/src/nat-manager.d.ts @@ -0,0 +1,121 @@ +export = NatManager; +declare class NatManager { + /** + * @class + * @param {NatManagerProperties & NatManagerOptions} options + */ + constructor({ peerId, addressManager, transportManager, ...options }: NatManagerProperties & NatManagerOptions); + _peerId: import("peer-id"); + _addressManager: import("./address-manager"); + _transportManager: import("./transport-manager"); + _enabled: boolean; + _externalIp: string | undefined; + _options: { + description: string; + ttl: number; + autoUpdate: true; + gateway: string | undefined; + enablePMP: boolean; + }; + /** + * Starts the NAT manager + */ + start(): void; + _start(): Promise; + _getClient(): { + /** + * @param {...any} args + * @returns {Promise} + */ + map: (...args: any[]) => Promise; + /** + * @param {...any} args + * @returns {Promise} + */ + destroy: (...args: any[]) => Promise; + /** + * @param {...any} args + * @returns {Promise} + */ + externalIp: (...args: any[]) => Promise; + }; + _client: { + /** + * @param {...any} args + * @returns {Promise} + */ + map: (...args: any[]) => Promise; + /** + * @param {...any} args + * @returns {Promise} + */ + destroy: (...args: any[]) => Promise; + /** + * @param {...any} args + * @returns {Promise} + */ + externalIp: (...args: any[]) => Promise; + } | null | undefined; + /** + * Stops the NAT manager + * + * @async + */ + stop(): Promise; +} +declare namespace NatManager { + export { PeerId, TransportManager, AddressManager, NatManagerProperties, NatManagerOptions }; +} +type NatManagerProperties = { + /** + * - The peer ID of the current node + */ + peerId: PeerId; + /** + * - A transport manager + */ + transportManager: TransportManager; + /** + * - An address manager + */ + addressManager: AddressManager; +}; +type NatManagerOptions = { + /** + * - Whether to enable the NAT manager + */ + enabled: boolean; + /** + * - Pass a value to use instead of auto-detection + */ + externalIp?: string | undefined; + /** + * - A string value to use for the port mapping description on the gateway + */ + description?: string | undefined; + /** + * - How long UPnP port mappings should last for in seconds (minimum 1200) + */ + ttl?: number | undefined; + /** + * - Whether to automatically refresh UPnP port mappings when their TTL is reached + */ + keepAlive?: boolean | undefined; + /** + * - Pass a value to use instead of auto-detection + */ + gateway?: string | undefined; + /** + * - PMP options + */ + pmp?: { + /** + * - Whether to enable PMP as well as UPnP + */ + enabled?: boolean | undefined; + } | undefined; +}; +type PeerId = import('peer-id'); +type TransportManager = import('./transport-manager'); +type AddressManager = import('./address-manager'); +//# sourceMappingURL=nat-manager.d.ts.map \ No newline at end of file diff --git a/dist/src/nat-manager.d.ts.map b/dist/src/nat-manager.d.ts.map new file mode 100644 index 0000000000..d80d30df88 --- /dev/null +++ b/dist/src/nat-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"nat-manager.d.ts","sourceRoot":"","sources":["../../src/nat-manager.js"],"names":[],"mappings":";AAiDA;IACE;;;OAGG;IACH,sEAFW,oBAAoB,GAAG,iBAAiB,EAoBlD;IAjBC,2BAAqB;IACrB,6CAAqC;IACrC,iDAAyC;IAEzC,kBAA+B;IAC/B,gCAAqC;IACrC;;;;;;MAMC;IAOH;;OAEG;IACH,cAUC;IAED,wBAgDC;IAED;QAgBI;;;WAGG;uBAFY,GAAG,OACL,QAAQ,IAAI,CAAC;QAI1B;;;WAGG;2BAFY,GAAG,OACL,QAAQ,IAAI,CAAC;QAI1B;;;WAGG;8BAFY,GAAG,OACL,QAAQ,MAAM,CAAC;MAM/B;IArBC;QACE;;;WAGG;uBAFY,GAAG,OACL,QAAQ,IAAI,CAAC;QAI1B;;;WAGG;2BAFY,GAAG,OACL,QAAQ,IAAI,CAAC;QAI1B;;;WAGG;8BAFY,GAAG,OACL,QAAQ,MAAM,CAAC;yBAG7B;IAKH;;;;OAIG;IACH,sBAWC;CACF;;;;;;;;YApKa,MAAM;;;;sBACN,gBAAgB;;;;oBAChB,cAAc;;;;;;aAGd,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAZR,OAAO,SAAS,CAAC;wBACjB,OAAO,qBAAqB,CAAC;sBAC7B,OAAO,mBAAmB,CAAC"} \ No newline at end of file diff --git a/dist/src/peer-routing.d.ts b/dist/src/peer-routing.d.ts new file mode 100644 index 0000000000..19bbf85ebd --- /dev/null +++ b/dist/src/peer-routing.d.ts @@ -0,0 +1,103 @@ +export = PeerRouting; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('libp2p-interfaces/src/peer-routing/types').PeerRouting} PeerRoutingModule + */ +/** + * @typedef {Object} RefreshManagerOptions + * @property {boolean} [enabled = true] - Whether to enable the Refresh manager + * @property {number} [bootDelay = 6e5] - Boot delay to start the Refresh Manager (in ms) + * @property {number} [interval = 10e3] - Interval between each Refresh Manager run (in ms) + * @property {number} [timeout = 10e3] - How long to let each refresh run (in ms) + * + * @typedef {Object} PeerRoutingOptions + * @property {RefreshManagerOptions} [refreshManager] + */ +declare class PeerRouting { + /** + * @class + * @param {import('./')} libp2p + */ + constructor(libp2p: import('./')); + _peerId: import("peer-id"); + _peerStore: import("./peer-store/types").PeerStore; + /** @type {PeerRoutingModule[]} */ + _routers: PeerRoutingModule[]; + _refreshManagerOptions: { + enabled: boolean; + interval: number; + bootDelay: number; + } & RefreshManagerOptions; + /** + * Recurrent task to find closest peers and add their addresses to the Address Book. + */ + _findClosestPeersTask(): Promise; + /** + * Start peer routing service. + */ + start(): void; + _timeoutId: any; + /** + * Stop peer routing service. + */ + stop(): void; + /** + * Iterates over all peer routers in parallel to find the given peer. + * + * @param {PeerId} id - The id of the peer to find + * @param {object} [options] + * @param {number} [options.timeout] - How long the query should run + * @returns {Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>} + */ + findPeer(id: PeerId, options?: { + timeout?: number | undefined; + } | undefined): Promise<{ + id: PeerId; + multiaddrs: Multiaddr[]; + }>; + /** + * Attempt to find the closest peers on the network to the given key. + * + * @param {Uint8Array} key - A CID like key + * @param {Object} [options] + * @param {number} [options.timeout=30e3] - How long the query can take + * @param {AbortSignal} [options.signal] - An AbortSignal to abort the request + * @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} + */ + getClosestPeers(key: Uint8Array, options?: { + timeout?: number | undefined; + signal?: AbortSignal | undefined; + } | undefined): AsyncIterable<{ + id: PeerId; + multiaddrs: Multiaddr[]; + }>; +} +declare namespace PeerRouting { + export { PeerId, Multiaddr, PeerRoutingModule, RefreshManagerOptions, PeerRoutingOptions }; +} +type PeerRoutingModule = import('libp2p-interfaces/src/peer-routing/types').PeerRouting; +type RefreshManagerOptions = { + /** + * - Whether to enable the Refresh manager + */ + enabled?: boolean | undefined; + /** + * - Boot delay to start the Refresh Manager (in ms) + */ + bootDelay?: number | undefined; + /** + * - Interval between each Refresh Manager run (in ms) + */ + interval?: number | undefined; + /** + * - How long to let each refresh run (in ms) + */ + timeout?: number | undefined; +}; +type PeerId = import('peer-id'); +type Multiaddr = import('multiaddr').Multiaddr; +type PeerRoutingOptions = { + refreshManager?: RefreshManagerOptions | undefined; +}; +//# sourceMappingURL=peer-routing.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-routing.d.ts.map b/dist/src/peer-routing.d.ts.map new file mode 100644 index 0000000000..2a3b7331e4 --- /dev/null +++ b/dist/src/peer-routing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"peer-routing.d.ts","sourceRoot":"","sources":["../../src/peer-routing.js"],"names":[],"mappings":";AA6BA;;;;GAIG;AAEH;;;;;;;;;GASG;AAEH;IACE;;;OAGG;IACH,oBAFW,OAAO,IAAI,CAAC,EAgBtB;IAbC,2BAA4B;IAC5B,mDAAkC;IAClC,kCAAkC;IAClC,UADW,iBAAiB,EAAE,CACmB;IAOjD;;;;8BAAwE;IAkB1E;;OAEG;IACH,uCAOC;IAvBD;;OAEG;IACH,cAQC;IAHC,gBAEC;IAeH;;OAEG;IACH,aAEC;IAED;;;;;;;OAOG;IACH,aALW,MAAM;;oBAGJ,QAAQ;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC,CA+B5D;IAED;;;;;;;;OAQG;IACH,qBANW,UAAU;;;oBAIR,cAAc;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC,CA2BlE;CACF;;;;yBA7IY,OAAO,0CAA0C,EAAE,WAAW;;;;;;;;;;;;;;;;;;;cAF9D,OAAO,SAAS,CAAC;iBACjB,OAAO,WAAW,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/peer-store/address-book.d.ts b/dist/src/peer-store/address-book.d.ts new file mode 100644 index 0000000000..36a412715b --- /dev/null +++ b/dist/src/peer-store/address-book.d.ts @@ -0,0 +1,67 @@ +export = PeerStoreAddressBook; +/** + * @implements {AddressBook} + */ +declare class PeerStoreAddressBook implements AddressBook { + /** + * @param {PeerStore["emit"]} emit + * @param {import('./types').Store} store + * @param {(peerId: PeerId, multiaddr: Multiaddr) => Promise} addressFilter + */ + constructor(emit: PeerStore["emit"], store: import('./types').Store, addressFilter: (peerId: PeerId, multiaddr: Multiaddr) => Promise); + _emit: (event: U, ...args: Parameters) => boolean; + _store: import("./types").Store; + _addressFilter: (peerId: PeerId, multiaddr: Multiaddr) => Promise; + /** + * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope. + * This will return a boolean that indicates if the record was successfully processed and added + * into the AddressBook. + * + * @param {Envelope} envelope + */ + consumePeerRecord(envelope: Envelope): Promise; + /** + * @param {PeerId} peerId + */ + getRawEnvelope(peerId: PeerId): Promise; + /** + * Get an Envelope containing a PeerRecord for the given peer. + * Returns undefined if no record exists. + * + * @param {PeerId} peerId + */ + getPeerRecord(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + */ + get(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + * @param {Multiaddr[]} multiaddrs + */ + set(peerId: PeerId, multiaddrs: Multiaddr[]): Promise; + /** + * @param {PeerId} peerId + * @param {Multiaddr[]} multiaddrs + */ + add(peerId: PeerId, multiaddrs: Multiaddr[]): Promise; + /** + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + * @param {(addresses: Address[]) => Address[]} [addressSorter] + */ + getMultiaddrsForPeer(peerId: PeerId, addressSorter?: ((addresses: Address[]) => Address[]) | undefined): Promise; +} +declare namespace PeerStoreAddressBook { + export { PeerStore, Address, AddressBook }; +} +type AddressBook = import('./types').AddressBook; +import Envelope = require("../record/envelope"); +import PeerId = require("peer-id"); +import { Multiaddr } from "multiaddr"; +type PeerStore = import('./types').PeerStore; +type Address = import('./types').Address; +//# sourceMappingURL=address-book.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/address-book.d.ts.map b/dist/src/peer-store/address-book.d.ts.map new file mode 100644 index 0000000000..2d03a513ad --- /dev/null +++ b/dist/src/peer-store/address-book.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address-book.d.ts","sourceRoot":"","sources":["../../../src/peer-store/address-book.js"],"names":[],"mappings":";AA2BA;;GAEG;AACH;IACE;;;;OAIG;IACH,kBAJW,SAAS,CAAC,MAAM,CAAC,SACjB,OAAO,SAAS,EAAE,KAAK,0BACd,MAAM,aAAa,SAAS,KAAK,QAAQ,OAAO,CAAC,EAMpE;IAHC,2IAAiB;IACjB,gCAAmB;IACnB,yBALkB,MAAM,aAAa,SAAS,KAAK,QAAQ,OAAO,CAAC,CAKhC;IAGrC;;;;;;OAMG;IACH,4BAFW,QAAQ,oBA+DlB;IAED;;OAEG;IACH,uBAFW,MAAM,mCAmBhB;IAED;;;;;OAKG;IACH,sBAFW,MAAM,iCAUhB;IAED;;OAEG;IACH,YAFW,MAAM,wCA0BhB;IAED;;;OAGG;IACH,YAHW,MAAM,cACN,SAAS,EAAE,iBA2DrB;IAED;;;OAGG;IACH,YAHW,MAAM,cACN,SAAS,EAAE,iBA0DrB;IAED;;OAEG;IACH,eAFW,MAAM,iBA4BhB;IAED;;;OAGG;IACH,6BAHW,MAAM,+BACM,OAAO,EAAE,KAAK,OAAO,EAAE,qCAe7C;CACF;;;;mBA/UY,OAAO,SAAS,EAAE,WAAW;;;;iBAF7B,OAAO,SAAS,EAAE,SAAS;eAC3B,OAAO,SAAS,EAAE,OAAO"} \ No newline at end of file diff --git a/dist/src/peer-store/index.d.ts b/dist/src/peer-store/index.d.ts new file mode 100644 index 0000000000..408eaf4530 --- /dev/null +++ b/dist/src/peer-store/index.d.ts @@ -0,0 +1,58 @@ +export = DefaultPeerStore; +/** + * An implementation of PeerStore that stores data in a Datastore + * + * @implements {PeerStore} + */ +declare class DefaultPeerStore extends EventEmitter implements PeerStore { + /** + * @param {object} properties + * @param {PeerId} properties.peerId + * @param {import('interface-datastore').Datastore} properties.datastore + * @param {(peerId: PeerId, multiaddr: Multiaddr) => Promise} properties.addressFilter + */ + constructor({ peerId, datastore, addressFilter }: { + peerId: PeerId; + datastore: import('interface-datastore').Datastore; + addressFilter: (peerId: PeerId, multiaddr: Multiaddr) => Promise; + }); + _peerId: import("peer-id"); + _store: Store; + addressBook: AddressBook; + keyBook: KeyBook; + metadataBook: MetadataBook; + protoBook: ProtoBook; + getPeers(): AsyncGenerator; + /** + * Delete the information of the given peer in every book + * + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; + /** + * Get the stored information of a given peer + * + * @param {PeerId} peerId + */ + get(peerId: PeerId): Promise; + /** + * Returns true if we have a record of the peer + * + * @param {PeerId} peerId + */ + has(peerId: PeerId): Promise; +} +declare namespace DefaultPeerStore { + export { PeerStore, Peer, PeerId, Multiaddr }; +} +type PeerStore = import('./types').PeerStore; +import { EventEmitter } from "events"; +import Store = require("./store"); +import AddressBook = require("./address-book"); +import KeyBook = require("./key-book"); +import MetadataBook = require("./metadata-book"); +import ProtoBook = require("./proto-book"); +type PeerId = import('peer-id'); +type Multiaddr = import('multiaddr').Multiaddr; +type Peer = import('./types').Peer; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/index.d.ts.map b/dist/src/peer-store/index.d.ts.map new file mode 100644 index 0000000000..370e1595fc --- /dev/null +++ b/dist/src/peer-store/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/peer-store/index.js"],"names":[],"mappings":";AAqBA;;;;GAIG;AACH;IACE;;;;;OAKG;IACH;gBAJW,MAAM;mBACN,OAAO,qBAAqB,EAAE,SAAS;gCAC9B,MAAM,aAAa,SAAS,KAAK,QAAQ,OAAO,CAAC;OAYpE;IAPC,2BAAqB;IACrB,cAAkC;IAElC,yBAAoF;IACpF,iBAA6D;IAC7D,2BAAuE;IACvE,qBAAiE;IAGnE,kEAkBC;IAED;;;;OAIG;IACH,eAFW,MAAM,iBAahB;IAED;;;;OAIG;IACH,YAFW,MAAM,mCAahB;IAED;;;;OAIG;IACH,YAFW,MAAM,oBAahB;CACF;;;;iBA3GY,OAAO,SAAS,EAAE,SAAS;;;;;;;cAE3B,OAAO,SAAS,CAAC;iBACjB,OAAO,WAAW,EAAE,SAAS;YAF7B,OAAO,SAAS,EAAE,IAAI"} \ No newline at end of file diff --git a/dist/src/peer-store/key-book.d.ts b/dist/src/peer-store/key-book.d.ts new file mode 100644 index 0000000000..125dbf9212 --- /dev/null +++ b/dist/src/peer-store/key-book.d.ts @@ -0,0 +1,40 @@ +export = PeerStoreKeyBook; +/** + * @implements {KeyBook} + */ +declare class PeerStoreKeyBook implements KeyBook { + /** + * The KeyBook is responsible for keeping the known public keys of a peer. + * + * @param {PeerStore["emit"]} emit + * @param {import('./types').Store} store + */ + constructor(emit: PeerStore["emit"], store: import('./types').Store); + _emit: (event: U, ...args: Parameters) => boolean; + _store: import("./types").Store; + /** + * Set the Peer public key + * + * @param {PeerId} peerId + * @param {PublicKey} publicKey + */ + set(peerId: PeerId, publicKey: PublicKey): Promise; + /** + * Get Public key of the given PeerId, if stored + * + * @param {PeerId} peerId + */ + get(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; +} +declare namespace PeerStoreKeyBook { + export { PeerStore, KeyBook, PublicKey }; +} +type KeyBook = import('./types').KeyBook; +import PeerId = require("peer-id"); +type PublicKey = import('libp2p-interfaces/src/keys/types').PublicKey; +type PeerStore = import('./types').PeerStore; +//# sourceMappingURL=key-book.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/key-book.d.ts.map b/dist/src/peer-store/key-book.d.ts.map new file mode 100644 index 0000000000..49d9f415de --- /dev/null +++ b/dist/src/peer-store/key-book.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"key-book.d.ts","sourceRoot":"","sources":["../../../src/peer-store/key-book.js"],"names":[],"mappings":";AAoBA;;GAEG;AACH;IACE;;;;;OAKG;IACH,kBAHW,SAAS,CAAC,MAAM,CAAC,SACjB,OAAO,SAAS,EAAE,KAAK,EAKjC;IAFC,2IAAiB;IACjB,gCAAmB;IAGrB;;;;;OAKG;IACH,YAHW,MAAM,aACN,SAAS,iBA4CnB;IAED;;;;OAIG;IACH,YAFW,MAAM,6EAwBhB;IAED;;OAEG;IACH,eAFW,MAAM,iBAsBhB;CACF;;;;eAhIY,OAAO,SAAS,EAAE,OAAO;;iBACzB,OAAO,kCAAkC,EAAE,SAAS;iBAFpD,OAAO,SAAS,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/peer-store/metadata-book.d.ts b/dist/src/peer-store/metadata-book.d.ts new file mode 100644 index 0000000000..b565c9ea32 --- /dev/null +++ b/dist/src/peer-store/metadata-book.d.ts @@ -0,0 +1,58 @@ +export = PeerStoreMetadataBook; +/** + * @implements {MetadataBook} + */ +declare class PeerStoreMetadataBook implements MetadataBook { + /** + * The MetadataBook is responsible for keeping the known supported + * protocols of a peer + * + * @param {PeerStore["emit"]} emit + * @param {import('./types').Store} store + */ + constructor(emit: PeerStore["emit"], store: import('./types').Store); + _emit: (event: U, ...args: Parameters) => boolean; + _store: import("./types").Store; + /** + * Get the known data of a provided peer + * + * @param {PeerId} peerId + */ + get(peerId: PeerId): Promise>; + /** + * Get specific metadata value, if it exists + * + * @param {PeerId} peerId + * @param {string} key + */ + getValue(peerId: PeerId, key: string): Promise; + /** + * @param {PeerId} peerId + * @param {Map} metadata + */ + set(peerId: PeerId, metadata: Map): Promise; + /** + * Set metadata key and value of a provided peer + * + * @param {PeerId} peerId + * @param {string} key - metadata key + * @param {Uint8Array} value - metadata value + */ + setValue(peerId: PeerId, key: string, value: Uint8Array): Promise; + /** + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + * @param {string} key + */ + deleteValue(peerId: PeerId, key: string): Promise; +} +declare namespace PeerStoreMetadataBook { + export { PeerStore, MetadataBook }; +} +type MetadataBook = import('./types').MetadataBook; +import PeerId = require("peer-id"); +type PeerStore = import('./types').PeerStore; +//# sourceMappingURL=metadata-book.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/metadata-book.d.ts.map b/dist/src/peer-store/metadata-book.d.ts.map new file mode 100644 index 0000000000..72fae7cf75 --- /dev/null +++ b/dist/src/peer-store/metadata-book.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata-book.d.ts","sourceRoot":"","sources":["../../../src/peer-store/metadata-book.js"],"names":[],"mappings":";AAmBA;;GAEG;AACH;IACE;;;;;;OAMG;IACH,kBAHW,SAAS,CAAC,MAAM,CAAC,SACjB,OAAO,SAAS,EAAE,KAAK,EAKjC;IAFC,2IAAiB;IACjB,gCAAmB;IAGrB;;;;OAIG;IACH,YAFW,MAAM,0BA0BhB;IAED;;;;;OAKG;IACH,iBAHW,MAAM,OACN,MAAM,mCAwBhB;IAED;;;OAGG;IACH,YAHW,MAAM,YACN,IAAI,MAAM,EAAE,UAAU,CAAC,iBA2BjC;IAED;;;;;;OAMG;IACH,iBAJW,MAAM,OACN,MAAM,SACN,UAAU,iBA0CpB;IAED;;OAEG;IACH,eAFW,MAAM,iBA8BhB;IAED;;;OAGG;IACH,oBAHW,MAAM,OACN,MAAM,iBAmChB;CACF;;;;oBAzOY,OAAO,SAAS,EAAE,YAAY;;iBAD9B,OAAO,SAAS,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/peer-store/pb/peer.d.ts b/dist/src/peer-store/pb/peer.d.ts new file mode 100644 index 0000000000..e6ccdfe6c1 --- /dev/null +++ b/dist/src/peer-store/pb/peer.d.ts @@ -0,0 +1,222 @@ +import * as $protobuf from "protobufjs"; +/** Properties of a Peer. */ +export interface IPeer { + + /** Peer addresses */ + addresses?: (IAddress[]|null); + + /** Peer protocols */ + protocols?: (string[]|null); + + /** Peer metadata */ + metadata?: (IMetadata[]|null); + + /** Peer pubKey */ + pubKey?: (Uint8Array|null); + + /** Peer peerRecordEnvelope */ + peerRecordEnvelope?: (Uint8Array|null); +} + +/** Represents a Peer. */ +export class Peer implements IPeer { + + /** + * Constructs a new Peer. + * @param [p] Properties to set + */ + constructor(p?: IPeer); + + /** Peer addresses. */ + public addresses: IAddress[]; + + /** Peer protocols. */ + public protocols: string[]; + + /** Peer metadata. */ + public metadata: IMetadata[]; + + /** Peer pubKey. */ + public pubKey?: (Uint8Array|null); + + /** Peer peerRecordEnvelope. */ + public peerRecordEnvelope?: (Uint8Array|null); + + /** Peer _pubKey. */ + public _pubKey?: "pubKey"; + + /** Peer _peerRecordEnvelope. */ + public _peerRecordEnvelope?: "peerRecordEnvelope"; + + /** + * Encodes the specified Peer message. Does not implicitly {@link Peer.verify|verify} messages. + * @param m Peer message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IPeer, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Peer message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Peer + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Peer; + + /** + * Creates a Peer message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Peer + */ + public static fromObject(d: { [k: string]: any }): Peer; + + /** + * Creates a plain object from a Peer message. Also converts values to other types if specified. + * @param m Peer + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Peer, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Peer to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Properties of an Address. */ +export interface IAddress { + + /** Address multiaddr */ + multiaddr?: (Uint8Array|null); + + /** Address isCertified */ + isCertified?: (boolean|null); +} + +/** Represents an Address. */ +export class Address implements IAddress { + + /** + * Constructs a new Address. + * @param [p] Properties to set + */ + constructor(p?: IAddress); + + /** Address multiaddr. */ + public multiaddr: Uint8Array; + + /** Address isCertified. */ + public isCertified?: (boolean|null); + + /** Address _isCertified. */ + public _isCertified?: "isCertified"; + + /** + * Encodes the specified Address message. Does not implicitly {@link Address.verify|verify} messages. + * @param m Address message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IAddress, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Address message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Address + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Address; + + /** + * Creates an Address message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Address + */ + public static fromObject(d: { [k: string]: any }): Address; + + /** + * Creates a plain object from an Address message. Also converts values to other types if specified. + * @param m Address + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Address, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Address to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Properties of a Metadata. */ +export interface IMetadata { + + /** Metadata key */ + key?: (string|null); + + /** Metadata value */ + value?: (Uint8Array|null); +} + +/** Represents a Metadata. */ +export class Metadata implements IMetadata { + + /** + * Constructs a new Metadata. + * @param [p] Properties to set + */ + constructor(p?: IMetadata); + + /** Metadata key. */ + public key: string; + + /** Metadata value. */ + public value: Uint8Array; + + /** + * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages. + * @param m Metadata message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IMetadata, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Metadata message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Metadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Metadata; + + /** + * Creates a Metadata message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Metadata + */ + public static fromObject(d: { [k: string]: any }): Metadata; + + /** + * Creates a plain object from a Metadata message. Also converts values to other types if specified. + * @param m Metadata + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Metadata, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Metadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} diff --git a/dist/src/peer-store/proto-book.d.ts b/dist/src/peer-store/proto-book.d.ts new file mode 100644 index 0000000000..b73f8a875b --- /dev/null +++ b/dist/src/peer-store/proto-book.d.ts @@ -0,0 +1,43 @@ +export = PersistentProtoBook; +/** + * @implements {ProtoBook} + */ +declare class PersistentProtoBook implements ProtoBook { + /** + * @param {PeerStore["emit"]} emit + * @param {import('./types').Store} store + */ + constructor(emit: PeerStore["emit"], store: import('./types').Store); + _emit: (event: U, ...args: Parameters) => boolean; + _store: import("./types").Store; + /** + * @param {PeerId} peerId + */ + get(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + * @param {string[]} protocols + */ + set(peerId: PeerId, protocols: string[]): Promise; + /** + * @param {PeerId} peerId + * @param {string[]} protocols + */ + add(peerId: PeerId, protocols: string[]): Promise; + /** + * @param {PeerId} peerId + * @param {string[]} protocols + */ + remove(peerId: PeerId, protocols: string[]): Promise; + /** + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; +} +declare namespace PersistentProtoBook { + export { PeerStore, ProtoBook }; +} +type ProtoBook = import('./types').ProtoBook; +import PeerId = require("peer-id"); +type PeerStore = import('./types').PeerStore; +//# sourceMappingURL=proto-book.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/proto-book.d.ts.map b/dist/src/peer-store/proto-book.d.ts.map new file mode 100644 index 0000000000..ddfa8db338 --- /dev/null +++ b/dist/src/peer-store/proto-book.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proto-book.d.ts","sourceRoot":"","sources":["../../../src/peer-store/proto-book.js"],"names":[],"mappings":";AAkBA;;GAEG;AACH;IACE;;;OAGG;IACH,kBAHW,SAAS,CAAC,MAAM,CAAC,SACjB,OAAO,SAAS,EAAE,KAAK,EAKjC;IAFC,2IAAiB;IACjB,gCAAmB;IAGrB;;OAEG;IACH,YAFW,MAAM,qBAqBhB;IAED;;;OAGG;IACH,YAHW,MAAM,aACN,MAAM,EAAE,iBA6ClB;IAED;;;OAGG;IACH,YAHW,MAAM,aACN,MAAM,EAAE,iBA8ClB;IAED;;;OAGG;IACH,eAHW,MAAM,aACN,MAAM,EAAE,iBAgDlB;IAED;;OAEG;IACH,eAFW,MAAM,iBA0BhB;CACF;;;;iBAjOY,OAAO,SAAS,EAAE,SAAS;;iBAD3B,OAAO,SAAS,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/peer-store/store.d.ts b/dist/src/peer-store/store.d.ts new file mode 100644 index 0000000000..09115b109d --- /dev/null +++ b/dist/src/peer-store/store.d.ts @@ -0,0 +1,73 @@ +export = PersistentStore; +declare class PersistentStore { + /** + * @param {import('interface-datastore').Datastore} datastore + */ + constructor(datastore: import('interface-datastore').Datastore); + _datastore: import("interface-datastore").Datastore; + lock: any; + /** + * @param {PeerId} peerId + * @returns {Key} + */ + _peerIdToDatastoreKey(peerId: PeerId): Key; + /** + * @param {PeerId} peerId + */ + has(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + */ + delete(peerId: PeerId): Promise; + /** + * @param {PeerId} peerId + * @returns {Promise} peer + */ + load(peerId: PeerId): Promise; + /** + * @param {Peer} peer + */ + save(peer: Peer): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + */ + patch(peerId: PeerId, data: Partial): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + */ + patchOrCreate(peerId: PeerId, data: Partial): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + * @param {Peer} peer + */ + _patch(peerId: PeerId, data: Partial, peer: Peer): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + */ + merge(peerId: PeerId, data: Partial): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + */ + mergeOrCreate(peerId: PeerId, data: Partial): Promise; + /** + * @param {PeerId} peerId + * @param {Partial} data + * @param {Peer} peer + */ + _merge(peerId: PeerId, data: Partial, peer: Peer): Promise; + all(): AsyncGenerator; +} +declare namespace PersistentStore { + export { PeerStore, EventName, Peer }; +} +import PeerId = require("peer-id"); +import { Key } from "interface-datastore/key"; +type Peer = import('./types').Peer; +type PeerStore = import('./types').PeerStore; +type EventName = import('./types').EventName; +//# sourceMappingURL=store.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/store.d.ts.map b/dist/src/peer-store/store.d.ts.map new file mode 100644 index 0000000000..aaa5820867 --- /dev/null +++ b/dist/src/peer-store/store.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/peer-store/store.js"],"names":[],"mappings":";AA2BA;IACE;;OAEG;IACH,uBAFW,OAAO,qBAAqB,EAAE,SAAS,EAOjD;IAJC,oDAA2B;IAC3B,UAEE;IAGJ;;;OAGG;IACH,8BAHW,MAAM,GACJ,GAAG,CAUf;IAED;;OAEG;IACH,YAFW,MAAM,oBAIhB;IAED;;OAEG;IACH,eAFW,MAAM,iBAIhB;IAED;;;OAGG;IACH,aAHW,MAAM,GACJ,QAAQ,OAAO,SAAS,EAAE,IAAI,CAAC,CAuB3C;IAED;;OAEG;IACH,WAFW,IAAI,mCAqCd;IAED;;;OAGG;IACH,cAHW,MAAM,QACN,QAAQ,IAAI,CAAC,mCAMvB;IAED;;;OAGG;IACH,sBAHW,MAAM,QACN,QAAQ,IAAI,CAAC,mCAiBvB;IAED;;;;OAIG;IACH,eAJW,MAAM,QACN,QAAQ,IAAI,CAAC,QACb,IAAI,mCAQd;IAED;;;OAGG;IACH,cAHW,MAAM,QACN,QAAQ,IAAI,CAAC,mCAMvB;IAED;;;OAGG;IACH,sBAHW,MAAM,QACN,QAAQ,IAAI,CAAC,mCAiBvB;IAED;;;;OAIG;IACH,eAJW,MAAM,QACN,QAAQ,IAAI,CAAC,QACb,IAAI,mCAoCd;IAED,6DAUC;CACF;;;;;;YA9OY,OAAO,SAAS,EAAE,IAAI;iBAFtB,OAAO,SAAS,EAAE,SAAS;iBAC3B,OAAO,SAAS,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/peer-store/types.d.ts b/dist/src/peer-store/types.d.ts new file mode 100644 index 0000000000..e02c65ce1a --- /dev/null +++ b/dist/src/peer-store/types.d.ts @@ -0,0 +1,202 @@ +import type PeerId from 'peer-id'; +import type { Multiaddr } from 'multiaddr'; +import type Envelope from '../record/envelope'; +import type { PublicKey } from 'libp2p-interfaces/src/keys/types'; +export interface Address { + /** + * Peer multiaddr + */ + multiaddr: Multiaddr; + /** + * Obtained from a signed peer record + */ + isCertified: boolean; +} +export interface Peer { + /** + * Peer's peer-id instance + */ + id: PeerId; + /** + * Peer's addresses containing its multiaddrs and metadata + */ + addresses: Address[]; + /** + * Peer's supported protocols + */ + protocols: string[]; + /** + * Peer's metadata map + */ + metadata: Map; + /** + * May be set if the key that this Peer has is an RSA key + */ + pubKey?: PublicKey; + /** + * The last peer record envelope received + */ + peerRecordEnvelope?: Uint8Array; +} +export interface CertifiedRecord { + raw: Uint8Array; + seqNumber: number; +} +export interface AddressBookEntry { + addresses: Address[]; + record: CertifiedRecord; +} +export interface Book { + /** + * Get the known data of a peer + */ + get: (peerId: PeerId) => Promise; + /** + * Set the known data of a peer + */ + set: (peerId: PeerId, data: Type) => Promise; + /** + * Remove the known data of a peer + */ + delete: (peerId: PeerId) => Promise; +} +/** + * AddressBook containing a map of peerIdStr to Address. + */ +export interface AddressBook { + /** + * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope. + * This will return a boolean that indicates if the record was successfully processed and added + * into the AddressBook + */ + consumePeerRecord: (envelope: Envelope) => Promise; + /** + * Get the raw Envelope for a peer. Returns + * undefined if no Envelope is found + */ + getRawEnvelope: (peerId: PeerId) => Promise; + /** + * Get an Envelope containing a PeerRecord for the given peer. + * Returns undefined if no record exists. + */ + getPeerRecord: (peerId: PeerId) => Promise; + /** + * Add known addresses of a provided peer. + * If the peer is not known, it is set with the given addresses. + */ + add: (peerId: PeerId, multiaddrs: Multiaddr[]) => Promise; + /** + * Set the known addresses of a peer + */ + set: (peerId: PeerId, data: Multiaddr[]) => Promise; + /** + * Return the known addresses of a peer + */ + get: (peerId: PeerId) => Promise; + /** + * Get the known multiaddrs for a given peer. All returned multiaddrs + * will include the encapsulated `PeerId` of the peer. + */ + getMultiaddrsForPeer: (peerId: PeerId, addressSorter?: (ms: Address[]) => Address[]) => Promise; +} +/** + * KeyBook containing a map of peerIdStr to their PeerId with public keys. + */ +export interface KeyBook { + /** + * Get the known data of a peer + */ + get: (peerId: PeerId) => Promise; + /** + * Set the known data of a peer + */ + set: (peerId: PeerId, data: PublicKey) => Promise; + /** + * Remove the known data of a peer + */ + delete: (peerId: PeerId) => Promise; +} +/** + * MetadataBook containing a map of peerIdStr to their metadata Map. + */ +export interface MetadataBook extends Book> { + /** + * Set a specific metadata value + */ + setValue: (peerId: PeerId, key: string, value: Uint8Array) => Promise; + /** + * Get specific metadata value, if it exists + */ + getValue: (peerId: PeerId, key: string) => Promise; + /** + * Deletes the provided peer metadata key from the book + */ + deleteValue: (peerId: PeerId, key: string) => Promise; +} +/** + * ProtoBook containing a map of peerIdStr to supported protocols. + */ +export interface ProtoBook extends Book { + /** + * Adds known protocols of a provided peer. + * If the peer was not known before, it will be added. + */ + add: (peerId: PeerId, protocols: string[]) => Promise; + /** + * Removes known protocols of a provided peer. + * If the protocols did not exist before, nothing will be done. + */ + remove: (peerId: PeerId, protocols: string[]) => Promise; +} +export interface PeerProtocolsChangeEvent { + peerId: PeerId; + protocols: string[]; +} +export interface PeerMultiaddrsChangeEvent { + peerId: PeerId; + multiaddrs: Multiaddr[]; +} +export interface PeerPublicKeyChangeEvent { + peerId: PeerId; + pubKey?: PublicKey; +} +export interface PeerMetadataChangeEvent { + peerId: PeerId; + metadata: Map; +} +export declare type EventName = 'peer' | 'change:protocols' | 'change:multiaddrs' | 'change:pubkey' | 'change:metadata'; +export interface PeerStoreEvents { + 'peer': (event: PeerId) => void; + 'change:protocols': (event: PeerProtocolsChangeEvent) => void; + 'change:multiaddrs': (event: PeerMultiaddrsChangeEvent) => void; + 'change:pubkey': (event: PeerPublicKeyChangeEvent) => void; + 'change:metadata': (event: PeerMetadataChangeEvent) => void; +} +export interface PeerStore { + addressBook: AddressBook; + keyBook: KeyBook; + metadataBook: MetadataBook; + protoBook: ProtoBook; + getPeers: () => AsyncIterable; + delete: (peerId: PeerId) => Promise; + has: (peerId: PeerId) => Promise; + get: (peerId: PeerId) => Promise; + on: (event: U, listener: PeerStoreEvents[U]) => this; + once: (event: U, listener: PeerStoreEvents[U]) => this; + emit: (event: U, ...args: Parameters) => boolean; +} +export interface Store { + has: (peerId: PeerId) => Promise; + save: (peer: Peer) => Promise; + load: (peerId: PeerId) => Promise; + merge: (peerId: PeerId, data: Partial) => Promise; + mergeOrCreate: (peerId: PeerId, data: Partial) => Promise; + patch: (peerId: PeerId, data: Partial) => Promise; + patchOrCreate: (peerId: PeerId, data: Partial) => Promise; + all: () => AsyncIterable; + lock: { + readLock: () => Promise<() => void>; + writeLock: () => Promise<() => void>; + }; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/src/peer-store/types.d.ts.map b/dist/src/peer-store/types.d.ts.map new file mode 100644 index 0000000000..b7e7596dc3 --- /dev/null +++ b/dist/src/peer-store/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/peer-store/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,SAAS,CAAA;AACjC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAC1C,OAAO,KAAK,QAAQ,MAAM,oBAAoB,CAAA;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAA;AAEjE,MAAM,WAAW,OAAO;IACtB;;OAEG;IACH,SAAS,EAAE,SAAS,CAAA;IAEpB;;OAEG;IACH,WAAW,EAAE,OAAO,CAAA;CACrB;AAED,MAAM,WAAW,IAAI;IACnB;;OAEG;IACH,EAAE,EAAE,MAAM,CAAA;IAEV;;OAEG;IACH,SAAS,EAAE,OAAO,EAAE,CAAA;IAEpB;;OAEG;IACH,SAAS,EAAE,MAAM,EAAE,CAAA;IAEnB;;OAEG;IACH,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAEjC;;OAEG;IACH,MAAM,CAAC,EAAE,SAAS,CAAA;IAElB;;OAEG;IACH,kBAAkB,CAAC,EAAE,UAAU,CAAA;CAChC;AAED,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,UAAU,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,MAAM,WAAW,IAAI,CAAC,IAAI;IACxB;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAEtC;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAElD;;OAEG;IACH,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAE3D;;;OAGG;IACH,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAA;IAEnE;;;OAGG;IACH,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAA;IAEhE;;;OAGG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAE/D;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAEzD;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAA;IAE3C;;;OAGG;IACH,oBAAoB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,CAAC,SAAS,EAAE,CAAC,CAAA;CAC7G;AAED;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAA;IAEvD;;OAEG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAEvD;;OAEG;IACH,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACjE;;OAEG;IACH,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3E;;OAEG;IACH,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAA;IAE1E;;OAEG;IACH,WAAW,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAC5D;AAED;;GAEG;AACH,MAAM,WAAW,SAAU,SAAQ,IAAI,CAAC,MAAM,EAAE,CAAC;IAC/C;;;OAGG;IACH,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3D;;;OAGG;IACH,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAC/D;AAED,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,EAAE,CAAA;CACpB;AAED,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,SAAS,EAAE,CAAA;CACxB;AAED,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,SAAS,CAAA;CACnB;AAED,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;CAClC;AAED,oBAAY,SAAS,GAAG,MAAM,GAAG,kBAAkB,GAAG,mBAAmB,GAAG,eAAe,GAAG,iBAAiB,CAAA;AAE/G,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/B,kBAAkB,EAAE,CAAC,KAAK,EAAE,wBAAwB,KAAK,IAAI,CAAA;IAC7D,mBAAmB,EAAE,CAAC,KAAK,EAAE,yBAAyB,KAAK,IAAI,CAAA;IAC/D,eAAe,EAAE,CAAC,KAAK,EAAE,wBAAwB,KAAK,IAAI,CAAA;IAC1D,iBAAiB,EAAE,CAAC,KAAK,EAAE,uBAAuB,KAAK,IAAI,CAAA;CAC5D;AAED,MAAM,WAAW,SAAS;IACxB,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,SAAS,CAAA;IAEpB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,CAAA;IACnC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACzC,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACtC,EAAE,EAAE,CAAC,CAAC,SAAS,MAAM,eAAe,EAClC,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC,KACnC,IAAI,CAAA;IACT,IAAI,EAAE,CAAC,CAAC,SAAS,MAAM,eAAe,EACpC,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC,KACnC,IAAI,CAAA;IACT,IAAI,EAAE,CAAC,CAAC,SAAS,MAAM,eAAe,EACpC,KAAK,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,KAC9C,OAAO,CAAA;CACb;AAED,MAAM,WAAW,KAAK;IACpB,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACzC,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACnC,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACvC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7D,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACrE,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7D,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACrE,GAAG,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,CAAA;IAE9B,IAAI,EAAE;QACJ,QAAQ,EAAE,MAAM,OAAO,CAAC,MAAM,IAAI,CAAC,CAAA;QACnC,SAAS,EAAE,MAAM,OAAO,CAAC,MAAM,IAAI,CAAC,CAAA;KACrC,CAAA;CACF"} \ No newline at end of file diff --git a/dist/src/ping/constants.d.ts b/dist/src/ping/constants.d.ts new file mode 100644 index 0000000000..0e4a4cbbf4 --- /dev/null +++ b/dist/src/ping/constants.d.ts @@ -0,0 +1,5 @@ +export const PROTOCOL: string; +export const PING_LENGTH: number; +export const PROTOCOL_VERSION: string; +export const PROTOCOL_NAME: string; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/dist/src/ping/constants.d.ts.map b/dist/src/ping/constants.d.ts.map new file mode 100644 index 0000000000..8d84717686 --- /dev/null +++ b/dist/src/ping/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/ping/constants.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/ping/index.d.ts b/dist/src/ping/index.d.ts new file mode 100644 index 0000000000..f1d04a25fc --- /dev/null +++ b/dist/src/ping/index.d.ts @@ -0,0 +1,42 @@ +export = PingService; +/** + * @typedef {import('../')} Libp2p + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + */ +declare class PingService { + /** + * @param {import('../')} libp2p + */ + static getProtocolStr(libp2p: import('../')): string; + /** + * @param {Libp2p} libp2p + */ + constructor(libp2p: Libp2p); + _libp2p: import("../"); + /** + * A handler to register with Libp2p to process ping messages + * + * @param {Object} options + * @param {MuxedStream} options.stream + */ + handleMessage({ stream }: { + stream: MuxedStream; + }): any; + /** + * Ping a given peer and wait for its response, getting the operation latency. + * + * @param {PeerId|Multiaddr} peer + * @returns {Promise} + */ + ping(peer: PeerId | Multiaddr): Promise; +} +declare namespace PingService { + export { Libp2p, Multiaddr, PeerId, MuxedStream }; +} +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +type PeerId = import('peer-id'); +type Multiaddr = import('multiaddr').Multiaddr; +type Libp2p = import('../'); +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/ping/index.d.ts.map b/dist/src/ping/index.d.ts.map new file mode 100644 index 0000000000..15cb925937 --- /dev/null +++ b/dist/src/ping/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ping/index.js"],"names":[],"mappings":";AAiBA;;;;;GAKG;AAEH;IACE;;OAEG;IACH,8BAFW,OAAO,KAAK,CAAC,UAIvB;IAED;;OAEG;IACH,oBAFW,MAAM,EAIhB;IADC,uBAAqB;IAGvB;;;;;OAKG;IACH;QAFgC,MAAM,EAA3B,WAAW;YAIrB;IAED;;;;;OAKG;IACH,WAHW,MAAM,GAAC,SAAS,GACd,QAAQ,MAAM,CAAC,CA2B3B;CACF;;;;mBA5DY,OAAO,0CAA0C,EAAE,WAAW;cAD9D,OAAO,SAAS,CAAC;iBADjB,OAAO,WAAW,EAAE,SAAS;cAD7B,OAAO,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/src/ping/util.d.ts b/dist/src/ping/util.d.ts new file mode 100644 index 0000000000..f5d8750442 --- /dev/null +++ b/dist/src/ping/util.d.ts @@ -0,0 +1,5 @@ +/** + * @param {number} length + */ +export function rnd(length: number): Uint8Array; +//# sourceMappingURL=util.d.ts.map \ No newline at end of file diff --git a/dist/src/ping/util.d.ts.map b/dist/src/ping/util.d.ts.map new file mode 100644 index 0000000000..4ffc8a83f2 --- /dev/null +++ b/dist/src/ping/util.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../../src/ping/util.js"],"names":[],"mappings":"AAKA;;GAEG;AACH,4BAFW,MAAM,cAOhB"} \ No newline at end of file diff --git a/dist/src/pnet/crypto.d.ts b/dist/src/pnet/crypto.d.ts new file mode 100644 index 0000000000..4ea254f53b --- /dev/null +++ b/dist/src/pnet/crypto.d.ts @@ -0,0 +1,8 @@ +export function createBoxStream(nonce: Uint8Array, psk: Uint8Array): any; +export function createUnboxStream(nonce: Uint8Array, psk: Uint8Array): any; +export function decodeV1PSK(pskBuffer: Uint8Array): { + tag?: string; + codecName?: string; + psk: Uint8Array; +}; +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/dist/src/pnet/crypto.d.ts.map b/dist/src/pnet/crypto.d.ts.map new file mode 100644 index 0000000000..328d7c697f --- /dev/null +++ b/dist/src/pnet/crypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../../src/pnet/crypto.js"],"names":[],"mappings":"AAsBiC,uCAJtB,UAAU,OACV,UAAU,OAWpB;AASkC,yCAJxB,UAAU,OACV,UAAU,OAYpB;AAS4B,uCAJlB,UAAU,GAER;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,UAAU,CAAA;CAAE,CA4BjE"} \ No newline at end of file diff --git a/dist/src/pnet/errors.d.ts b/dist/src/pnet/errors.d.ts new file mode 100644 index 0000000000..e59b966e51 --- /dev/null +++ b/dist/src/pnet/errors.d.ts @@ -0,0 +1,6 @@ +export var INVALID_PEER: string; +export var INVALID_PSK: string; +export var NO_LOCAL_ID: string; +export var NO_HANDSHAKE_CONNECTION: string; +export var STREAM_ENDED: string; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/src/pnet/errors.d.ts.map b/dist/src/pnet/errors.d.ts.map new file mode 100644 index 0000000000..9db10ede62 --- /dev/null +++ b/dist/src/pnet/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/pnet/errors.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/src/pnet/index.d.ts b/dist/src/pnet/index.d.ts new file mode 100644 index 0000000000..45852e71f4 --- /dev/null +++ b/dist/src/pnet/index.d.ts @@ -0,0 +1,32 @@ +export = Protector; +/** + * @typedef {import('libp2p-interfaces/src/transport/types').MultiaddrConnection} MultiaddrConnection + */ +declare class Protector { + /** + * Takes a Private Shared Key (psk) and provides a `protect` method + * for wrapping existing connections in a private encryption stream. + * + * @param {Uint8Array} keyBuffer - The private shared key buffer + * @class + */ + constructor(keyBuffer: Uint8Array); + psk: Uint8Array; + tag: string | undefined; + /** + * Takes a given Connection and creates a private encryption stream + * between its two peers from the PSK the Protector instance was + * created with. + * + * @param {MultiaddrConnection} connection - The connection to protect + * @returns {Promise} A protected duplex iterable + */ + protect(connection: MultiaddrConnection): Promise; +} +declare namespace Protector { + export { Errors as errors, generate, MultiaddrConnection }; +} +type MultiaddrConnection = import('libp2p-interfaces/src/transport/types').MultiaddrConnection; +import Errors = require("./errors"); +declare var generate: typeof import("./key-generator"); +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/pnet/index.d.ts.map b/dist/src/pnet/index.d.ts.map new file mode 100644 index 0000000000..d64b1f6926 --- /dev/null +++ b/dist/src/pnet/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pnet/index.js"],"names":[],"mappings":";AAwBA;;GAEG;AAEH;IACE;;;;;;OAMG;IACH,uBAHW,UAAU,EAOpB;IAFC,gBAAyB;IACzB,wBAAyB;IAG3B;;;;;;;OAOG;IACH,oBAHW,mBAAmB,GACjB,QAAQ,mBAAmB,CAAC,CAgCxC;CACF;;;;2BAxDY,OAAO,uCAAuC,EAAE,mBAAmB"} \ No newline at end of file diff --git a/dist/src/pnet/key-generator.d.ts b/dist/src/pnet/key-generator.d.ts new file mode 100644 index 0000000000..52d57ceb6c --- /dev/null +++ b/dist/src/pnet/key-generator.d.ts @@ -0,0 +1,14 @@ +export = generate; +/** + * Generates a PSK that can be used in a libp2p-pnet private network + * + * @param {Uint8Array} bytes - An object to write the psk into + * @returns {void} + */ +declare function generate(bytes: Uint8Array): void; +declare namespace generate { + export { NONCE_LENGTH, KEY_LENGTH }; +} +declare var NONCE_LENGTH: number; +declare const KEY_LENGTH: 32; +//# sourceMappingURL=key-generator.d.ts.map \ No newline at end of file diff --git a/dist/src/pnet/key-generator.d.ts.map b/dist/src/pnet/key-generator.d.ts.map new file mode 100644 index 0000000000..7410c852ee --- /dev/null +++ b/dist/src/pnet/key-generator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"key-generator.d.ts","sourceRoot":"","sources":["../../../src/pnet/key-generator.js"],"names":[],"mappings":";AAOA;;;;;GAKG;AACH,iCAHW,UAAU,GACR,IAAI,CAOhB;;;;;AAfD,6BAAqB"} \ No newline at end of file diff --git a/dist/src/pubsub-adapter.d.ts b/dist/src/pubsub-adapter.d.ts new file mode 100644 index 0000000000..0443d402ce --- /dev/null +++ b/dist/src/pubsub-adapter.d.ts @@ -0,0 +1,22 @@ +export = pubsubAdapter; +/** + * @typedef {import('libp2p-interfaces/src/pubsub').InMessage} InMessage + * @typedef {import('libp2p-interfaces/src/pubsub')} PubsubRouter + */ +/** + * @param {{new(...args: any[]): PubsubRouter}} PubsubRouter + * @param {import('.')} libp2p + * @param {{ enabled: boolean; } & import(".").PubsubLocalOptions & import("libp2p-interfaces/src/pubsub").PubsubOptions} options + */ +declare function pubsubAdapter(PubsubRouter: new (...args: any[]) => PubsubRouter, libp2p: import('.'), options: { + enabled: boolean; +} & import(".").PubsubLocalOptions & import("libp2p-interfaces/src/pubsub").PubsubOptions): import("libp2p-interfaces/src/pubsub") & { + _subscribeAdapter: (topic: string) => void; + _unsubscribeAdapter: (topic: string) => void; +}; +declare namespace pubsubAdapter { + export { InMessage, PubsubRouter }; +} +type PubsubRouter = import('libp2p-interfaces/src/pubsub'); +type InMessage = import('libp2p-interfaces/src/pubsub').InMessage; +//# sourceMappingURL=pubsub-adapter.d.ts.map \ No newline at end of file diff --git a/dist/src/pubsub-adapter.d.ts.map b/dist/src/pubsub-adapter.d.ts.map new file mode 100644 index 0000000000..56c1ebeb42 --- /dev/null +++ b/dist/src/pubsub-adapter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pubsub-adapter.d.ts","sourceRoot":"","sources":["../../src/pubsub-adapter.js"],"names":[],"mappings":";AAGA;;;GAGG;AAEH;;;;GAIG;AACH,2DAJyB,GAAG,EAAE,KAAG,YAAY,UAClC,OAAO,GAAG,CAAC,WACX;IAAE,OAAO,EAAE,OAAO,CAAC;CAAE,GAAG,OAAO,GAAG,EAAE,kBAAkB,GAAG,OAAO,8BAA8B,EAAE,aAAa;;;EA+CvH;;;;oBArDY,OAAO,8BAA8B,CAAC;iBADtC,OAAO,8BAA8B,EAAE,SAAS"} \ No newline at end of file diff --git a/dist/src/record/envelope/envelope.d.ts b/dist/src/record/envelope/envelope.d.ts new file mode 100644 index 0000000000..440590c14b --- /dev/null +++ b/dist/src/record/envelope/envelope.d.ts @@ -0,0 +1,77 @@ +import * as $protobuf from "protobufjs"; +/** Properties of an Envelope. */ +export interface IEnvelope { + + /** Envelope publicKey */ + publicKey?: (Uint8Array|null); + + /** Envelope payloadType */ + payloadType?: (Uint8Array|null); + + /** Envelope payload */ + payload?: (Uint8Array|null); + + /** Envelope signature */ + signature?: (Uint8Array|null); +} + +/** Represents an Envelope. */ +export class Envelope implements IEnvelope { + + /** + * Constructs a new Envelope. + * @param [p] Properties to set + */ + constructor(p?: IEnvelope); + + /** Envelope publicKey. */ + public publicKey: Uint8Array; + + /** Envelope payloadType. */ + public payloadType: Uint8Array; + + /** Envelope payload. */ + public payload: Uint8Array; + + /** Envelope signature. */ + public signature: Uint8Array; + + /** + * Encodes the specified Envelope message. Does not implicitly {@link Envelope.verify|verify} messages. + * @param m Envelope message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IEnvelope, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Envelope message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns Envelope + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Envelope; + + /** + * Creates an Envelope message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns Envelope + */ + public static fromObject(d: { [k: string]: any }): Envelope; + + /** + * Creates a plain object from an Envelope message. Also converts values to other types if specified. + * @param m Envelope + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: Envelope, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Envelope to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} diff --git a/dist/src/record/envelope/index.d.ts b/dist/src/record/envelope/index.d.ts new file mode 100644 index 0000000000..c6ca9af4b2 --- /dev/null +++ b/dist/src/record/envelope/index.d.ts @@ -0,0 +1,80 @@ +export = Envelope; +/** + * @typedef {import('libp2p-interfaces/src/record/types').Record} Record + */ +declare class Envelope { + /** + * The Envelope is responsible for keeping an arbitrary signed record + * by a libp2p peer. + * + * @class + * @param {object} params + * @param {PeerId} params.peerId + * @param {Uint8Array} params.payloadType + * @param {Uint8Array} params.payload - marshaled record + * @param {Uint8Array} params.signature - signature of the domain string :: type hint :: payload. + */ + constructor({ peerId, payloadType, payload, signature }: { + peerId: PeerId; + payloadType: Uint8Array; + payload: Uint8Array; + signature: Uint8Array; + }); + peerId: PeerId; + payloadType: Uint8Array; + payload: Uint8Array; + signature: Uint8Array; + _marshal: Uint8Array | undefined; + /** + * Marshal the envelope content. + * + * @returns {Uint8Array} + */ + marshal(): Uint8Array; + /** + * Verifies if the other Envelope is identical to this one. + * + * @param {Envelope} other + * @returns {boolean} + */ + equals(other: Envelope): boolean; + /** + * Validate envelope data signature for the given domain. + * + * @param {string} domain + * @returns {Promise} + */ + validate(domain: string): Promise; +} +declare namespace Envelope { + export { createFromProtobuf, seal, openAndCertify, Record }; +} +import PeerId = require("peer-id"); +/** + * Unmarshal a serialized Envelope protobuf message. + * + * @param {Uint8Array} data + * @returns {Promise} + */ +declare function createFromProtobuf(data: Uint8Array): Promise; +/** + * Seal marshals the given Record, places the marshaled bytes inside an Envelope + * and signs it with the given peerId's private key. + * + * @async + * @param {Record} record + * @param {PeerId} peerId + * @returns {Promise} + */ +declare function seal(record: Record, peerId: PeerId): Promise; +/** + * Open and certify a given marshalled envelope. + * Data is unmarshalled and the signature validated for the given domain. + * + * @param {Uint8Array} data + * @param {string} domain + * @returns {Promise} + */ +declare function openAndCertify(data: Uint8Array, domain: string): Promise; +type Record = import('libp2p-interfaces/src/record/types').Record; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/record/envelope/index.d.ts.map b/dist/src/record/envelope/index.d.ts.map new file mode 100644 index 0000000000..83f4199653 --- /dev/null +++ b/dist/src/record/envelope/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/record/envelope/index.js"],"names":[],"mappings":";AAcA;;GAEG;AAEH;IACE;;;;;;;;;;OAUG;IACH;QAL0B,MAAM,EAArB,MAAM;QACa,WAAW,EAA9B,UAAU;QACS,OAAO,EAA1B,UAAU;QACS,SAAS,EAA5B,UAAU;OAUpB;IAPC,eAAoB;IACpB,wBAA8B;IAC9B,oBAAsB;IACtB,sBAA0B;IAG1B,iCAAyB;IAG3B;;;;OAIG;IACH,WAFa,UAAU,CAiBtB;IAED;;;;;OAKG;IACH,cAHW,QAAQ,GACN,OAAO,CAOnB;IAED;;;;;OAKG;IACH,iBAHW,MAAM,GACJ,QAAQ,OAAO,CAAC,CAM5B;CACF;;;;;AAkCD;;;;;GAKG;AACH,0CAHW,UAAU,GACR,QAAQ,QAAQ,CAAC,CAY7B;AAED;;;;;;;;GAQG;AACH,8BAJW,MAAM,UACN,MAAM,GACJ,QAAQ,QAAQ,CAAC,CAgB7B;AAED;;;;;;;GAOG;AACH,sCAJW,UAAU,UACV,MAAM,GACJ,QAAQ,QAAQ,CAAC,CAW7B;cArKY,OAAO,oCAAoC,EAAE,MAAM"} \ No newline at end of file diff --git a/dist/src/record/peer-record/consts.d.ts b/dist/src/record/peer-record/consts.d.ts new file mode 100644 index 0000000000..1ed2c98295 --- /dev/null +++ b/dist/src/record/peer-record/consts.d.ts @@ -0,0 +1,4 @@ +declare const domain: "libp2p-peer-record"; +declare const payloadType: Uint8Array; +export { domain as ENVELOPE_DOMAIN_PEER_RECORD, payloadType as ENVELOPE_PAYLOAD_TYPE_PEER_RECORD }; +//# sourceMappingURL=consts.d.ts.map \ No newline at end of file diff --git a/dist/src/record/peer-record/consts.d.ts.map b/dist/src/record/peer-record/consts.d.ts.map new file mode 100644 index 0000000000..e0b22c4e1e --- /dev/null +++ b/dist/src/record/peer-record/consts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../../src/record/peer-record/consts.js"],"names":[],"mappings":"AAGA,2CAAmC;AAKnC,sCAA2C"} \ No newline at end of file diff --git a/dist/src/record/peer-record/index.d.ts b/dist/src/record/peer-record/index.d.ts new file mode 100644 index 0000000000..4f01d61cd1 --- /dev/null +++ b/dist/src/record/peer-record/index.d.ts @@ -0,0 +1,60 @@ +export = PeerRecord; +/** + * @typedef {import('../../peer-store/types').Address} Address + * @typedef {import('libp2p-interfaces/src/record/types').Record} Record + */ +/** + * @implements {Record} + */ +declare class PeerRecord implements Record { + /** + * The PeerRecord is used for distributing peer routing records across the network. + * It contains the peer's reachable listen addresses. + * + * @class + * @param {Object} params + * @param {PeerId} params.peerId + * @param {Multiaddr[]} params.multiaddrs - addresses of the associated peer. + * @param {number} [params.seqNumber] - monotonically-increasing sequence counter that's used to order PeerRecords in time. + */ + constructor({ peerId, multiaddrs, seqNumber }: { + peerId: PeerId; + multiaddrs: Multiaddr[]; + seqNumber?: number | undefined; + }); + domain: string; + codec: Uint8Array; + peerId: PeerId; + multiaddrs: Multiaddr[]; + seqNumber: number; + _marshal: Uint8Array | undefined; + /** + * Marshal a record to be used in an envelope. + * + * @returns {Uint8Array} + */ + marshal(): Uint8Array; + /** + * Returns true if `this` record equals the `other`. + * + * @param {unknown} other + * @returns {boolean} + */ + equals(other: unknown): boolean; +} +declare namespace PeerRecord { + export { createFromProtobuf, ENVELOPE_DOMAIN_PEER_RECORD as DOMAIN, Address, Record }; +} +type Record = import('libp2p-interfaces/src/record/types').Record; +import PeerId = require("peer-id"); +import { Multiaddr } from "multiaddr"; +/** + * Unmarshal Peer Record Protobuf. + * + * @param {Uint8Array} buf - marshaled peer record. + * @returns {PeerRecord} + */ +declare function createFromProtobuf(buf: Uint8Array): PeerRecord; +import { ENVELOPE_DOMAIN_PEER_RECORD } from "./consts"; +type Address = import('../../peer-store/types').Address; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/src/record/peer-record/index.d.ts.map b/dist/src/record/peer-record/index.d.ts.map new file mode 100644 index 0000000000..8b290817f3 --- /dev/null +++ b/dist/src/record/peer-record/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/record/peer-record/index.js"],"names":[],"mappings":";AAYA;;;GAGG;AAEH;;GAEG;AACH;IACE;;;;;;;;;OASG;IACH;QAJ0B,MAAM,EAArB,MAAM;QACc,UAAU,EAA9B,SAAS,EAAE;QACK,SAAS;OAYnC;IATC,eAAyC;IACzC,kBAA8C;IAE9C,eAAoB;IACpB,wBAA4B;IAC5B,kBAA0B;IAG1B,iCAAyB;IAG3B;;;;OAIG;IACH,WAFa,UAAU,CAgBtB;IAED;;;;;OAKG;IACH,cAHW,OAAO,GACL,OAAO,CAuBnB;CACF;;;;cA9EY,OAAO,oCAAoC,EAAE,MAAM;;;AAgFhE;;;;;GAKG;AACH,yCAHW,UAAU,GACR,UAAU,CAUtB;;eA/FY,OAAO,wBAAwB,EAAE,OAAO"} \ No newline at end of file diff --git a/dist/src/record/peer-record/peer-record.d.ts b/dist/src/record/peer-record/peer-record.d.ts new file mode 100644 index 0000000000..a851b53307 --- /dev/null +++ b/dist/src/record/peer-record/peer-record.d.ts @@ -0,0 +1,133 @@ +import * as $protobuf from "protobufjs"; +/** Properties of a PeerRecord. */ +export interface IPeerRecord { + + /** PeerRecord peerId */ + peerId?: (Uint8Array|null); + + /** PeerRecord seq */ + seq?: (number|null); + + /** PeerRecord addresses */ + addresses?: (PeerRecord.IAddressInfo[]|null); +} + +/** Represents a PeerRecord. */ +export class PeerRecord implements IPeerRecord { + + /** + * Constructs a new PeerRecord. + * @param [p] Properties to set + */ + constructor(p?: IPeerRecord); + + /** PeerRecord peerId. */ + public peerId: Uint8Array; + + /** PeerRecord seq. */ + public seq: number; + + /** PeerRecord addresses. */ + public addresses: PeerRecord.IAddressInfo[]; + + /** + * Encodes the specified PeerRecord message. Does not implicitly {@link PeerRecord.verify|verify} messages. + * @param m PeerRecord message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: IPeerRecord, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PeerRecord message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns PeerRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): PeerRecord; + + /** + * Creates a PeerRecord message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns PeerRecord + */ + public static fromObject(d: { [k: string]: any }): PeerRecord; + + /** + * Creates a plain object from a PeerRecord message. Also converts values to other types if specified. + * @param m PeerRecord + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: PeerRecord, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PeerRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +export namespace PeerRecord { + + /** Properties of an AddressInfo. */ + interface IAddressInfo { + + /** AddressInfo multiaddr */ + multiaddr?: (Uint8Array|null); + } + + /** Represents an AddressInfo. */ + class AddressInfo implements IAddressInfo { + + /** + * Constructs a new AddressInfo. + * @param [p] Properties to set + */ + constructor(p?: PeerRecord.IAddressInfo); + + /** AddressInfo multiaddr. */ + public multiaddr: Uint8Array; + + /** + * Encodes the specified AddressInfo message. Does not implicitly {@link PeerRecord.AddressInfo.verify|verify} messages. + * @param m AddressInfo message or plain object to encode + * @param [w] Writer to encode to + * @returns Writer + */ + public static encode(m: PeerRecord.IAddressInfo, w?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AddressInfo message from the specified reader or buffer. + * @param r Reader or buffer to decode from + * @param [l] Message length if known beforehand + * @returns AddressInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): PeerRecord.AddressInfo; + + /** + * Creates an AddressInfo message from a plain object. Also converts values to their respective internal types. + * @param d Plain object + * @returns AddressInfo + */ + public static fromObject(d: { [k: string]: any }): PeerRecord.AddressInfo; + + /** + * Creates a plain object from an AddressInfo message. Also converts values to other types if specified. + * @param m AddressInfo + * @param [o] Conversion options + * @returns Plain object + */ + public static toObject(m: PeerRecord.AddressInfo, o?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AddressInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + } +} diff --git a/dist/src/record/utils.d.ts b/dist/src/record/utils.d.ts new file mode 100644 index 0000000000..46680a008f --- /dev/null +++ b/dist/src/record/utils.d.ts @@ -0,0 +1,12 @@ +export type Libp2p = import('../'); +/** + * @typedef {import('../')} Libp2p + */ +/** + * Create (or update if existing) self peer record and store it in the AddressBook. + * + * @param {Libp2p} libp2p + * @returns {Promise} + */ +export function updateSelfPeerRecord(libp2p: Libp2p): Promise; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/dist/src/record/utils.d.ts.map b/dist/src/record/utils.d.ts.map new file mode 100644 index 0000000000..89eb669fcf --- /dev/null +++ b/dist/src/record/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/record/utils.js"],"names":[],"mappings":"qBAMa,OAAO,KAAK,CAAC;AAD1B;;GAEG;AAEH;;;;;GAKG;AACH,6CAHW,MAAM,GACJ,QAAQ,IAAI,CAAC,CASzB"} \ No newline at end of file diff --git a/dist/src/registrar.d.ts b/dist/src/registrar.d.ts new file mode 100644 index 0000000000..e4e2695ac5 --- /dev/null +++ b/dist/src/registrar.d.ts @@ -0,0 +1,82 @@ +export = Registrar; +/** + * @typedef {import('peer-id')} PeerId + * @typedef {import('./peer-store/types').PeerStore} PeerStore + * @typedef {import('./connection-manager')} ConnectionManager + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('./').HandlerProps} HandlerProps + */ +/** + * + */ +/** + * Responsible for notifying registered protocols of events in the network. + */ +declare class Registrar { + /** + * @param {Object} props + * @param {PeerStore} props.peerStore + * @param {ConnectionManager} props.connectionManager + * @class + */ + constructor({ peerStore, connectionManager }: { + peerStore: PeerStore; + connectionManager: ConnectionManager; + }); + peerStore: import("./peer-store/types").PeerStore; + connectionManager: import("./connection-manager"); + /** + * Map of topologies + * + * @type {Map} + */ + topologies: Map; + /** @type {(protocols: string[]|string, handler: (props: HandlerProps) => void) => void} */ + _handle: (protocols: string[] | string, handler: (props: HandlerProps) => void) => void; + /** + * Remove a disconnected peer from the record + * + * @param {Connection} connection + * @returns {void} + */ + _onDisconnect(connection: Connection): void; + /** + * @param {(protocols: string[]|string, handler: (props: HandlerProps) => void) => void} handle + */ + set handle(arg: (protocols: string[] | string, handler: (props: HandlerProps) => void) => void); + /** + * @returns {(protocols: string[]|string, handler: (props: HandlerProps) => void) => void} + */ + get handle(): (protocols: string[] | string, handler: (props: HandlerProps) => void) => void; + /** + * Get a connection with a peer. + * + * @param {PeerId} peerId + * @returns {Connection | null} + */ + getConnection(peerId: PeerId): Connection | null; + /** + * Register handlers for a set of multicodecs given + * + * @param {Topology} topology - protocol topology + * @returns {Promise} registrar identifier + */ + register(topology: Topology): Promise; + /** + * Unregister topology. + * + * @param {string} id - registrar identifier + * @returns {boolean} unregistered successfully + */ + unregister(id: string): boolean; +} +declare namespace Registrar { + export { PeerId, PeerStore, ConnectionManager, Connection, HandlerProps }; +} +import Topology = require("libp2p-interfaces/src/topology"); +type Connection = import("libp2p-interfaces/src/connection/connection"); +type PeerId = import('peer-id'); +type PeerStore = import('./peer-store/types').PeerStore; +type ConnectionManager = import('./connection-manager'); +type HandlerProps = import('./').HandlerProps; +//# sourceMappingURL=registrar.d.ts.map \ No newline at end of file diff --git a/dist/src/registrar.d.ts.map b/dist/src/registrar.d.ts.map new file mode 100644 index 0000000000..48638cab66 --- /dev/null +++ b/dist/src/registrar.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registrar.d.ts","sourceRoot":"","sources":["../../src/registrar.js"],"names":[],"mappings":";AAaA;;;;;;GAMG;AAEH;;GAEG;AAEH;;GAEG;AACH;IACE;;;;;OAKG;IACH;QAJ4B,SAAS,EAA1B,SAAS;QACgB,iBAAiB,EAA1C,iBAAiB;OAsB3B;IAjBC,kDAA0B;IAE1B,kDAA0C;IAE1C;;;;OAIG;IACH,YAFU,IAAI,MAAM,EAAE,QAAQ,CAAC,CAEJ;IAE3B,2FAA2F;IAE3F,qBAFuB,MAAM,EAAE,GAAC,MAAM,mBAAmB,YAAY,KAAK,IAAI,KAAK,IAAI,CAE/D;IA+D1B;;;;;OAKG;IACH,0BAHW,UAAU,GACR,IAAI,CAMhB;IA5DD;;OAEG;IACH,4BATyB,MAAM,EAAE,GAAC,MAAM,mBAAmB,YAAY,KAAK,IAAI,KAAK,IAAI,EAWxF;IAZD;;OAEG;IACH,0BAFyB,MAAM,EAAE,GAAC,MAAM,mBAAmB,YAAY,KAAK,IAAI,KAAK,IAAI,CAIxF;IASD;;;;;OAKG;IACH,sBAHW,MAAM,GACJ,UAAU,GAAG,IAAI,CAI7B;IAED;;;;;OAKG;IACH,mBAHW,QAAQ,GACN,QAAQ,MAAM,CAAC,CAiB3B;IAED;;;;;OAKG;IACH,eAHW,MAAM,GACJ,OAAO,CAInB;CAaF;;;;;;cA9GY,OAAO,SAAS,CAAC;iBACjB,OAAO,oBAAoB,EAAE,SAAS;yBACtC,OAAO,sBAAsB,CAAC;oBAE9B,OAAO,IAAI,EAAE,YAAY"} \ No newline at end of file diff --git a/dist/src/transport-manager.d.ts b/dist/src/transport-manager.d.ts new file mode 100644 index 0000000000..2648ad0992 --- /dev/null +++ b/dist/src/transport-manager.d.ts @@ -0,0 +1,120 @@ +export = TransportManager; +/** + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('libp2p-interfaces/src/transport/types').TransportFactory} TransportFactory + * @typedef {import('libp2p-interfaces/src/transport/types').Transport} Transport + * + * @typedef {Object} TransportManagerProperties + * @property {import('./')} libp2p + * @property {import('./upgrader')} upgrader + * + * @typedef {Object} TransportManagerOptions + * @property {number} [faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance. + */ +declare class TransportManager { + /** + * @class + * @param {TransportManagerProperties & TransportManagerOptions} options + */ + constructor({ libp2p, upgrader, faultTolerance }: TransportManagerProperties & TransportManagerOptions); + libp2p: import("./"); + upgrader: import("./upgrader"); + /** @type {Map} */ + _transports: Map>; + _listeners: Map; + _listenerOptions: Map; + faultTolerance: number; + /** + * Adds a `Transport` to the manager + * + * @param {string} key + * @param {TransportFactory} Transport + * @param {*} transportOptions - Additional options to pass to the transport + * @returns {void} + */ + add(key: string, Transport: import("libp2p-interfaces/src/transport/types").TransportFactory, transportOptions?: any): void; + /** + * Stops all listeners + * + * @async + */ + close(): Promise; + /** + * Dials the given Multiaddr over it's supported transport + * + * @param {Multiaddr} ma + * @param {*} options + * @returns {Promise} + */ + dial(ma: Multiaddr, options: any): Promise; + /** + * Returns all Multiaddr's the listeners are using + * + * @returns {Multiaddr[]} + */ + getAddrs(): Multiaddr[]; + /** + * Returns all the transports instances. + * + * @returns {IterableIterator} + */ + getTransports(): IterableIterator>; + /** + * Finds a transport that matches the given Multiaddr + * + * @param {Multiaddr} ma + * @returns {Transport|null} + */ + transportForMultiaddr(ma: Multiaddr): import("libp2p-interfaces/src/transport/types").Transport | null; + /** + * Starts listeners for each listen Multiaddr. + * + * @async + * @param {Multiaddr[]} addrs - addresses to attempt to listen on + */ + listen(addrs: Multiaddr[]): Promise; + /** + * Removes the given transport from the manager. + * If a transport has any running listeners, they will be closed. + * + * @async + * @param {string} key + */ + remove(key: string): Promise; + /** + * Removes all transports from the manager. + * If any listeners are running, they will be closed. + * + * @async + */ + removeAll(): Promise; +} +declare namespace TransportManager { + export { FAULT_TOLERANCE as FaultTolerance, Multiaddr, Connection, TransportFactory, Transport, TransportManagerProperties, TransportManagerOptions }; +} +type Multiaddr = import('multiaddr').Multiaddr; +type Connection = import("libp2p-interfaces/src/connection/connection"); +type TransportManagerProperties = { + libp2p: import('./'); + upgrader: import('./upgrader'); +}; +type TransportManagerOptions = { + /** + * - Address listen error tolerance. + */ + faultTolerance?: number | undefined; +}; +/** + * Enum Transport Manager Fault Tolerance values. + * FATAL_ALL should be used for failing in any listen circumstance. + * NO_FATAL should be used for not failing when not listening. + */ +type FAULT_TOLERANCE = number; +declare namespace FAULT_TOLERANCE { + const FATAL_ALL: number; + const NO_FATAL: number; +} +type TransportFactory = import('libp2p-interfaces/src/transport/types').TransportFactory; +type Transport = import('libp2p-interfaces/src/transport/types').Transport; +//# sourceMappingURL=transport-manager.d.ts.map \ No newline at end of file diff --git a/dist/src/transport-manager.d.ts.map b/dist/src/transport-manager.d.ts.map new file mode 100644 index 0000000000..90a6731759 --- /dev/null +++ b/dist/src/transport-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport-manager.d.ts","sourceRoot":"","sources":["../../src/transport-manager.js"],"names":[],"mappings":";AAaA;;;;;;;;;;;;GAYG;AAEH;IACE;;;OAGG;IACH,kDAFW,0BAA0B,GAAG,uBAAuB,EAU9D;IAPC,qBAAoB;IACpB,+BAAwB;IACxB,qCAAqC;IACrC,aADW,IAAI,MAAM,sEAAY,CACL;IAC5B,0BAA2B;IAC3B,gCAAiC;IACjC,uBAAoC;IAGtC;;;;;;;OAOG;IACH,SALW,MAAM,kHAGJ,IAAI,CAsBhB;IAED;;;;OAIG;IACH,uBAiBC;IAED;;;;;;OAMG;IACH,SAJW,SAAS,iBAEP,QAAQ,UAAU,CAAC,CAc/B;IAED;;;;OAIG;IACH,YAFa,SAAS,EAAE,CAWvB;IAED;;;;OAIG;IACH,iBAFa,qFAA2B,CAIvC;IAED;;;;;OAKG;IACH,0BAHW,SAAS,GACP,sEAAU,IAAI,CAQ1B;IAED;;;;;OAKG;IACH,cAFW,SAAS,EAAE,iBAqDrB;IAED;;;;;;OAMG;IACH,YAFW,MAAM,iBAehB;IAED;;;;;OAKG;IACH,2BAOC;CACF;;;;iBA7OY,OAAO,WAAW,EAAE,SAAS;;;YAM5B,OAAO,IAAI,CAAC;cACZ,OAAO,YAAY,CAAC;;;;;;;;;;;;;uBA8OxB,MAAM;;;;;wBAnPH,OAAO,uCAAuC,EAAE,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC;iBAC1E,OAAO,uCAAuC,EAAE,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC"} \ No newline at end of file diff --git a/dist/src/types.d.ts b/dist/src/types.d.ts new file mode 100644 index 0000000000..05ee714221 --- /dev/null +++ b/dist/src/types.d.ts @@ -0,0 +1,90 @@ +import type PeerId from 'peer-id'; +import type { Multiaddr } from 'multiaddr'; +import type { MultiaddrConnection } from 'libp2p-interfaces/src/transport/types'; +export interface ConnectionGater { + /** + * denyDialMultiaddr tests whether we're permitted to Dial the + * specified peer. + * + * This is called by the dialer.connectToPeer implementation before + * dialling a peer. + * + * Return true to prevent dialing the passed peer. + */ + denyDialPeer: (peerId: PeerId) => Promise; + /** + * denyDialMultiaddr tests whether we're permitted to dial the specified + * multiaddr for the given peer. + * + * This is called by the dialer.connectToPeer implementation after it has + * resolved the peer's addrs, and prior to dialling each. + * + * Return true to prevent dialing the passed peer on the passed multiaddr. + */ + denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise; + /** + * denyInboundConnection tests whether an incipient inbound connection is allowed. + * + * This is called by the upgrader, or by the transport directly (e.g. QUIC, + * Bluetooth), straight after it has accepted a connection from its socket. + * + * Return true to deny the incoming passed connection. + */ + denyInboundConnection: (maConn: MultiaddrConnection) => Promise; + /** + * denyOutboundConnection tests whether an incipient outbound connection is allowed. + * + * This is called by the upgrader, or by the transport directly (e.g. QUIC, + * Bluetooth), straight after it has created a connection with its socket. + * + * Return true to deny the incoming passed connection. + */ + denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise; + /** + * denyInboundEncryptedConnection tests whether a given connection, now encrypted, + * is allowed. + * + * This is called by the upgrader, after it has performed the security + * handshake, and before it negotiates the muxer, or by the directly by the + * transport, at the exact same checkpoint. + * + * Return true to deny the passed secured connection. + */ + denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise; + /** + * denyOutboundEncryptedConnection tests whether a given connection, now encrypted, + * is allowed. + * + * This is called by the upgrader, after it has performed the security + * handshake, and before it negotiates the muxer, or by the directly by the + * transport, at the exact same checkpoint. + * + * Return true to deny the passed secured connection. + */ + denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise; + /** + * denyInboundUpgradedConnection tests whether a fully capable connection is allowed. + * + * This is called after encryption has been negotiated and the connection has been + * multiplexed, if a multiplexer is configured. + * + * Return true to deny the passed upgraded connection. + */ + denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise; + /** + * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed. + * + * This is called after encryption has been negotiated and the connection has been + * multiplexed, if a multiplexer is configured. + * + * Return true to deny the passed upgraded connection. + */ + denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise; + /** + * Used by the address book to filter passed addresses. + * + * Return true to allow storing the passed multiaddr for the passed peer. + */ + filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/src/types.d.ts.map b/dist/src/types.d.ts.map new file mode 100644 index 0000000000..2eca66f602 --- /dev/null +++ b/dist/src/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,SAAS,CAAA;AACjC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAC1C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAA;AAEhF,MAAM,WAAW,eAAe;IAC9B;;;;;;;;OAQG;IACH,YAAY,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAElD;;;;;;;;OAQG;IACH,iBAAiB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAE7E;;;;;;;OAOG;IACH,qBAAqB,EAAE,CAAC,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAExE;;;;;;;OAOG;IACH,sBAAsB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAEzF;;;;;;;;;OASG;IACH,8BAA8B,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAEjG;;;;;;;;;OASG;IACH,+BAA+B,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAElG;;;;;;;OAOG;IACH,6BAA6B,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAEhG;;;;;;;OAOG;IACH,8BAA8B,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAEjG;;;;OAIG;IACH,sBAAsB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;CACjF"} \ No newline at end of file diff --git a/dist/src/upgrader.d.ts b/dist/src/upgrader.d.ts new file mode 100644 index 0000000000..08e64ff988 --- /dev/null +++ b/dist/src/upgrader.d.ts @@ -0,0 +1,157 @@ +export = Upgrader; +/** + * @typedef {import('libp2p-interfaces/src/transport/types').MultiaddrConnection} MultiaddrConnection + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxerFactory} MuxerFactory + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').Muxer} Muxer + * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream + * @typedef {import('libp2p-interfaces/src/crypto/types').Crypto} Crypto + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('multiaddr').Multiaddr} Multiaddr + * @typedef {import('./types').ConnectionGater} ConnectionGater + */ +/** + * @typedef CryptoResult + * @property {MultiaddrConnection} conn A duplex iterable + * @property {PeerId} remotePeer + * @property {string} protocol + */ +declare class Upgrader { + /** + * @param {object} options + * @param {PeerId} options.localPeer + * @param {ConnectionGater} options.connectionGater + * + * @param {import('./metrics')} [options.metrics] + * @param {Map} [options.cryptos] + * @param {Map} [options.muxers] + * @param {(connection: Connection) => void} options.onConnection - Called when a connection is upgraded + * @param {(connection: Connection) => void} options.onConnectionEnd + */ + constructor({ localPeer, metrics, connectionGater, cryptos, muxers, onConnectionEnd, onConnection }: { + localPeer: PeerId; + connectionGater: ConnectionGater; + metrics?: import("./metrics") | undefined; + cryptos?: Map | undefined; + muxers?: Map | undefined; + onConnection: (connection: Connection) => void; + onConnectionEnd: (connection: Connection) => void; + }); + connectionGater: import("./types").ConnectionGater; + localPeer: PeerId; + metrics: import("./metrics") | undefined; + cryptos: Map; + muxers: Map; + /** @type {import("./pnet") | null} */ + protector: import("./pnet") | null; + protocols: Map; + onConnection: (connection: Connection) => void; + onConnectionEnd: (connection: Connection) => void; + /** + * Upgrades an inbound connection + * + * @async + * @param {MultiaddrConnection} maConn + * @returns {Promise} + */ + upgradeInbound(maConn: MultiaddrConnection): Promise; + /** + * Upgrades an outbound connection + * + * @async + * @param {MultiaddrConnection} maConn + * @returns {Promise} + */ + upgradeOutbound(maConn: MultiaddrConnection): Promise; + /** + * A convenience method for generating a new `Connection` + * + * @private + * @param {object} options + * @param {string} options.cryptoProtocol - The crypto protocol that was negotiated + * @param {'inbound' | 'outbound'} options.direction - One of ['inbound', 'outbound'] + * @param {MultiaddrConnection} options.maConn - The transport layer connection + * @param {MuxedStream | MultiaddrConnection} options.upgradedConn - A duplex connection returned from multiplexer and/or crypto selection + * @param {MuxerFactory} [options.Muxer] - The muxer to be used for muxing + * @param {PeerId} options.remotePeer - The peer the connection is with + * @returns {Connection} + */ + private _createConnection; + /** + * Routes incoming streams to the correct handler + * + * @private + * @param {object} options + * @param {Connection} options.connection - The connection the stream belongs to + * @param {MuxedStream} options.stream + * @param {string} options.protocol + */ + private _onStream; + /** + * Attempts to encrypt the incoming `connection` with the provided `cryptos`. + * + * @private + * @async + * @param {PeerId} localPeer - The initiators PeerId + * @param {*} connection + * @param {Map} cryptos + * @returns {Promise} An encrypted connection, remote peer `PeerId` and the protocol of the `Crypto` used + */ + private _encryptInbound; + /** + * Attempts to encrypt the given `connection` with the provided `cryptos`. + * The first `Crypto` module to succeed will be used + * + * @private + * @async + * @param {PeerId} localPeer - The initiators PeerId + * @param {MultiaddrConnection} connection + * @param {PeerId} remotePeerId + * @param {Map} cryptos + * @returns {Promise} An encrypted connection, remote peer `PeerId` and the protocol of the `Crypto` used + */ + private _encryptOutbound; + /** + * Selects one of the given muxers via multistream-select. That + * muxer will be used for all future streams on the connection. + * + * @private + * @async + * @param {MultiaddrConnection} connection - A basic duplex connection to multiplex + * @param {Map} muxers - The muxers to attempt multiplexing with + * @returns {Promise<{ stream: MuxedStream, Muxer?: MuxerFactory}>} A muxed connection + */ + private _multiplexOutbound; + /** + * Registers support for one of the given muxers via multistream-select. The + * selected muxer will be used for all future streams on the connection. + * + * @private + * @async + * @param {MultiaddrConnection} connection - A basic duplex connection to multiplex + * @param {Map} muxers - The muxers to attempt multiplexing with + * @returns {Promise<{ stream: MuxedStream, Muxer?: MuxerFactory}>} A muxed connection + */ + private _multiplexInbound; +} +declare namespace Upgrader { + export { MultiaddrConnection, MuxerFactory, Muxer, MuxedStream, Crypto, Connection, Multiaddr, ConnectionGater, CryptoResult }; +} +import PeerId = require("peer-id"); +type MultiaddrConnection = import('libp2p-interfaces/src/transport/types').MultiaddrConnection; +import { Connection } from "libp2p-interfaces/src/connection"; +type ConnectionGater = import('./types').ConnectionGater; +type MuxerFactory = import('libp2p-interfaces/src/stream-muxer/types').MuxerFactory; +type Muxer = import('libp2p-interfaces/src/stream-muxer/types').Muxer; +type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream; +type Crypto = import('libp2p-interfaces/src/crypto/types').Crypto; +type Connection = import("libp2p-interfaces/src/connection/connection"); +type Multiaddr = import('multiaddr').Multiaddr; +type CryptoResult = { + /** + * A duplex iterable + */ + conn: MultiaddrConnection; + remotePeer: PeerId; + protocol: string; +}; +//# sourceMappingURL=upgrader.d.ts.map \ No newline at end of file diff --git a/dist/src/upgrader.d.ts.map b/dist/src/upgrader.d.ts.map new file mode 100644 index 0000000000..544b4c5fc4 --- /dev/null +++ b/dist/src/upgrader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"upgrader.d.ts","sourceRoot":"","sources":["../../src/upgrader.js"],"names":[],"mappings":";AAgBA;;;;;;;;;GASG;AAEH;;;;;GAKG;AAEH;IACE;;;;;;;;;;OAUG;IACH;mBATW,MAAM;yBACN,eAAe;;;;mCAKF,UAAU,KAAK,IAAI;sCACnB,UAAU,KAAK,IAAI;OAqB1C;IAVC,mDAAsC;IACtC,kBAA0B;IAC1B,yCAAsB;IACtB,0EAAsB;IACtB,qFAAoB;IACpB,sCAAsC;IACtC,WADW,OAAO,QAAQ,CAAC,GAAG,IAAI,CACb;IACrB,yBAA0B;IAC1B,2BApBsB,UAAU,KAAK,IAAI,CAoBT;IAChC,8BApBsB,UAAU,KAAK,IAAI,CAoBH;IAGxC;;;;;;OAMG;IACH,uBAHW,mBAAmB,GACjB,QAAQ,UAAU,CAAC,CAyE/B;IAED;;;;;;OAMG;IACH,wBAHW,mBAAmB,GACjB,QAAQ,UAAU,CAAC,CAgF/B;IAED;;;;;;;;;;;;OAYG;IACH,0BAgHC;IAED;;;;;;;;OAQG;IACH,kBAGC;IAED;;;;;;;;;OASG;IACH,wBAqBC;IAED;;;;;;;;;;;OAWG;IACH,yBAqBC;IAED;;;;;;;;;OASG;IACH,2BAYC;IAED;;;;;;;;;OASG;IACH,0BAWC;CACF;;;;;2BAxdY,OAAO,uCAAuC,EAAE,mBAAmB;;uBAOnE,OAAO,SAAS,EAAE,eAAe;oBANjC,OAAO,0CAA0C,EAAE,YAAY;aAC/D,OAAO,0CAA0C,EAAE,KAAK;mBACxD,OAAO,0CAA0C,EAAE,WAAW;cAC9D,OAAO,oCAAoC,EAAE,MAAM;;iBAEnD,OAAO,WAAW,EAAE,SAAS;;;;;UAM5B,mBAAmB;gBACnB,MAAM;cACN,MAAM"} \ No newline at end of file diff --git a/src/dialer/dial-request.js b/src/dialer/dial-request.js index 0d97751aae..babef13611 100644 --- a/src/dialer/dial-request.js +++ b/src/dialer/dial-request.js @@ -80,6 +80,7 @@ class DialRequest { const signal = dialAbortControllers[i].signal conn = await this.dialAction(addr, { ...options, signal: options.signal ? anySignal([signal, options.signal]) : signal }) // Remove the successful AbortController so it is not aborted + // @ts-ignore dialAbortControllers[i] = undefined } finally { completedDials++