@libp2p/webtransport 3.0.3-123ded59 → 3.0.3-5e85154b

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.
@@ -0,0 +1,77 @@
1
+ import { peerIdFromString } from '@libp2p/peer-id';
2
+ import { protocols } from '@multiformats/multiaddr';
3
+ import { bases, digest } from 'multiformats/basics';
4
+ // @ts-expect-error - Not easy to combine these types.
5
+ const multibaseDecoder = Object.values(bases).map(b => b.decoder).reduce((d, b) => d.or(b));
6
+ function decodeCerthashStr(s) {
7
+ return digest.decode(multibaseDecoder.decode(s));
8
+ }
9
+ export function parseMultiaddr(ma) {
10
+ const parts = ma.stringTuples();
11
+ // This is simpler to have inline than extract into a separate function
12
+ // eslint-disable-next-line complexity
13
+ const { url, certhashes, remotePeer } = parts.reduce((state, [proto, value]) => {
14
+ switch (proto) {
15
+ case protocols('ip6').code:
16
+ // @ts-expect-error - ts error on switch fallthrough
17
+ case protocols('dns6').code:
18
+ if (value?.includes(':') === true) {
19
+ /**
20
+ * This resolves cases where `new globalThis.WebTransport` fails to construct because of an invalid URL being passed.
21
+ *
22
+ * `new URL('https://::1:4001/blah')` will throw a `TypeError: Failed to construct 'URL': Invalid URL`
23
+ * `new URL('https://[::1]:4001/blah')` is valid and will not.
24
+ *
25
+ * @see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2
26
+ */
27
+ value = `[${value}]`;
28
+ }
29
+ // eslint-disable-next-line no-fallthrough
30
+ case protocols('ip4').code:
31
+ case protocols('dns4').code:
32
+ if (state.seenHost || state.seenPort) {
33
+ throw new Error('Invalid multiaddr, saw host and already saw the host or port');
34
+ }
35
+ return {
36
+ ...state,
37
+ url: `${state.url}${value ?? ''}`,
38
+ seenHost: true
39
+ };
40
+ case protocols('quic').code:
41
+ case protocols('quic-v1').code:
42
+ case protocols('webtransport').code:
43
+ if (!state.seenHost || !state.seenPort) {
44
+ throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");
45
+ }
46
+ return state;
47
+ case protocols('udp').code:
48
+ if (state.seenPort) {
49
+ throw new Error('Invalid multiaddr, saw port but already saw the port');
50
+ }
51
+ return {
52
+ ...state,
53
+ url: `${state.url}:${value ?? ''}`,
54
+ seenPort: true
55
+ };
56
+ case protocols('certhash').code:
57
+ if (!state.seenHost || !state.seenPort) {
58
+ throw new Error('Invalid multiaddr, saw the certhash before seeing the host and port');
59
+ }
60
+ return {
61
+ ...state,
62
+ certhashes: state.certhashes.concat([decodeCerthashStr(value ?? '')])
63
+ };
64
+ case protocols('p2p').code:
65
+ return {
66
+ ...state,
67
+ remotePeer: peerIdFromString(value ?? '')
68
+ };
69
+ default:
70
+ throw new Error(`unexpected component in multiaddr: ${proto} ${protocols(proto).name} ${value ?? ''} `);
71
+ }
72
+ },
73
+ // All webtransport urls are https
74
+ { url: 'https://', seenHost: false, seenPort: false, certhashes: [] });
75
+ return { url, certhashes, remotePeer };
76
+ }
77
+ //# sourceMappingURL=parse-multiaddr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-multiaddr.js","sourceRoot":"","sources":["../../../src/utils/parse-multiaddr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAClD,OAAO,EAAkB,SAAS,EAAE,MAAM,yBAAyB,CAAA;AACnE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAInD,sDAAsD;AACtD,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;AAE3F,SAAS,iBAAiB,CAAE,CAAS;IACnC,OAAO,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,MA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  {
2
2
  "name": "@libp2p/webtransport",
3
- "version": "3.0.3-123ded59",
3
+ "version": "3.0.3-5e85154b",
4
4
  "description": "JavaScript implementation of the WebTransport module that libp2p uses and that implements the interface-transport spec",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/transport-webtransport#readme",
