@libp2p/fetch 0.0.0-05b52d69c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +4 -0
- package/README.md +68 -0
- package/dist/index.min.js +3 -0
- package/dist/src/constants.d.ts +3 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +4 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/fetch.d.ts +63 -0
- package/dist/src/fetch.d.ts.map +1 -0
- package/dist/src/fetch.js +208 -0
- package/dist/src/fetch.js.map +1 -0
- package/dist/src/index.d.ts +87 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +39 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/pb/proto.d.ts +28 -0
- package/dist/src/pb/proto.d.ts.map +1 -0
- package/dist/src/pb/proto.js +120 -0
- package/dist/src/pb/proto.js.map +1 -0
- package/package.json +66 -0
- package/src/constants.ts +3 -0
- package/src/fetch.ts +236 -0
- package/src/index.ts +98 -0
- package/src/pb/proto.proto +15 -0
- package/src/pb/proto.ts +153 -0
package/LICENSE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
[](http://libp2p.io/)
|
|
2
|
+
[](https://discuss.libp2p.io)
|
|
3
|
+
[](https://codecov.io/gh/libp2p/js-libp2p)
|
|
4
|
+
[](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amaster)
|
|
5
|
+
|
|
6
|
+
> Implementation of the Fetch Protocol
|
|
7
|
+
|
|
8
|
+
# About
|
|
9
|
+
|
|
10
|
+
An implementation of the Fetch protocol as described here: <https://github.com/libp2p/specs/tree/master/fetch>
|
|
11
|
+
|
|
12
|
+
The fetch protocol is a simple protocol for requesting a value corresponding to a key from a peer.
|
|
13
|
+
|
|
14
|
+
## Example
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
import { createLibp2p } from 'libp2p'
|
|
18
|
+
import { fetch } from '@libp2p/fetch'
|
|
19
|
+
|
|
20
|
+
const libp2p = await createLibp2p({
|
|
21
|
+
services: {
|
|
22
|
+
fetch: fetch()
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
// Given a key (as a string) returns a value (as a Uint8Array), or null if the key isn't found.
|
|
27
|
+
// All keys must be prefixed my the same prefix, which will be used to find the appropriate key
|
|
28
|
+
// lookup function.
|
|
29
|
+
async function my_subsystem_key_lookup(key) {
|
|
30
|
+
// app specific callback to lookup key-value pairs.
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
|
|
34
|
+
libp2p.fetch.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
|
|
35
|
+
|
|
36
|
+
const key = '/my_subsystem_key_prefix/{...}'
|
|
37
|
+
const peerDst = PeerId.parse('Qmfoo...') // or Multiaddr instance
|
|
38
|
+
const value = await libp2p.fetch(peerDst, key)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
# Install
|
|
42
|
+
|
|
43
|
+
```console
|
|
44
|
+
$ npm i @libp2p/fetch
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Browser `<script>` tag
|
|
48
|
+
|
|
49
|
+
Loading this module through a script tag will make it's exports available as `Libp2pFetch` in the global namespace.
|
|
50
|
+
|
|
51
|
+
```html
|
|
52
|
+
<script src="https://unpkg.com/@libp2p/fetch/dist/index.min.js"></script>
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
# API Docs
|
|
56
|
+
|
|
57
|
+
- <https://libp2p.github.io/js-libp2p/modules/_libp2p_fetch.html>
|
|
58
|
+
|
|
59
|
+
# License
|
|
60
|
+
|
|
61
|
+
Licensed under either of
|
|
62
|
+
|
|
63
|
+
- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
|
|
64
|
+
- MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
|
|
65
|
+
|
|
66
|
+
# Contribution
|
|
67
|
+
|
|
68
|
+
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PFetch = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
+
"use strict";var Libp2PFetch=(()=>{var br=Object.create;var ft=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var yr=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty;var Lr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),U=(r,t)=>{for(var e in t)ft(r,e,{get:t[e],enumerable:!0})},Le=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of yr(t))!Er.call(r,i)&&i!==e&&ft(r,i,{get:()=>t[i],enumerable:!(n=wr(t,i))||n.enumerable});return r};var Ar=(r,t,e)=>(e=r!=null?br(xr(r)):{},Le(t||!r||!r.__esModule?ft(e,"default",{value:r,enumerable:!0}):e,r)),Sr=r=>Le(ft({},"__esModule",{value:!0}),r);var ve=Lr((_i,_e)=>{"use strict";function Be(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function Br(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return Be(r,e)}catch{e.message=r.message,e.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),Be(new i,e)}}_e.exports=Br});var ei={};U(ei,{fetch:()=>ti});var V=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var Ae="ERR_TIMEOUT",Se="ERR_INVALID_PARAMETERS";var Ne="ERR_INVALID_MESSAGE";var Tt=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},ai=globalThis.CustomEvent??Tt;var Ue=(r,...t)=>{try{[...t]}catch{}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var dt=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},q=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new dt(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new dt(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Ot=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function De(r={}){return Nr(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Nr(r,t){t=t??{};let e=t.onEnd,n=new q,i,s,o,a=lt(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((u,b)=>{s=L=>{s=null,n.push(L);try{u(r(n))}catch(w){b(w)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},h=u=>s!=null?s(u):(n.push(u),i),f=u=>(n=new q,s!=null?s({error:u}):(n.push({error:u}),i)),l=u=>{if(o)return i;if(t?.objectMode!==!0&&u?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:u})},A=u=>o?i:(o=!0,u!=null?f(u):h({done:!0})),j=()=>(n=new q,A(),{done:!0}),p=u=>(A(u),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:j,throw:p,push:l,end:A,get readableLength(){return n.size},onEmpty:async u=>{let b=u?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let L,w;b!=null&&(L=new Promise((N,D)=>{w=()=>{D(new Ot)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,L])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},e==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(u){return m.throw(u),e!=null&&(e(u),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(u){return m.end(u),e!=null&&(e(u),e=void 0),i},get readableLength(){return m.readableLength}},i}function z(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function _(r=0){return globalThis.Buffer?.alloc!=null?z(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function y(r=0){return globalThis.Buffer?.allocUnsafe!=null?z(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Ft(r,t){t==null&&(t=r.reduce((i,s)=>i+s.length,0));let e=y(t),n=0;for(let i of r)e.set(i,n),n+=i.length;return z(e)}function Ie(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Te=Symbol.for("@achingbrain/uint8arraylist");function Re(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let i=e+n.byteLength;if(t<i)return{buf:n,index:t-e};e=i}throw new RangeError("index is out of bounds")}function pt(r){return!!r?.[Te]}var I=class r{constructor(...t){Object.defineProperty(this,Te,{value:!0}),this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(pt(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(pt(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Re(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Re(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(pt(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:i}=this._subList(t,e);return Ft(n,i)}subarray(t,e){let{bufs:n,length:i}=this._subList(t,e);return n.length===1?n[0]:Ft(n,i)}sublist(t,e){let{bufs:n,length:i}=this._subList(t,e),s=new r;return s.length=i,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,t>=c)continue;let h=t>=a&&t<c,f=e>a&&e<=c;if(h&&f){if(t===a&&e===c){n.push(o);break}let l=t-a;n.push(o.subarray(l,l+(e-t)));break}if(h){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(f){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!pt(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let l=0;l<s;l++)o[l]=-1;for(let l=0;l<i;l++)o[n[l]]=l;let a=o,c=this.byteLength-n.byteLength,h=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let A=h;A>=0;A--){let j=this.get(l+A);if(n[A]!==j){f=Math.max(1,A-a[j]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,e,n),this.write(i,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,e,n),this.write(i,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,e,n),this.write(i,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,e,n),this.write(i,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,e,n),this.write(i,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,e,n),this.write(i,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,e,n),this.write(i,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,e,n),this.write(i,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Ie(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((i,s)=>i+s.byteLength,0)),n.length=e,n}};var gt=class extends Error{code;constructor(t,e){super(t),this.code=e}},Bt=class extends gt{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Oe(r){let t=De();r.sink(t).catch(s=>{t.end(s)}),r.sink=async s=>{for await(let o of s)t.push(o);t.end()};let e=r.source;r.source[Symbol.iterator]!=null?e=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(e=r.source[Symbol.asyncIterator]());let n=new I;return{read:async(s,o)=>{o?.signal?.throwIfAborted();let a,c=new Promise((h,f)=>{a=()=>{f(new Bt("Read aborted"))},o?.signal?.addEventListener("abort",a)});try{if(s==null){let{done:f,value:l}=await Promise.race([e.next(),c]);return f===!0?new I:l}for(;n.byteLength<s;){let{value:f,done:l}=await Promise.race([e.next(),c]);if(l===!0)throw new gt("unexpected end of input","ERR_UNEXPECTED_EOF");n.append(f)}let h=n.sublist(0,s);return n.consume(s),h}finally{a!=null&&o?.signal?.removeEventListener("abort",a)}},write:async(s,o)=>{o?.signal?.throwIfAborted(),s instanceof Uint8Array?t.push(s):t.push(s.subarray()),await t.onEmpty(o)},unwrap:()=>{let s=r.source;return r.source=async function*(){yield*n,yield*s}(),r}}}var Ur=Math.pow(2,7),Dr=Math.pow(2,14),Ir=Math.pow(2,21),_t=Math.pow(2,28),vt=Math.pow(2,35),Ct=Math.pow(2,42),Mt=Math.pow(2,49),d=128,x=127;function P(r){if(r<Ur)return 1;if(r<Dr)return 2;if(r<Ir)return 3;if(r<_t)return 4;if(r<vt)return 5;if(r<Ct)return 6;if(r<Mt)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Rr(r,t,e=0){switch(P(r)){case 8:t[e++]=r&255|d,r/=128;case 7:t[e++]=r&255|d,r/=128;case 6:t[e++]=r&255|d,r/=128;case 5:t[e++]=r&255|d,r/=128;case 4:t[e++]=r&255|d,r>>>=7;case 3:t[e++]=r&255|d,r>>>=7;case 2:t[e++]=r&255|d,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Tr(r,t,e=0){switch(P(r)){case 8:t.set(e++,r&255|d),r/=128;case 7:t.set(e++,r&255|d),r/=128;case 6:t.set(e++,r&255|d),r/=128;case 5:t.set(e++,r&255|d),r/=128;case 4:t.set(e++,r&255|d),r>>>=7;case 3:t.set(e++,r&255|d),r>>>=7;case 2:t.set(e++,r&255|d),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Or(r,t){let e=r[t],n=0;if(n+=e&x,e<d||(e=r[t+1],n+=(e&x)<<7,e<d)||(e=r[t+2],n+=(e&x)<<14,e<d)||(e=r[t+3],n+=(e&x)<<21,e<d)||(e=r[t+4],n+=(e&x)*_t,e<d)||(e=r[t+5],n+=(e&x)*vt,e<d)||(e=r[t+6],n+=(e&x)*Ct,e<d)||(e=r[t+7],n+=(e&x)*Mt,e<d))return n;throw new RangeError("Could not decode varint")}function Fr(r,t){let e=r.get(t),n=0;if(n+=e&x,e<d||(e=r.get(t+1),n+=(e&x)<<7,e<d)||(e=r.get(t+2),n+=(e&x)<<14,e<d)||(e=r.get(t+3),n+=(e&x)<<21,e<d)||(e=r.get(t+4),n+=(e&x)*_t,e<d)||(e=r.get(t+5),n+=(e&x)*vt,e<d)||(e=r.get(t+6),n+=(e&x)*Ct,e<d)||(e=r.get(t+7),n+=(e&x)*Mt,e<d))return n;throw new RangeError("Could not decode varint")}function Fe(r,t,e=0){return t==null&&(t=y(P(r))),t instanceof Uint8Array?Rr(r,t,e):Tr(r,t,e)}function mt(r,t=0){return r instanceof Uint8Array?Or(r,t):Fr(r,t)}function bt(r){return r[Symbol.asyncIterator]!=null}var wt=r=>{let t=P(r),e=y(t);return Fe(r,e),wt.bytes=t,e};wt.bytes=0;function et(r,t){t=t??{};let e=t.lengthEncoder??wt;function*n(i){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return bt(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}et.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??wt;return new I(e(r.byteLength),r)};var W=Ar(ve(),1);var _r=8,vr=1024*1024*4,G;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(G||(G={}));var zt=r=>{let t=mt(r);return zt.bytes=P(t),t};zt.bytes=0;function Vt(r,t){let e=new I,n=G.LENGTH,i=-1,s=t?.lengthDecoder??zt,o=t?.maxLengthLength??_r,a=t?.maxDataLength??vr;function*c(){for(;e.byteLength>0;){if(n===G.LENGTH)try{if(i=s(e),i<0)throw(0,W.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,W.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let h=s.bytes;e.consume(h),t?.onLength!=null&&t.onLength(i),n=G.DATA}catch(h){if(h instanceof RangeError){if(e.byteLength>o)throw(0,W.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw h}if(n===G.DATA){if(e.byteLength<i)break;let h=e.sublist(0,i);e.consume(i),t?.onData!=null&&t.onData(h),yield h,n=G.LENGTH}}}return bt(r)?async function*(){for await(let h of r)e.append(h),yield*c();if(e.byteLength>0)throw(0,W.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let h of r)e.append(h),yield*c();if(e.byteLength>0)throw(0,W.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Vt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(e);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Vt(n,{...t??{},onLength:s=>{e=s}})};var yt=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ce=r=>mt(r);Ce.bytes=0;function Me(r,t){let e=Oe(r);return{read:async i=>{let s=-1,o=new I,a=t?.lengthDecoder??Ce;for(;;){o.append(await e.read(1,i));try{s=a(o)}catch(c){if(c instanceof RangeError)continue;throw c}if(s>-1)break;if(t?.maxLengthLength!=null&&o.byteLength>t.maxLengthLength)throw new yt("message length length too long","ERR_MSG_LENGTH_TOO_LONG")}if(t?.maxDataLength!=null&&s>t.maxDataLength)throw new yt("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(s,i)},write:async(i,s)=>{await e.write(et.single(i,t),s)},writeV:async(i,s)=>{let o=new I(...i.map(a=>et.single(a,t)));await e.write(o,s)},unwrap:()=>e.unwrap()}}function Pt(r,t){let e=Me(r,t),n={read:async(i,s)=>{let o=await e.read(s);return i.decode(o)},write:async(i,s,o)=>{await e.write(s.encode(i),o)},writeV:async(i,s,o)=>{await e.writeV(i.map(a=>s.encode(a)),o)},pb:i=>({read:async s=>n.read(i,s),write:async(s,o)=>n.write(s,i,o),writeV:async(s,o)=>n.writeV(s,i,o),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var jt={};U(jt,{base10:()=>Gr});function Mr(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(e[o]!==255)throw new TypeError(s+" is ambiguous");e[o]=i}var a=r.length,c=r.charAt(0),h=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,u=0,b=0,L=p.length;b!==L&&p[b]===0;)b++,m++;for(var w=(L-b)*f+1>>>0,N=new Uint8Array(w);b!==L;){for(var D=p[b],C=0,R=w-1;(D!==0||C<u)&&R!==-1;R--,C++)D+=256*N[R]>>>0,N[R]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");u=C,b++}for(var B=w-u;B!==w&&N[B]===0;)B++;for(var ut=c.repeat(m);B<w;++B)ut+=r.charAt(N[B]);return ut}function A(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var u=0,b=0;p[m]===c;)u++,m++;for(var L=(p.length-m)*h+1>>>0,w=new Uint8Array(L);p[m];){var N=e[p.charCodeAt(m)];if(N===255)return;for(var D=0,C=L-1;(N!==0||D<b)&&C!==-1;C--,D++)N+=a*w[C]>>>0,w[C]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");b=D,m++}if(p[m]!==" "){for(var R=L-b;R!==L&&w[R]===0;)R++;for(var B=new Uint8Array(u+(L-R)),ut=u;R!==L;)B[ut++]=w[R++];return B}}}function j(p){var m=A(p);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:A,decode:j}}var kr=Mr,Vr=kr,ke=Vr;var ji=new Uint8Array(0);var Ve=(r,t)=>{if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0},v=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var ze=r=>new TextEncoder().encode(r),Pe=r=>new TextDecoder().decode(r);var Gt=class{constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},$t=class{constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $e(this,t)}},Xt=class{constructor(t){this.decoders=t}or(t){return $e(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},$e=(r,t)=>new Xt({...r.decoders||{[r.prefix]:r},...t.decoders||{[t.prefix]:t}}),Ht=class{constructor(t,e,n,i){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=i,this.encoder=new Gt(t,e,n),this.decoder=new $t(t,e,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},K=({name:r,prefix:t,encode:e,decode:n})=>new Ht(r,t,e,n),M=({prefix:r,name:t,alphabet:e})=>{let{encode:n,decode:i}=ke(e,t);return K({prefix:r,name:t,encode:n,decode:s=>v(i(s))})},zr=(r,t,e,n)=>{let i={};for(let f=0;f<t.length;++f)i[t[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),a=0,c=0,h=0;for(let f=0;f<s;++f){let l=i[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|l,a+=e,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Pr=(r,t,e)=>{let n=t[t.length-1]==="=",i=(1<<e)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,s+=t[i&a>>o];if(o&&(s+=t[i&a<<e-o]),n)for(;s.length*e&7;)s+="=";return s},g=({name:r,prefix:t,bitsPerChar:e,alphabet:n})=>K({prefix:t,name:r,encode(i){return Pr(i,n,e)},decode(i){return zr(i,n,e,r)}});var Gr=M({prefix:"9",name:"base10",alphabet:"0123456789"});var qt={};U(qt,{base16:()=>$r,base16upper:()=>Xr});var $r=g({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xr=g({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Wt={};U(Wt,{base2:()=>Hr});var Hr=g({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kt={};U(Kt,{base256emoji:()=>Jr});var Xe=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),jr=Xe.reduce((r,t,e)=>(r[e]=t,r),[]),qr=Xe.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Wr(r){return r.reduce((t,e)=>(t+=jr[e],t),"")}function Kr(r){let t=[];for(let e of r){let n=qr[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Jr=K({prefix:"\u{1F680}",name:"base256emoji",encode:Wr,decode:Kr});var Jt={};U(Jt,{base32:()=>J,base32hex:()=>tn,base32hexpad:()=>rn,base32hexpadupper:()=>nn,base32hexupper:()=>en,base32pad:()=>Zr,base32padupper:()=>Yr,base32upper:()=>Qr,base32z:()=>sn});var J=g({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qr=g({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Zr=g({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yr=g({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),tn=g({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),en=g({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rn=g({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nn=g({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sn=g({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qt={};U(Qt,{base36:()=>on,base36upper:()=>an});var on=M({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),an=M({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Zt={};U(Zt,{base58btc:()=>F,base58flickr:()=>cn});var F=M({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cn=M({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yt={};U(Yt,{base64:()=>hn,base64pad:()=>un,base64url:()=>fn,base64urlpad:()=>ln});var hn=g({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),un=g({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fn=g({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ln=g({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var te={};U(te,{base8:()=>dn});var dn=g({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ee={};U(ee,{identity:()=>pn});var pn=K({prefix:"\0",name:"identity",encode:r=>Pe(r),decode:r=>ze(r)});var as=new TextEncoder,cs=new TextDecoder;var ne={};U(ne,{identity:()=>Mn});var bn=qe,He=128,wn=127,yn=~wn,xn=Math.pow(2,31);function qe(r,t,e){t=t||[],e=e||0;for(var n=e;r>=xn;)t[e++]=r&255|He,r/=128;for(;r&yn;)t[e++]=r&255|He,r>>>=7;return t[e]=r|0,qe.bytes=e-n+1,t}var En=re,Ln=128,je=127;function re(r,n){var e=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw re.bytes=0,new RangeError("Could not decode varint");o=r[s++],e+=i<28?(o&je)<<i:(o&je)*Math.pow(2,i),i+=7}while(o>=Ln);return re.bytes=s-n,e}var An=Math.pow(2,7),Sn=Math.pow(2,14),Nn=Math.pow(2,21),Un=Math.pow(2,28),Dn=Math.pow(2,35),In=Math.pow(2,42),Rn=Math.pow(2,49),Tn=Math.pow(2,56),On=Math.pow(2,63),Fn=function(r){return r<An?1:r<Sn?2:r<Nn?3:r<Un?4:r<Dn?5:r<In?6:r<Rn?7:r<Tn?8:r<On?9:10},Bn={encode:bn,decode:En,encodingLength:Fn},_n=Bn,rt=_n;var nt=(r,t=0)=>[rt.decode(r,t),rt.decode.bytes],Q=(r,t,e=0)=>(rt.encode(r,t,e),t),Z=r=>rt.encodingLength(r);var $=(r,t)=>{let e=t.byteLength,n=Z(r),i=n+Z(e),s=new Uint8Array(i+e);return Q(r,s,0),Q(e,s,n),s.set(t,i),new Y(r,e,t,s)},We=r=>{let t=v(r),[e,n]=nt(t),[i,s]=nt(t.subarray(n)),o=t.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Y(e,i,o,t)},Ke=(r,t)=>{if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ve(r.bytes,e.bytes)}},Y=class{constructor(t,e,n,i){this.code=t,this.size=e,this.digest=n,this.bytes=i}};var Je=0,vn="identity",Qe=v,Cn=r=>$(Je,Qe(r)),Mn={code:Je,name:vn,encode:Qe,digest:Cn};var oe={};U(oe,{sha256:()=>kn,sha512:()=>Vn});var se=({name:r,code:t,encode:e})=>new ie(r,t,e),ie=class{constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?$(this.code,e):e.then(n=>$(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Ye=r=>async t=>new Uint8Array(await crypto.subtle.digest(r,t)),kn=se({name:"sha2-256",code:18,encode:Ye("SHA-256")}),Vn=se({name:"sha2-512",code:19,encode:Ye("SHA-512")});var tr=(r,t)=>{let{bytes:e,version:n}=r;switch(n){case 0:return Pn(e,ae(r),t||F.encoder);default:return Gn(e,ae(r),t||J.encoder)}};var er=new WeakMap,ae=r=>{let t=er.get(r);if(t==null){let e=new Map;return er.set(r,e),e}return t},Et=class r{constructor(t,e,n,i){this.code=e,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==st)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==$n)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=$(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n&&t.code===n.code&&t.version===n.version&&Ke(t.multihash,n.multihash)}toString(t){return tr(this,t)}toJSON(){return{"/":tr(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:i,multihash:s,bytes:o}=e;return new r(n,i,s,o||rr(n,i,s.bytes))}else if(e[Xn]===!0){let{version:n,multihash:i,code:s}=e,o=We(i);return r.create(n,s,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==st)throw new Error(`Version 0 CID must use dag-pb (code: ${st}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let i=rr(t,e,n.bytes);return new r(t,e,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,st,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,i=v(t.subarray(n,n+e.multihashSize));if(i.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=i.subarray(e.multihashSize-e.digestSize),o=new Y(e.multihashCode,e.digestSize,s,i);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,A]=nt(t.subarray(e));return e+=A,l},i=n(),s=st;if(i===18?(i=0,e=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=e,a=n(),c=n(),h=e+c,f=h-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:h}}static parse(t,e){let[n,i]=zn(t,e),s=r.decode(i);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ae(s).set(n,t),s}},zn=(r,t)=>{switch(r[0]){case"Q":{let e=t||F;return[F.prefix,e.decode(`${F.prefix}${r}`)]}case F.prefix:{let e=t||F;return[F.prefix,e.decode(r)]}case J.prefix:{let e=t||J;return[J.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}},Pn=(r,t,e)=>{let{prefix:n}=e;if(n!==F.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let i=t.get(n);if(i==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return i},Gn=(r,t,e)=>{let{prefix:n}=e,i=t.get(n);if(i==null){let s=e.encode(r);return t.set(n,s),s}else return i},st=112,$n=18,rr=(r,t,e)=>{let n=Z(r),i=n+Z(t),s=new Uint8Array(i+e.byteLength);return Q(r,s,0),Q(t,s,n),s.set(e,i),s},Xn=Symbol.for("@ipld/js-cid/CID");var ce={...ee,...Wt,...te,...jt,...qt,...Jt,...Qt,...Zt,...Yt,...Kt},Ss={...oe,...ne};function ir(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var nr=ir("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),he=ir("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=y(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Hn={utf8:nr,"utf-8":nr,hex:ce.base16,latin1:he,ascii:he,binary:he,...ce},Lt=Hn;function At(r,t="utf8"){let e=Lt[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?z(globalThis.Buffer.from(r,"utf-8")):e.decoder.decode(`${e.prefix}${r}`)}function sr(r,t="utf8"){let e=Lt[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):e.encoder.encode(r).substring(1)}var or="0.0.1",ar="fetch";var ue=new Float32Array([-0]),k=new Uint8Array(ue.buffer);function cr(r,t,e){ue[0]=r,t[e]=k[0],t[e+1]=k[1],t[e+2]=k[2],t[e+3]=k[3]}function hr(r,t){return k[0]=r[t],k[1]=r[t+1],k[2]=r[t+2],k[3]=r[t+3],ue[0]}var fe=new Float64Array([-0]),E=new Uint8Array(fe.buffer);function ur(r,t,e){fe[0]=r,t[e]=E[0],t[e+1]=E[1],t[e+2]=E[2],t[e+3]=E[3],t[e+4]=E[4],t[e+5]=E[5],t[e+6]=E[6],t[e+7]=E[7]}function fr(r,t){return E[0]=r[t],E[1]=r[t+1],E[2]=r[t+2],E[3]=r[t+3],E[4]=r[t+4],E[5]=r[t+5],E[6]=r[t+6],E[7]=r[t+7],fe[0]}var jn=BigInt(Number.MAX_SAFE_INTEGER),qn=BigInt(Number.MIN_SAFE_INTEGER),S=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return X;if(t<jn&&t>qn)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,i=t-(n<<32n);return e&&(n=~n|0n,i=~i|0n,++i>lr&&(i=0n,++n>lr&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(t){if(t===0)return X;let e=t<0;e&&(t=-t);let n=t>>>0,i=(t-n)/4294967296>>>0;return e&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):X}},X=new S(0,0);X.toBigInt=function(){return 0n};X.zzEncode=X.zzDecode=function(){return this};X.length=function(){return 1};var lr=4294967296n;function dr(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function pr(r,t,e){if(e-t<1)return"";let i,s=[],o=0,a;for(;t<e;)a=r[t++],a<128?s[o++]=a:a>191&&a<224?s[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[o++]=55296+(a>>10),s[o++]=56320+(a&1023)):s[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i!=null?(o>0&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))}function le(r,t,e){let n=e,i,s;for(let o=0;o<r.length;++o)i=r.charCodeAt(o),i<128?t[e++]=i:i<2048?(t[e++]=i>>6|192,t[e++]=i&63|128):(i&64512)===55296&&((s=r.charCodeAt(o+1))&64512)===56320?(i=65536+((i&1023)<<10)+(s&1023),++o,t[e++]=i>>18|240,t[e++]=i>>12&63|128,t[e++]=i>>6&63|128,t[e++]=i&63|128):(t[e++]=i>>12|224,t[e++]=i>>6&63|128,t[e++]=i&63|128);return e-n}function T(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function St(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var de=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,T(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw T(this,4);return St(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw T(this,4);return St(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw T(this,4);let t=hr(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw T(this,4);let t=fr(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw T(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return pr(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw T(this,t);this.pos+=t}else do if(this.pos>=this.len)throw T(this);while(this.buf[this.pos++]&128);return this}skipType(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}readLongVarint(){let t=new S(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>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 T(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw T(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw T(this,8);let t=St(this.buf,this.pos+=4),e=St(this.buf,this.pos+=4);return new S(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function pe(r){return new de(r instanceof Uint8Array?r:r.subarray())}function Nt(r,t){let e=pe(r);return t.decode(e)}function ge(r){let t=r??8192,e=t>>>1,n,i=t;return function(o){if(o<1||o>e)return y(o);i+o>t&&(n=y(t),i=0);let a=n.subarray(i,i+=o);return i&7&&(i=(i|7)+1),a}}var H=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function me(){}var we=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Wn=ge();function Kn(r){return globalThis.Buffer!=null?y(r):Wn(r)}var ct=class{len;head;tail;states;constructor(){this.len=0,this.head=new H(me,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new H(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ye((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ot,10,S.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=S.fromBigInt(t);return this._push(ot,e.length(),e)}uint64Number(t){let e=S.fromNumber(t);return this._push(ot,e.length(),e)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=S.fromBigInt(t).zzEncode();return this._push(ot,e.length(),e)}sint64Number(t){let e=S.fromNumber(t).zzEncode();return this._push(ot,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(be,1,t?1:0)}fixed32(t){return this._push(at,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=S.fromBigInt(t);return this._push(at,4,e.lo)._push(at,4,e.hi)}fixed64Number(t){let e=S.fromNumber(t);return this._push(at,4,e.lo)._push(at,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(cr,4,t)}double(t){return this._push(ur,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(be,1,0):this.uint32(e)._push(Qn,e,t)}string(t){let e=dr(t);return e!==0?this.uint32(e)._push(le,e,t):this._push(be,1,0)}fork(){return this.states=new we(this),this.head=this.tail=new H(me,0,0),this.len=0,this}reset(){return this.states!=null?(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 H(me,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Kn(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function be(r,t,e){t[e]=r&255}function Jn(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ye=class extends H{next;constructor(t,e){super(Jn,t,e),this.next=void 0}};function ot(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function at(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Qn(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ct.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Zn,t,r),this},ct.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Yn,t,r),this});function Zn(r,t,e){t.set(r,e)}function Yn(r,t,e){r.length<40?le(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(At(r),e)}function xe(){return new ct}function Ut(r,t){let e=xe();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var tt;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(tt||(tt={}));function Dt(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ee(r){function t(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let e=function(s,o){let a=t(s);o.int32(a)},n=function(s){let o=s.int32();return t(o)};return Dt("enum",tt.VARINT,e,n)}function It(r,t){return Dt("message",tt.LENGTH_DELIMITED,r,t)}var ht;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),e.identifier!=null&&e.identifier!==""&&(n.uint32(10),n.string(e.identifier)),i.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let i={identifier:""},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let o=e.uint32();switch(o>>>3){case 1:i.identifier=e.string();break;default:e.skipType(o&7);break}}return i})),t),r.encode=e=>Ut(e,r.codec()),r.decode=e=>Nt(e,r.codec())})(ht||(ht={}));var O;(function(r){let t;(function(i){i.OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR"})(t=r.StatusCode||(r.StatusCode={}));let e;(function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"})(e||(e={})),function(i){i.codec=()=>Ee(e)}(t=r.StatusCode||(r.StatusCode={}));let n;r.codec=()=>(n==null&&(n=It((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.status!=null&&e[i.status]!==0&&(s.uint32(8),r.StatusCode.codec().encode(i.status,s)),i.data!=null&&i.data.byteLength>0&&(s.uint32(18),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={status:t.OK,data:new Uint8Array(0)},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.status=r.StatusCode.codec().decode(i);break;case 2:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>Ut(i,r.codec()),r.decode=i=>Nt(i,r.codec())})(O||(O={}));var mr=1e4,Rt=class{protocol;components;lookupFunctions;started;init;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:fetch"),this.started=!1,this.components=t,this.protocol=`/${e.protocolPrefix??"libp2p"}/${ar}/${or}`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=e}async start(){await this.components.registrar.handle(this.protocol,t=>{this.handleMessage(t).then(async()=>{await t.stream.close()}).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async fetch(t,e,n={}){this.log("dialing %s to %p",this.protocol,t);let i=await this.components.connectionManager.openConnection(t,n),s=n.signal,o,a=()=>{};s==null&&(this.log("using default timeout of %d ms",this.init.timeout),s=AbortSignal.timeout(this.init.timeout??mr),Ue(1/0,s));try{o=await i.newStream(this.protocol,{signal:s}),a=()=>{o?.abort(new V("fetch timeout",Ae))},s.addEventListener("abort",a,{once:!0}),this.log("fetch %s",e);let c=Pt(o);await c.write({identifier:e},ht,n);let h=await c.read(O,n);switch(await c.unwrap().close(n),h.status){case O.StatusCode.OK:return this.log("received status for %s ok",e),h.data;case O.StatusCode.NOT_FOUND:{this.log("received status for %s not found",e);return}case O.StatusCode.ERROR:{this.log("received status for %s error",e);let f=sr(h.data);throw new V("Error in fetch protocol response: "+f,Se)}default:throw this.log("received status for %s unknown",e),new V("Unknown response status",Ne)}}catch(c){throw o?.abort(c),c}finally{s.removeEventListener("abort",a),o!=null&&await o.close()}}async handleMessage(t){let{stream:e}=t,n=AbortSignal.timeout(this.init.timeout??mr);try{let i=Pt(e),s=await i.read(ht,{signal:n}),o,a=this._getLookupFunction(s.identifier);if(a!=null){this.log("look up data with identifier %s",s.identifier);let c=await a(s.identifier);c!=null?(this.log("sending status for %s ok",s.identifier),o={status:O.StatusCode.OK,data:c}):(this.log("sending status for %s not found",s.identifier),o={status:O.StatusCode.NOT_FOUND,data:new Uint8Array(0)})}else{this.log("sending status for %s error",s.identifier);let c=At(`No lookup function registered for key: ${s.identifier}`);o={status:O.StatusCode.ERROR,data:c}}await i.write(o,O,{signal:n}),await i.unwrap().close({signal:n})}catch(i){this.log("error answering fetch request",i),e.abort(i)}}_getLookupFunction(t){for(let e of this.lookupFunctions.keys())if(t.startsWith(e))return this.lookupFunctions.get(e)}registerLookupFunction(t,e){if(this.lookupFunctions.has(t))throw new V(`Fetch protocol handler for key prefix '${t}' already registered`,"ERR_KEY_ALREADY_EXISTS");this.lookupFunctions.set(t,e)}unregisterLookupFunction(t,e){e!=null&&this.lookupFunctions.get(t)!==e||this.lookupFunctions.delete(t)}};function ti(r={}){return t=>new Rt(t,r)}return Sr(ei);})();
|
|
3
|
+
return Libp2PFetch}));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,gBAAgB,UAAU,CAAA;AACvC,eAAO,MAAM,aAAa,UAAU,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAA;AACvC,MAAM,CAAC,MAAM,aAAa,GAAG,OAAO,CAAA"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Fetch as FetchInterface, FetchComponents, FetchInit, LookupFunction } from './index.js';
|
|
2
|
+
import type { AbortOptions } from '@libp2p/interface';
|
|
3
|
+
import type { PeerId } from '@libp2p/interface/peer-id';
|
|
4
|
+
import type { Startable } from '@libp2p/interface/startable';
|
|
5
|
+
import type { IncomingStreamData } from '@libp2p/interface-internal/registrar';
|
|
6
|
+
/**
|
|
7
|
+
* A simple libp2p protocol for requesting a value corresponding to a key from a peer.
|
|
8
|
+
* Developers can register one or more lookup function for retrieving the value corresponding to
|
|
9
|
+
* a given key. Each lookup function must act on a distinct part of the overall key space, defined
|
|
10
|
+
* by a fixed prefix that all keys that should be routed to that lookup function will start with.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Fetch implements Startable, FetchInterface {
|
|
13
|
+
readonly protocol: string;
|
|
14
|
+
private readonly components;
|
|
15
|
+
private readonly lookupFunctions;
|
|
16
|
+
private started;
|
|
17
|
+
private readonly init;
|
|
18
|
+
private readonly log;
|
|
19
|
+
constructor(components: FetchComponents, init?: FetchInit);
|
|
20
|
+
start(): Promise<void>;
|
|
21
|
+
stop(): Promise<void>;
|
|
22
|
+
isStarted(): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Sends a request to fetch the value associated with the given key from the given peer
|
|
25
|
+
*/
|
|
26
|
+
fetch(peer: PeerId, key: string, options?: AbortOptions): Promise<Uint8Array | undefined>;
|
|
27
|
+
/**
|
|
28
|
+
* Invoked when a fetch request is received. Reads the request message off the given stream and
|
|
29
|
+
* responds based on looking up the key in the request via the lookup callback that corresponds
|
|
30
|
+
* to the key's prefix.
|
|
31
|
+
*/
|
|
32
|
+
handleMessage(data: IncomingStreamData): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Given a key, finds the appropriate function for looking up its corresponding value, based on
|
|
35
|
+
* the key's prefix.
|
|
36
|
+
*/
|
|
37
|
+
_getLookupFunction(key: string): LookupFunction | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
40
|
+
* share the same prefix
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
*
|
|
44
|
+
* ```js
|
|
45
|
+
* // ...
|
|
46
|
+
* libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
registerLookupFunction(prefix: string, lookup: LookupFunction): void;
|
|
50
|
+
/**
|
|
51
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
52
|
+
* share the same prefix.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
*
|
|
56
|
+
* ```js
|
|
57
|
+
* // ...
|
|
58
|
+
* libp2p.fetchService.unregisterLookupFunction('/prefix')
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
unregisterLookupFunction(prefix: string, lookup?: LookupFunction): void;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=fetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"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M,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI;IAQrE;;;;;;;;;;OAUG;IACH,wBAAwB,CAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,cAAc,GAAG,IAAI;CAWzE"}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { CodeError, ERR_INVALID_MESSAGE, ERR_INVALID_PARAMETERS, ERR_TIMEOUT } from '@libp2p/interface/errors';
|
|
2
|
+
import { setMaxListeners } from '@libp2p/interface/events';
|
|
3
|
+
import { pbStream } from 'it-protobuf-stream';
|
|
4
|
+
import { fromString as uint8arrayFromString } from 'uint8arrays/from-string';
|
|
5
|
+
import { toString as uint8arrayToString } from 'uint8arrays/to-string';
|
|
6
|
+
import { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js';
|
|
7
|
+
import { FetchRequest, FetchResponse } from './pb/proto.js';
|
|
8
|
+
const DEFAULT_TIMEOUT = 10000;
|
|
9
|
+
/**
|
|
10
|
+
* A simple libp2p protocol for requesting a value corresponding to a key from a peer.
|
|
11
|
+
* Developers can register one or more lookup function for retrieving the value corresponding to
|
|
12
|
+
* a given key. Each lookup function must act on a distinct part of the overall key space, defined
|
|
13
|
+
* by a fixed prefix that all keys that should be routed to that lookup function will start with.
|
|
14
|
+
*/
|
|
15
|
+
export class Fetch {
|
|
16
|
+
protocol;
|
|
17
|
+
components;
|
|
18
|
+
lookupFunctions;
|
|
19
|
+
started;
|
|
20
|
+
init;
|
|
21
|
+
log;
|
|
22
|
+
constructor(components, init = {}) {
|
|
23
|
+
this.log = components.logger.forComponent('libp2p:fetch');
|
|
24
|
+
this.started = false;
|
|
25
|
+
this.components = components;
|
|
26
|
+
this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;
|
|
27
|
+
this.lookupFunctions = new Map(); // Maps key prefix to value lookup function
|
|
28
|
+
this.handleMessage = this.handleMessage.bind(this);
|
|
29
|
+
this.init = init;
|
|
30
|
+
}
|
|
31
|
+
async start() {
|
|
32
|
+
await this.components.registrar.handle(this.protocol, (data) => {
|
|
33
|
+
void this.handleMessage(data)
|
|
34
|
+
.then(async () => {
|
|
35
|
+
await data.stream.close();
|
|
36
|
+
})
|
|
37
|
+
.catch(err => {
|
|
38
|
+
this.log.error(err);
|
|
39
|
+
});
|
|
40
|
+
}, {
|
|
41
|
+
maxInboundStreams: this.init.maxInboundStreams,
|
|
42
|
+
maxOutboundStreams: this.init.maxOutboundStreams
|
|
43
|
+
});
|
|
44
|
+
this.started = true;
|
|
45
|
+
}
|
|
46
|
+
async stop() {
|
|
47
|
+
await this.components.registrar.unhandle(this.protocol);
|
|
48
|
+
this.started = false;
|
|
49
|
+
}
|
|
50
|
+
isStarted() {
|
|
51
|
+
return this.started;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Sends a request to fetch the value associated with the given key from the given peer
|
|
55
|
+
*/
|
|
56
|
+
async fetch(peer, key, options = {}) {
|
|
57
|
+
this.log('dialing %s to %p', this.protocol, peer);
|
|
58
|
+
const connection = await this.components.connectionManager.openConnection(peer, options);
|
|
59
|
+
let signal = options.signal;
|
|
60
|
+
let stream;
|
|
61
|
+
let onAbort = () => { };
|
|
62
|
+
// create a timeout if no abort signal passed
|
|
63
|
+
if (signal == null) {
|
|
64
|
+
this.log('using default timeout of %d ms', this.init.timeout);
|
|
65
|
+
signal = AbortSignal.timeout(this.init.timeout ?? DEFAULT_TIMEOUT);
|
|
66
|
+
setMaxListeners(Infinity, signal);
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
stream = await connection.newStream(this.protocol, {
|
|
70
|
+
signal
|
|
71
|
+
});
|
|
72
|
+
onAbort = () => {
|
|
73
|
+
stream?.abort(new CodeError('fetch timeout', ERR_TIMEOUT));
|
|
74
|
+
};
|
|
75
|
+
// make stream abortable
|
|
76
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
77
|
+
this.log('fetch %s', key);
|
|
78
|
+
const pb = pbStream(stream);
|
|
79
|
+
await pb.write({
|
|
80
|
+
identifier: key
|
|
81
|
+
}, FetchRequest, options);
|
|
82
|
+
const response = await pb.read(FetchResponse, options);
|
|
83
|
+
await pb.unwrap().close(options);
|
|
84
|
+
switch (response.status) {
|
|
85
|
+
case (FetchResponse.StatusCode.OK): {
|
|
86
|
+
this.log('received status for %s ok', key);
|
|
87
|
+
return response.data;
|
|
88
|
+
}
|
|
89
|
+
case (FetchResponse.StatusCode.NOT_FOUND): {
|
|
90
|
+
this.log('received status for %s not found', key);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
case (FetchResponse.StatusCode.ERROR): {
|
|
94
|
+
this.log('received status for %s error', key);
|
|
95
|
+
const errmsg = uint8arrayToString(response.data);
|
|
96
|
+
throw new CodeError('Error in fetch protocol response: ' + errmsg, ERR_INVALID_PARAMETERS);
|
|
97
|
+
}
|
|
98
|
+
default: {
|
|
99
|
+
this.log('received status for %s unknown', key);
|
|
100
|
+
throw new CodeError('Unknown response status', ERR_INVALID_MESSAGE);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
stream?.abort(err);
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
signal.removeEventListener('abort', onAbort);
|
|
110
|
+
if (stream != null) {
|
|
111
|
+
await stream.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Invoked when a fetch request is received. Reads the request message off the given stream and
|
|
117
|
+
* responds based on looking up the key in the request via the lookup callback that corresponds
|
|
118
|
+
* to the key's prefix.
|
|
119
|
+
*/
|
|
120
|
+
async handleMessage(data) {
|
|
121
|
+
const { stream } = data;
|
|
122
|
+
const signal = AbortSignal.timeout(this.init.timeout ?? DEFAULT_TIMEOUT);
|
|
123
|
+
try {
|
|
124
|
+
const pb = pbStream(stream);
|
|
125
|
+
const request = await pb.read(FetchRequest, {
|
|
126
|
+
signal
|
|
127
|
+
});
|
|
128
|
+
let response;
|
|
129
|
+
const lookup = this._getLookupFunction(request.identifier);
|
|
130
|
+
if (lookup != null) {
|
|
131
|
+
this.log('look up data with identifier %s', request.identifier);
|
|
132
|
+
const data = await lookup(request.identifier);
|
|
133
|
+
if (data != null) {
|
|
134
|
+
this.log('sending status for %s ok', request.identifier);
|
|
135
|
+
response = { status: FetchResponse.StatusCode.OK, data };
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
this.log('sending status for %s not found', request.identifier);
|
|
139
|
+
response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
this.log('sending status for %s error', request.identifier);
|
|
144
|
+
const errmsg = uint8arrayFromString(`No lookup function registered for key: ${request.identifier}`);
|
|
145
|
+
response = { status: FetchResponse.StatusCode.ERROR, data: errmsg };
|
|
146
|
+
}
|
|
147
|
+
await pb.write(response, FetchResponse, {
|
|
148
|
+
signal
|
|
149
|
+
});
|
|
150
|
+
await pb.unwrap().close({
|
|
151
|
+
signal
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
this.log('error answering fetch request', err);
|
|
156
|
+
stream.abort(err);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Given a key, finds the appropriate function for looking up its corresponding value, based on
|
|
161
|
+
* the key's prefix.
|
|
162
|
+
*/
|
|
163
|
+
_getLookupFunction(key) {
|
|
164
|
+
for (const prefix of this.lookupFunctions.keys()) {
|
|
165
|
+
if (key.startsWith(prefix)) {
|
|
166
|
+
return this.lookupFunctions.get(prefix);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
172
|
+
* share the same prefix
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
*
|
|
176
|
+
* ```js
|
|
177
|
+
* // ...
|
|
178
|
+
* libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
registerLookupFunction(prefix, lookup) {
|
|
182
|
+
if (this.lookupFunctions.has(prefix)) {
|
|
183
|
+
throw new CodeError(`Fetch protocol handler for key prefix '${prefix}' already registered`, 'ERR_KEY_ALREADY_EXISTS');
|
|
184
|
+
}
|
|
185
|
+
this.lookupFunctions.set(prefix, lookup);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
189
|
+
* share the same prefix.
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
*
|
|
193
|
+
* ```js
|
|
194
|
+
* // ...
|
|
195
|
+
* libp2p.fetchService.unregisterLookupFunction('/prefix')
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
unregisterLookupFunction(prefix, lookup) {
|
|
199
|
+
if (lookup != null) {
|
|
200
|
+
const existingLookup = this.lookupFunctions.get(prefix);
|
|
201
|
+
if (existingLookup !== lookup) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
this.lookupFunctions.delete(prefix);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=fetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAE,UAAU,IAAI,oBAAoB,EAAE,MAAM,yBAA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,EAAE;gBAC1B,OAAO,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;aACxC;SACF;IACH,CAAC;IAED;;;;;;;;;;OAUG;IACH,sBAAsB,CAAE,MAAc,EAAE,MAAsB;QAC5D,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YACpC,MAAM,IAAI,SAAS,CAAC,0CAA0C,MAAM,sBAAsB,EAAE,wBAAwB,CAAC,CAAA;SACtH;QAED,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC1C,CAAC;IAED;;;;;;;;;;OAUG;IACH,wBAAwB,CAAE,MAAc,EAAE,MAAuB;QAC/D,IAAI,MAAM,IAAI,IAAI,EAAE;YAClB,MAAM,cAAc,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YAEvD,IAAI,cAAc,KAAK,MAAM,EAAE;gBAC7B,OAAM;aACP;SACF;QAED,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IACrC,CAAC;CACF"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* An implementation of the Fetch protocol as described here: https://github.com/libp2p/specs/tree/master/fetch
|
|
5
|
+
*
|
|
6
|
+
* The fetch protocol is a simple protocol for requesting a value corresponding to a key from a peer.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
*
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { createLibp2p } from 'libp2p'
|
|
12
|
+
* import { fetch } from '@libp2p/fetch'
|
|
13
|
+
*
|
|
14
|
+
* const libp2p = await createLibp2p({
|
|
15
|
+
* services: {
|
|
16
|
+
* fetch: fetch()
|
|
17
|
+
* }
|
|
18
|
+
* })
|
|
19
|
+
*
|
|
20
|
+
* // Given a key (as a string) returns a value (as a Uint8Array), or null if the key isn't found.
|
|
21
|
+
* // All keys must be prefixed my the same prefix, which will be used to find the appropriate key
|
|
22
|
+
* // lookup function.
|
|
23
|
+
* async function my_subsystem_key_lookup(key) {
|
|
24
|
+
* // app specific callback to lookup key-value pairs.
|
|
25
|
+
* }
|
|
26
|
+
*
|
|
27
|
+
* // Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
|
|
28
|
+
* libp2p.fetch.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
|
|
29
|
+
*
|
|
30
|
+
* const key = '/my_subsystem_key_prefix/{...}'
|
|
31
|
+
* const peerDst = PeerId.parse('Qmfoo...') // or Multiaddr instance
|
|
32
|
+
* const value = await libp2p.fetch(peerDst, key)
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
import type { AbortOptions, ComponentLogger } from '@libp2p/interface';
|
|
36
|
+
import type { PeerId } from '@libp2p/interface/peer-id';
|
|
37
|
+
import type { ConnectionManager } from '@libp2p/interface-internal/connection-manager';
|
|
38
|
+
import type { Registrar } from '@libp2p/interface-internal/registrar';
|
|
39
|
+
export interface FetchInit {
|
|
40
|
+
protocolPrefix?: string;
|
|
41
|
+
maxInboundStreams?: number;
|
|
42
|
+
maxOutboundStreams?: number;
|
|
43
|
+
/**
|
|
44
|
+
* How long we should wait for a remote peer to send any data
|
|
45
|
+
*/
|
|
46
|
+
timeout?: number;
|
|
47
|
+
}
|
|
48
|
+
export interface LookupFunction {
|
|
49
|
+
(key: string): Promise<Uint8Array | undefined>;
|
|
50
|
+
}
|
|
51
|
+
export interface FetchComponents {
|
|
52
|
+
registrar: Registrar;
|
|
53
|
+
connectionManager: ConnectionManager;
|
|
54
|
+
logger: ComponentLogger;
|
|
55
|
+
}
|
|
56
|
+
export interface Fetch {
|
|
57
|
+
/**
|
|
58
|
+
* Sends a request to fetch the value associated with the given key from the given peer
|
|
59
|
+
*/
|
|
60
|
+
fetch(peer: PeerId, key: string, options?: AbortOptions): Promise<Uint8Array | undefined>;
|
|
61
|
+
/**
|
|
62
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
63
|
+
* share the same prefix
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
*
|
|
67
|
+
* ```js
|
|
68
|
+
* // ...
|
|
69
|
+
* libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
registerLookupFunction(prefix: string, lookup: LookupFunction): void;
|
|
73
|
+
/**
|
|
74
|
+
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
75
|
+
* share the same prefix.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
*
|
|
79
|
+
* ```js
|
|
80
|
+
* // ...
|
|
81
|
+
* libp2p.fetchService.unregisterLookupFunction('/prefix')
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
unregisterLookupFunction(prefix: string, lookup?: LookupFunction): void;
|
|
85
|
+
}
|
|
86
|
+
export declare function fetch(init?: FetchInit): (components: FetchComponents) => Fetch;
|
|
87
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACtE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAA;AACtF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAA;AAErE,MAAM,WAAW,SAAS;IACxB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAA;CAC/C;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,SAAS,CAAA;IACpB,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,MAAM,WAAW,KAAK;IACpB;;OAEG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAA;IAEzF;;;;;;;;;;OAUG;IACH,sBAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAAA;IAEpE;;;;;;;;;;OAUG;IACH,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,cAAc,GAAG,IAAI,CAAA;CACxE;AAED,wBAAgB,KAAK,CAAE,IAAI,GAAE,SAAc,GAAG,CAAC,UAAU,EAAE,eAAe,KAAK,KAAK,CAEnF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* An implementation of the Fetch protocol as described here: https://github.com/libp2p/specs/tree/master/fetch
|
|
5
|
+
*
|
|
6
|
+
* The fetch protocol is a simple protocol for requesting a value corresponding to a key from a peer.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
*
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { createLibp2p } from 'libp2p'
|
|
12
|
+
* import { fetch } from '@libp2p/fetch'
|
|
13
|
+
*
|
|
14
|
+
* const libp2p = await createLibp2p({
|
|
15
|
+
* services: {
|
|
16
|
+
* fetch: fetch()
|
|
17
|
+
* }
|
|
18
|
+
* })
|
|
19
|
+
*
|
|
20
|
+
* // Given a key (as a string) returns a value (as a Uint8Array), or null if the key isn't found.
|
|
21
|
+
* // All keys must be prefixed my the same prefix, which will be used to find the appropriate key
|
|
22
|
+
* // lookup function.
|
|
23
|
+
* async function my_subsystem_key_lookup(key) {
|
|
24
|
+
* // app specific callback to lookup key-value pairs.
|
|
25
|
+
* }
|
|
26
|
+
*
|
|
27
|
+
* // Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
|
|
28
|
+
* libp2p.fetch.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
|
|
29
|
+
*
|
|
30
|
+
* const key = '/my_subsystem_key_prefix/{...}'
|
|
31
|
+
* const peerDst = PeerId.parse('Qmfoo...') // or Multiaddr instance
|
|
32
|
+
* const value = await libp2p.fetch(peerDst, key)
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
import { Fetch as FetchClass } from './fetch.js';
|
|
36
|
+
export function fetch(init = {}) {
|
|
37
|
+
return (components) => new FetchClass(components, init);
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,YAAY,CAAA;AA4DhD,MAAM,UAAU,KAAK,CAAE,OAAkB,EAAE;IACzC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACzD,CAAC"}
|