@@ -65,17 +65,18 @@
65
65
  },
66
66
  "dependencies": {
67
67
  "@chainsafe/libp2p-noise": "^13.0.0",
68
- "@libp2p/interface": "0.1.1-123ded59",
69
- "@libp2p/logger": "3.0.1-123ded59",
70
- "@libp2p/peer-id": "3.0.1-123ded59",
68
+ "@libp2p/interface": "0.1.1-5e85154b",
69
+ "@libp2p/logger": "3.0.1-5e85154b",
70
+ "@libp2p/peer-id": "3.0.1-5e85154b",
71
71
  "@multiformats/multiaddr": "^12.1.3",
72
72
  "it-stream-types": "^2.0.1",
73
73
  "multiformats": "^12.0.1",
74
- "uint8arraylist": "^2.4.3"
74
+ "uint8arraylist": "^2.4.3",
75
+ "uint8arrays": "^4.0.6"
75
76
  },
76
77
  "devDependencies": {
77
78
  "aegir": "^40.0.1",
78
- "libp2p": "0.46.3-123ded59",
79
+ "libp2p": "0.46.3-5e85154b",
79
80
  "p-defer": "^4.0.0"
80
81
  },
81
82
  "browser": {
package/src/index.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { noise } from '@chainsafe/libp2p-noise'
2
2
  import { type Transport, symbol, type CreateListenerOptions, type DialOptions, type Listener } from '@libp2p/interface/transport'
3
3
  import { logger } from '@libp2p/logger'
4
- import { peerIdFromString } from '@libp2p/peer-id'
5
- import { type Multiaddr, protocols, type AbortOptions } from '@multiformats/multiaddr'
6
- import { bases, digest } from 'multiformats/basics'
7
- import { Uint8ArrayList } from 'uint8arraylist'
8
- import type { Connection, Direction, MultiaddrConnection, Stream } from '@libp2p/interface/connection'
4
+ import { type Multiaddr, type AbortOptions } from '@multiformats/multiaddr'
5
+ import { webtransportBiDiStreamToStream } from './stream.js'
6
+ import { inertDuplex } from './utils/inert-duplex.js'
7
+ import { isSubset } from './utils/is-subset.js'
8
+ import { parseMultiaddr } from './utils/parse-multiaddr.js'
9
+ import type { Connection, MultiaddrConnection, Stream } from '@libp2p/interface/connection'
9
10
  import type { PeerId } from '@libp2p/interface/peer-id'
10
11
  import type { StreamMuxerFactory, StreamMuxerInit, StreamMuxer } from '@libp2p/interface/stream-muxer'
11
- import type { Duplex, Source } from 'it-stream-types'
12
+ import type { Source } from 'it-stream-types'
12
13
  import type { MultihashDigest } from 'multiformats/hashes/interface'
13
14
 
14
15
  declare global {
@@ -17,300 +18,6 @@ declare global {
17
18
 
18
19
  const log = logger('libp2p:webtransport')
19
20
 
20
- // @ts-expect-error - Not easy to combine these types.
21
- const multibaseDecoder = Object.values(bases).map(b => b.decoder).reduce((d, b) => d.or(b))
22
-
23
- function decodeCerthashStr (s: string): MultihashDigest {
24
- return digest.decode(multibaseDecoder.decode(s))
25
- }
26
-
27
- // Duplex that does nothing. Needed to fulfill the interface
28
- function inertDuplex (): Duplex<any, any, any> {
29
- return {
30
- source: {
31
- [Symbol.asyncIterator] () {
32
- return {
33
- async next () {
34
- // This will never resolve
35
- return new Promise(() => { })
36
- }
37
- }
38
- }
39
- },
40
- sink: async (source: Source<any>) => {
41
- // This will never resolve
42
- return new Promise(() => { })
43
- }
44
- }
45
- }
46
-
47
- async function webtransportBiDiStreamToStream (bidiStream: any, streamId: string, direction: Direction, activeStreams: Stream[], onStreamEnd: undefined | ((s: Stream) => void)): Promise<Stream> {
48
- const writer = bidiStream.writable.getWriter()
49
- const reader = bidiStream.readable.getReader()
50
- await writer.ready
51
-
52
- function cleanupStreamFromActiveStreams (): void {
53
- const index = activeStreams.findIndex(s => s === stream)
54
- if (index !== -1) {
55
- activeStreams.splice(index, 1)
56
- stream.timeline.close = Date.now()
57
- onStreamEnd?.(stream)
58
- }
59
- }
60
-
61
- let writerClosed = false
62
- let readerClosed = false;
63
- (async function () {
64
- const err: Error | undefined = await writer.closed.catch((err: Error) => err)
65
- if (err != null) {
66
- const msg = err.message
67
- if (!(msg.includes('aborted by the remote server') || msg.includes('STOP_SENDING'))) {
68
- log.error(`WebTransport writer closed unexpectedly: streamId=${streamId} err=${err.message}`)
69
- }
70
- }
71
- writerClosed = true
72
- if (writerClosed && readerClosed) {
73
- cleanupStreamFromActiveStreams()
74
- }
75
- })().catch(() => {
76
- log.error('WebTransport failed to cleanup closed stream')
77
- });
78
-
79
- (async function () {
80
- const err: Error | undefined = await reader.closed.catch((err: Error) => err)
81
- if (err != null) {
82
- log.error(`WebTransport reader closed unexpectedly: streamId=${streamId} err=${err.message}`)
83
- }
84
- readerClosed = true
85
- if (writerClosed && readerClosed) {
86
- cleanupStreamFromActiveStreams()
87
- }
88
- })().catch(() => {
89
- log.error('WebTransport failed to cleanup closed stream')
90
- })
91
-
92
- let sinkSunk = false
93
- const stream: Stream = {
94
- id: streamId,
95
- status: 'open',
96
- writeStatus: 'ready',
97
- readStatus: 'ready',
98
- abort (err: Error) {
99
- if (!writerClosed) {
100
- writer.abort()
101
- writerClosed = true
102
- }
103
- stream.abort(err)
104
- readerClosed = true
105
-
106
- this.status = 'aborted'
107
- this.writeStatus = 'closed'
108
- this.readStatus = 'closed'
109
-
110
- this.timeline.reset =
111
- this.timeline.close =
112
- this.timeline.closeRead =
113
- this.timeline.closeWrite = Date.now()
114
-
115
- cleanupStreamFromActiveStreams()
116
- },
117
- async close (options?: AbortOptions) {
118
- this.status = 'closing'
119
-
120
- await Promise.all([
121
- stream.closeRead(options),
122
- stream.closeWrite(options)
123
- ])
124
-
125
- cleanupStreamFromActiveStreams()
126
-
127
- this.status = 'closed'
128
- this.timeline.close = Date.now()
129
- },
130
-
131
- async closeRead (options?: AbortOptions) {
132
- if (!readerClosed) {
133
- this.readStatus = 'closing'
134
-
135
- try {
136
- await reader.cancel()
137
- } catch (err: any) {
138
- if (err.toString().includes('RESET_STREAM') === true) {
139
- writerClosed = true
140
- }
141
- }
142
-
143
- this.timeline.closeRead = Date.now()
144
- this.readStatus = 'closed'
145
-
146
- readerClosed = true
147
- }
148
-
149
- if (writerClosed) {
150
- cleanupStreamFromActiveStreams()
151
- }
152
- },
153
-
154
- async closeWrite (options?: AbortOptions) {
155
- if (!writerClosed) {
156
- writerClosed = true
157
-
158
- this.writeStatus = 'closing'
159
-
160
- try {
161
- await writer.close()
162
- } catch (err: any) {
163
- if (err.toString().includes('RESET_STREAM') === true) {
164
- readerClosed = true
165
- }
166
- }
167
-
168
- this.timeline.closeWrite = Date.now()
169
- this.writeStatus = 'closed'
170
- }
171
-
172
- if (readerClosed) {
173
- cleanupStreamFromActiveStreams()
174
- }
175
- },
176
- direction,
177
- timeline: { open: Date.now() },
178
- metadata: {},
179
- source: (async function * () {
180
- while (true) {
181
- const val = await reader.read()
182
- if (val.done === true) {
183
- readerClosed = true
184
- if (writerClosed) {
185
- cleanupStreamFromActiveStreams()
186
- }
187
- return
188
- }
189
-
190
- yield new Uint8ArrayList(val.value)
191
- }
192
- })(),
193
- sink: async function (source: Source<Uint8Array | Uint8ArrayList>) {
194
- if (sinkSunk) {
195
- throw new Error('sink already called on stream')
196
- }
197
- sinkSunk = true
198
- try {
199
- this.writeStatus = 'writing'
200
-
201
- for await (const chunks of source) {
202
- if (chunks instanceof Uint8Array) {
203
- await writer.write(chunks)
204
- } else {
205
- for (const buf of chunks) {
206
- await writer.write(buf)
207
- }
208
- }
209
- }
210
-
211
- this.writeStatus = 'done'
212
- } finally {
213
- this.timeline.closeWrite = Date.now()
214
- this.writeStatus = 'closed'
215
-
216
- await stream.closeWrite()
217
- }
218
- }
219
- }
220
-
221
- return stream
222
- }
223
-
224
- function parseMultiaddr (ma: Multiaddr): { url: string, certhashes: MultihashDigest[], remotePeer?: PeerId } {
225
- const parts = ma.stringTuples()
226
-
227
- // This is simpler to have inline than extract into a separate function
228
- // eslint-disable-next-line complexity
229
- const { url, certhashes, remotePeer } = parts.reduce((state: { url: string, certhashes: MultihashDigest[], seenHost: boolean, seenPort: boolean, remotePeer?: PeerId }, [proto, value]) => {
230
- switch (proto) {
231
- case protocols('ip6').code:
232
- // @ts-expect-error - ts error on switch fallthrough
233
- case protocols('dns6').code:
234
- if (value?.includes(':') === true) {
235
- /**
236
- * This resolves cases where `new globalThis.WebTransport` fails to construct because of an invalid URL being passed.
237
- *
238
- * `new URL('https://::1:4001/blah')` will throw a `TypeError: Failed to construct 'URL': Invalid URL`
239
- * `new URL('https://[::1]:4001/blah')` is valid and will not.
240
- *
241
- * @see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2
242
- */
243
- value = `[${value}]`
244
- }
245
- // eslint-disable-next-line no-fallthrough
246
- case protocols('ip4').code:
247
- case protocols('dns4').code:
248
- if (state.seenHost || state.seenPort) {
249
- throw new Error('Invalid multiaddr, saw host and already saw the host or port')
250
- }
251
- return {
252
- ...state,
253
- url: `${state.url}${value ?? ''}`,
254
- seenHost: true
255
- }
256
- case protocols('quic').code:
257
- case protocols('quic-v1').code:
258
- case protocols('webtransport').code:
259
- if (!state.seenHost || !state.seenPort) {
260
- throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport")
261
- }
262
- return state
263
- case protocols('udp').code:
264
- if (state.seenPort) {
265
- throw new Error('Invalid multiaddr, saw port but already saw the port')
266
- }
267
- return {
268
- ...state,
269
- url: `${state.url}:${value ?? ''}`,
270
- seenPort: true
271
- }
272
- case protocols('certhash').code:
273
- if (!state.seenHost || !state.seenPort) {
274
- throw new Error('Invalid multiaddr, saw the certhash before seeing the host and port')
275
- }
276
- return {
277
- ...state,
278
- certhashes: state.certhashes.concat([decodeCerthashStr(value ?? '')])
279
- }
280
- case protocols('p2p').code:
281
- return {
282
- ...state,
283
- remotePeer: peerIdFromString(value ?? '')
284
- }
285
- default:
286
- throw new Error(`unexpected component in multiaddr: ${proto} ${protocols(proto).name} ${value ?? ''} `)
287
- }
288
- },
289
- // All webtransport urls are https
290
- { url: 'https://', seenHost: false, seenPort: false, certhashes: [] })
291
-
292
- return { url, certhashes, remotePeer }
293
- }
294
-
295
- // Determines if `maybeSubset` is a subset of `set`. This means that all byte arrays in `maybeSubset` are present in `set`.
296
- export function isSubset (set: Uint8Array[], maybeSubset: Uint8Array[]): boolean {
297
- const intersection = maybeSubset.filter(byteArray => {
298
- return Boolean(set.find((otherByteArray: Uint8Array) => {
299
- if (byteArray.length !== otherByteArray.length) {
300
- return false
301
- }
302
-
303
- for (let index = 0; index < byteArray.length; index++) {
304
- if (otherByteArray[index] !== byteArray[index]) {
305
- return false
306
- }
307
- }
308
- return true
309
- }))
310
- })
311
- return (intersection.length === maybeSubset.length)
312
- }
313
-
314
21
  export interface WebTransportInit {
315
22
  maxInboundStreams?: number
316
23
  }
package/src/stream.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { logger } from '@libp2p/logger'
2
+ import { Uint8ArrayList } from 'uint8arraylist'
3
+ import type { AbortOptions } from '@libp2p/interface'
4
+ import type { Direction, Stream } from '@libp2p/interface/connection'
5
+ import type { Source } from 'it-stream-types'
6
+
7
+ const log = logger('libp2p:webtransport:stream')
8
+
9
+ export async function webtransportBiDiStreamToStream (bidiStream: any, streamId: string, direction: Direction, activeStreams: Stream[], onStreamEnd: undefined | ((s: Stream) => void)): Promise<Stream> {
10
+ const writer = bidiStream.writable.getWriter()
11
+ const reader = bidiStream.readable.getReader()
12
+ await writer.ready
13
+
14
+ function cleanupStreamFromActiveStreams (): void {
15
+ const index = activeStreams.findIndex(s => s === stream)
16
+ if (index !== -1) {
17
+ activeStreams.splice(index, 1)
18
+ stream.timeline.close = Date.now()
19
+ onStreamEnd?.(stream)
20
+ }
21
+ }
22
+
23
+ let writerClosed = false
24
+ let readerClosed = false;
25
+ (async function () {
26
+ const err: Error | undefined = await writer.closed.catch((err: Error) => err)
27
+ if (err != null) {
28
+ const msg = err.message
29
+ if (!(msg.includes('aborted by the remote server') || msg.includes('STOP_SENDING'))) {
30
+ log.error(`WebTransport writer closed unexpectedly: streamId=${streamId} err=${err.message}`)
31
+ }
32
+ }
33
+ writerClosed = true
34
+ if (writerClosed && readerClosed) {
35
+ cleanupStreamFromActiveStreams()
36
+ }
37
+ })().catch(() => {
38
+ log.error('WebTransport failed to cleanup closed stream')
39
+ });
40
+
41
+ (async function () {
42
+ const err: Error | undefined = await reader.closed.catch((err: Error) => err)
43
+ if (err != null) {
44
+ log.error(`WebTransport reader closed unexpectedly: streamId=${streamId} err=${err.message}`)
45
+ }
46
+ readerClosed = true
47
+ if (writerClosed && readerClosed) {
48
+ cleanupStreamFromActiveStreams()
49
+ }
50
+ })().catch(() => {
51
+ log.error('WebTransport failed to cleanup closed stream')
52
+ })
53
+
54
+ let sinkSunk = false
55
+ const stream: Stream = {
56
+ id: streamId,
57
+ status: 'open',
58
+ writeStatus: 'ready',
59
+ readStatus: 'ready',
60
+ abort (err: Error) {
61
+ if (!writerClosed) {
62
+ writer.abort(err)
63
+ writerClosed = true
64
+ }
65
+ readerClosed = true
66
+
67
+ this.status = 'aborted'
68
+ this.writeStatus = 'closed'
69
+ this.readStatus = 'closed'
70
+
71
+ this.timeline.reset =
72
+ this.timeline.close =
73
+ this.timeline.closeRead =
74
+ this.timeline.closeWrite = Date.now()
75
+
76
+ cleanupStreamFromActiveStreams()
77
+ },
78
+ async close (options?: AbortOptions) {
79
+ this.status = 'closing'
80
+
81
+ await Promise.all([
82
+ stream.closeRead(options),
83
+ stream.closeWrite(options)
84
+ ])
85
+
86
+ cleanupStreamFromActiveStreams()
87
+
88
+ this.status = 'closed'
89
+ this.timeline.close = Date.now()
90
+ },
91
+
92
+ async closeRead (options?: AbortOptions) {
93
+ if (!readerClosed) {
94
+ this.readStatus = 'closing'
95
+
96
+ try {
97
+ await reader.cancel()
98
+ } catch (err: any) {
99
+ if (err.toString().includes('RESET_STREAM') === true) {
100
+ writerClosed = true
101
+ }
102
+ }
103
+
104
+ this.timeline.closeRead = Date.now()
105
+ this.readStatus = 'closed'
106
+
107
+ readerClosed = true
108
+ }
109
+
110
+ if (writerClosed) {
111
+ cleanupStreamFromActiveStreams()
112
+ }
113
+ },
114
+
115
+ async closeWrite (options?: AbortOptions) {
116
+ if (!writerClosed) {
117
+ writerClosed = true
118
+
119
+ this.writeStatus = 'closing'
120
+
121
+ try {
122
+ await writer.close()
123
+ } catch (err: any) {
124
+ if (err.toString().includes('RESET_STREAM') === true) {
125
+ readerClosed = true
126
+ }
127
+ }
128
+
129
+ this.timeline.closeWrite = Date.now()
130
+ this.writeStatus = 'closed'
131
+ }
132
+
133
+ if (readerClosed) {
134
+ cleanupStreamFromActiveStreams()
135
+ }
136
+ },
137
+ direction,
138
+ timeline: { open: Date.now() },
139
+ metadata: {},
140
+ source: (async function * () {
141
+ while (true) {
142
+ const val = await reader.read()
143
+ if (val.done === true) {
144
+ readerClosed = true
145
+ if (writerClosed) {
146
+ cleanupStreamFromActiveStreams()
147
+ }
148
+ return
149
+ }
150
+
151
+ yield new Uint8ArrayList(val.value)
152
+ }
153
+ })(),
154
+ sink: async function (source: Source<Uint8Array | Uint8ArrayList>) {
155
+ if (sinkSunk) {
156
+ throw new Error('sink already called on stream')
157
+ }
158
+ sinkSunk = true
159
+ try {
160
+ this.writeStatus = 'writing'
161
+
162
+ for await (const chunks of source) {
163
+ if (chunks instanceof Uint8Array) {
164
+ await writer.write(chunks)
165
+ } else {
166
+ for (const buf of chunks) {
167
+ await writer.write(buf)
168
+ }
169
+ }
170
+ }
171
+
172
+ this.writeStatus = 'done'
173
+ } finally {
174
+ this.timeline.closeWrite = Date.now()
175
+ this.writeStatus = 'closed'
176
+
177
+ await stream.closeWrite()
178
+ }
179
+ }
180
+ }
181
+
182
+ return stream
183
+ }
@@ -0,0 +1,21 @@
1
+ import type { Duplex, Source } from 'it-stream-types'
2
+
3
+ // Duplex that does nothing. Needed to fulfill the interface
4
+ export function inertDuplex (): Duplex<any, any, any> {
5
+ return {
6
+ source: {
7
+ [Symbol.asyncIterator] () {
8
+ return {
9
+ async next () {
10
+ // This will never resolve
11
+ return new Promise(() => { })
12
+ }
13
+ }
14
+ }
15
+ },
16
+ sink: async (source: Source<any>) => {
17
+ // This will never resolve
18
+ return new Promise(() => { })
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,12 @@
1
+ import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
2
+
3
+ /**
4
+ * Determines if `maybeSubset` is a subset of `set`. This means that all byte
5
+ * arrays in `maybeSubset` are present in `set`.
6
+ */
7
+ export function isSubset (set: Uint8Array[], maybeSubset: Uint8Array[]): boolean {
8
+ const intersection = maybeSubset.filter(byteArray => {
9
+ return Boolean(set.find((otherByteArray: Uint8Array) => uint8ArrayEquals(byteArray, otherByteArray)))
10
+ })
11
+ return (intersection.length === maybeSubset.length)
12
+ }