From e82385d4b97afcbba77a2d8bf29bbf1e314f0e50 Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Mon, 30 Nov 2020 16:43:51 +0100 Subject: [PATCH] feat: add types per jsdoc and types for testing interfaces --- package.json | 14 +- src/connection/connection.d.ts | 149 ---------------- src/connection/connection.js | 234 ------------------------- src/connection/index.d.ts | 231 +++++++++++++++++++++++- src/connection/index.js | 241 +++++++++++++++++++++++++- src/connection/status.d.ts | 6 +- src/content-routing/types.ts | 6 + src/crypto/types.ts | 0 src/peer-discovery/types.ts | 0 src/peer-routing/types.ts | 0 src/pubsub/errors.d.ts | 18 +- src/pubsub/index.d.ts | 109 +++++++----- src/pubsub/index.js | 75 +++++--- src/pubsub/message/sign.d.ts | 3 +- src/pubsub/message/sign.js | 3 +- src/pubsub/peer-streams.d.ts | 22 ++- src/pubsub/peer-streams.js | 9 +- src/pubsub/signature-policy.d.ts | 4 +- src/pubsub/utils.d.ts | 6 +- src/pubsub/utils.js | 7 +- src/record/index.d.ts | 7 +- src/record/index.js | 7 +- src/stream-muxer/tests/base-test.js | 5 +- src/stream-muxer/types.ts | 0 src/topology/index.d.ts | 69 +++++--- src/topology/index.js | 33 ++-- src/topology/multicodec-topology.d.ts | 35 ++-- src/topology/multicodec-topology.js | 21 +-- src/transport/tests/utils/index.js | 5 +- src/transport/types.ts | 103 +++++++++++ test/connection/compliance.spec.js | 1 + 31 files changed, 852 insertions(+), 571 deletions(-) delete mode 100644 src/connection/connection.d.ts delete mode 100644 src/connection/connection.js create mode 100644 src/content-routing/types.ts create mode 100644 src/crypto/types.ts create mode 100644 src/peer-discovery/types.ts create mode 100644 src/peer-routing/types.ts create mode 100644 src/stream-muxer/types.ts create mode 100644 src/transport/types.ts diff --git a/package.json b/package.json index f9678d9..62431ee 100644 --- a/package.json +++ b/package.json @@ -12,15 +12,15 @@ "scripts": { "lint": "aegir lint", "build": "aegir build", - "pregenerate:types": "rimraf './src/**/*.d.ts'", - "generate:types": "tsc", "test": "aegir test", "test:node": "aegir test --target node", "test:browser": "aegir test --target browser", + "test:types": "aegir ts -p check", "prepublishOnly": "npm run generate:types", "release": "aegir release -t node -t browser", "release-minor": "aegir release --type minor -t node -t browser", - "release-major": "aegir release --type major -t node -t browser" + "release-major": "aegir release --type major -t node -t browser", + "remove:types": "rimraf './src/**/*.d.ts'" }, "repository": { "type": "git", @@ -67,10 +67,12 @@ "uint8arrays": "^1.1.0" }, "devDependencies": { - "aegir": "^25.0.0", + "aegir": "^29.2.0", "it-handshake": "^1.0.1", - "rimraf": "^3.0.2", - "typescript": "3.7.5" + "rimraf": "^3.0.2" + }, + "eslintConfig": { + "extends": "ipfs" }, "contributors": [ "Alan Shaw ", diff --git a/src/connection/connection.d.ts b/src/connection/connection.d.ts deleted file mode 100644 index f74e296..0000000 --- a/src/connection/connection.d.ts +++ /dev/null @@ -1,149 +0,0 @@ -declare const _exports: typeof Connection; -export = _exports; -/** - * An implementation of the js-libp2p connection. - * Any libp2p transport should use an upgrader to return this connection. - */ -declare class Connection { - /** - * Creates an instance of Connection. - * @param {object} properties properties of the connection. - * @param {multiaddr} [properties.localAddr] local multiaddr of the connection if known. - * @param {multiaddr} [properties.remoteAddr] remote multiaddr of the connection. - * @param {PeerId} properties.localPeer local peer-id. - * @param {PeerId} properties.remotePeer remote peer-id. - * @param {function} properties.newStream new stream muxer function. - * @param {function} properties.close close raw connection function. - * @param {function(): Stream[]} properties.getStreams get streams from muxer function. - * @param {object} properties.stat metadata of the connection. - * @param {string} properties.stat.direction connection establishment direction ("inbound" or "outbound"). - * @param {object} properties.stat.timeline connection relevant events timestamp. - * @param {string} properties.stat.timeline.open connection opening timestamp. - * @param {string} properties.stat.timeline.upgraded connection upgraded timestamp. - * @param {string} [properties.stat.multiplexer] connection multiplexing identifier. - * @param {string} [properties.stat.encryption] connection encryption method identifier. - */ - constructor({ localAddr, remoteAddr, localPeer, remotePeer, newStream, close, getStreams, stat }: { - localAddr?: import("multiaddr"); - remoteAddr?: import("multiaddr"); - localPeer: import("peer-id"); - remotePeer: import("peer-id"); - newStream: Function; - close: Function; - getStreams: () => any[]; - stat: { - direction: string; - timeline: { - open: string; - upgraded: string; - }; - multiplexer?: string; - encryption?: string; - }; - }); - /** - * Connection identifier. - */ - id: any; - /** - * Observed multiaddr of the local peer - */ - localAddr: import("multiaddr"); - /** - * Observed multiaddr of the remote peer - */ - remoteAddr: import("multiaddr"); - /** - * Local peer id. - */ - localPeer: import("peer-id"); - /** - * Remote peer id. - */ - remotePeer: import("peer-id"); - /** - * Connection metadata. - */ - _stat: { - status: string; - direction: string; - timeline: { - open: string; - upgraded: string; - }; - multiplexer?: string; - encryption?: string; - }; - /** - * Reference to the new stream function of the multiplexer - */ - _newStream: Function; - /** - * Reference to the close function of the raw connection - */ - _close: Function; - /** - * Reference to the getStreams function of the muxer - */ - _getStreams: () => any[]; - /** - * Connection streams registry - */ - registry: Map; - /** - * User provided tags - * @type {string[]} - */ - tags: string[]; - /** - * Get connection metadata - * @this {Connection} - */ - get stat(): { - status: string; - direction: string; - timeline: { - open: string; - upgraded: string; - }; - multiplexer?: string; - encryption?: string; - }; - /** - * Get all the streams of the muxer. - * @this {Connection} - */ - get streams(): any[]; - /** - * Create a new stream from this connection - * @param {string[]} protocols intended protocol for the stream - * @return {Promise<{stream: Stream, protocol: string}>} with muxed+multistream-selected stream and selected protocol - */ - newStream(protocols: string[]): Promise<{ - stream: any; - protocol: string; - }>; - /** - * Add a stream when it is opened to the registry. - * @param {*} muxedStream a muxed stream - * @param {object} properties the stream properties to be registered - * @param {string} properties.protocol the protocol used by the stream - * @param {object} properties.metadata metadata of the stream - * @return {void} - */ - addStream(muxedStream: any, { protocol, metadata }: { - protocol: string; - metadata: any; - }): void; - /** - * Remove stream registry after it is closed. - * @param {string} id identifier of the stream - */ - removeStream(id: string): void; - /** - * Close the connection. - * @return {Promise} - */ - close(): Promise; - _closing: any; -} diff --git a/src/connection/connection.js b/src/connection/connection.js deleted file mode 100644 index d1ff248..0000000 --- a/src/connection/connection.js +++ /dev/null @@ -1,234 +0,0 @@ -'use strict' - -const PeerId = require('peer-id') -const multiaddr = require('multiaddr') -const withIs = require('class-is') -const errCode = require('err-code') -const Status = require('./status') - -function validateArgs (localAddr, localPeer, remotePeer, newStream, close, getStreams, stat) { - if (localAddr && !multiaddr.isMultiaddr(localAddr)) { - throw errCode(new Error('localAddr must be an instance of multiaddr'), 'ERR_INVALID_PARAMETERS') - } - - if (!PeerId.isPeerId(localPeer)) { - throw errCode(new Error('localPeer must be an instance of peer-id'), 'ERR_INVALID_PARAMETERS') - } - - if (!PeerId.isPeerId(remotePeer)) { - throw errCode(new Error('remotePeer must be an instance of peer-id'), 'ERR_INVALID_PARAMETERS') - } - - if (typeof newStream !== 'function') { - throw errCode(new Error('new stream must be a function'), 'ERR_INVALID_PARAMETERS') - } - - if (typeof close !== 'function') { - throw errCode(new Error('close must be a function'), 'ERR_INVALID_PARAMETERS') - } - - if (typeof getStreams !== 'function') { - throw errCode(new Error('getStreams must be a function'), 'ERR_INVALID_PARAMETERS') - } - - if (!stat) { - throw errCode(new Error('connection metadata object must be provided'), 'ERR_INVALID_PARAMETERS') - } - - if (stat.direction !== 'inbound' && stat.direction !== 'outbound') { - throw errCode(new Error('direction must be "inbound" or "outbound"'), 'ERR_INVALID_PARAMETERS') - } - - if (!stat.timeline) { - throw errCode(new Error('connection timeline object must be provided in the stat object'), 'ERR_INVALID_PARAMETERS') - } - - if (!stat.timeline.open) { - throw errCode(new Error('connection open timestamp must be provided'), 'ERR_INVALID_PARAMETERS') - } - - if (!stat.timeline.upgraded) { - throw errCode(new Error('connection upgraded timestamp must be provided'), 'ERR_INVALID_PARAMETERS') - } -} - -/** - * An implementation of the js-libp2p connection. - * Any libp2p transport should use an upgrader to return this connection. - */ -class Connection { - /** - * Creates an instance of Connection. - * @param {object} properties properties of the connection. - * @param {multiaddr} [properties.localAddr] local multiaddr of the connection if known. - * @param {multiaddr} [properties.remoteAddr] remote multiaddr of the connection. - * @param {PeerId} properties.localPeer local peer-id. - * @param {PeerId} properties.remotePeer remote peer-id. - * @param {function} properties.newStream new stream muxer function. - * @param {function} properties.close close raw connection function. - * @param {function(): Stream[]} properties.getStreams get streams from muxer function. - * @param {object} properties.stat metadata of the connection. - * @param {string} properties.stat.direction connection establishment direction ("inbound" or "outbound"). - * @param {object} properties.stat.timeline connection relevant events timestamp. - * @param {string} properties.stat.timeline.open connection opening timestamp. - * @param {string} properties.stat.timeline.upgraded connection upgraded timestamp. - * @param {string} [properties.stat.multiplexer] connection multiplexing identifier. - * @param {string} [properties.stat.encryption] connection encryption method identifier. - */ - constructor ({ localAddr, remoteAddr, localPeer, remotePeer, newStream, close, getStreams, stat }) { - validateArgs(localAddr, localPeer, remotePeer, newStream, close, getStreams, stat) - - /** - * Connection identifier. - */ - this.id = (parseInt(Math.random() * 1e9)).toString(36) + Date.now() - - /** - * Observed multiaddr of the local peer - */ - this.localAddr = localAddr - - /** - * Observed multiaddr of the remote peer - */ - this.remoteAddr = remoteAddr - - /** - * Local peer id. - */ - this.localPeer = localPeer - - /** - * Remote peer id. - */ - this.remotePeer = remotePeer - - /** - * Connection metadata. - */ - this._stat = { - ...stat, - status: Status.OPEN - } - - /** - * Reference to the new stream function of the multiplexer - */ - this._newStream = newStream - - /** - * Reference to the close function of the raw connection - */ - this._close = close - - /** - * Reference to the getStreams function of the muxer - */ - this._getStreams = getStreams - - /** - * Connection streams registry - */ - this.registry = new Map() - - /** - * User provided tags - * @type {string[]} - */ - this.tags = [] - } - - /** - * Get connection metadata - * @this {Connection} - */ - get stat () { - return this._stat - } - - /** - * Get all the streams of the muxer. - * @this {Connection} - */ - get streams () { - return this._getStreams() - } - - /** - * Create a new stream from this connection - * @param {string[]} protocols intended protocol for the stream - * @return {Promise<{stream: Stream, protocol: string}>} with muxed+multistream-selected stream and selected protocol - */ - async newStream (protocols) { - if (this.stat.status === Status.CLOSING) { - throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED') - } - - if (this.stat.status === Status.CLOSED) { - throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED') - } - - if (!Array.isArray(protocols)) protocols = [protocols] - - const { stream, protocol } = await this._newStream(protocols) - - this.addStream(stream, { protocol }) - - return { - stream, - protocol - } - } - - /** - * Add a stream when it is opened to the registry. - * @param {*} muxedStream a muxed stream - * @param {object} properties the stream properties to be registered - * @param {string} properties.protocol the protocol used by the stream - * @param {object} properties.metadata metadata of the stream - * @return {void} - */ - addStream (muxedStream, { protocol, metadata = {} }) { - // Add metadata for the stream - this.registry.set(muxedStream.id, { - protocol, - ...metadata - }) - } - - /** - * Remove stream registry after it is closed. - * @param {string} id identifier of the stream - */ - removeStream (id) { - this.registry.delete(id) - } - - /** - * Close the connection. - * @return {Promise} - */ - async close () { - if (this.stat.status === Status.CLOSED) { - return - } - - if (this._closing) { - return this._closing - } - - this.stat.status = Status.CLOSING - - // Close raw connection - this._closing = await this._close() - - this._stat.timeline.close = Date.now() - this.stat.status = Status.CLOSED - } -} - -/** - * @module - * @type {typeof Connection} - */ -module.exports = withIs(Connection, { className: 'Connection', symbolName: '@libp2p/interface-connection/connection' }) diff --git a/src/connection/index.d.ts b/src/connection/index.d.ts index 5dc4503..c07918e 100644 --- a/src/connection/index.d.ts +++ b/src/connection/index.d.ts @@ -1 +1,230 @@ -export var Connection: typeof import('./connection'); +export = Connection; +/** + * @typedef {Object} ConectionStat + * @property {string} direction - connection establishment direction ("inbound" or "outbound"). + * @property {object} timeline - connection relevant events timestamp. + * @property {string} timeline.open - connection opening timestamp. + * @property {string} timeline.upgraded - connection upgraded timestamp. + * @property {string} [multiplexer] - connection multiplexing identifier. + * @property {string} [encryption] - connection encryption method identifier. + * + * @typedef {Object} ConnectionOptions + * @property {multiaddr} [localAddr] - local multiaddr of the connection if known. + * @property {multiaddr} [remoteAddr] - remote multiaddr of the connection. + * @property {PeerId} localPeer - local peer-id. + * @property {PeerId} remotePeer - remote peer-id. + * @property {(protocols: string[]) => Promise<{stream: Stream, protocol: string}>} newStream - new stream muxer function. + * @property {() => Promise} close - close raw connection function. + * @property {() => Stream[]} getStreams - get streams from muxer function. + * @property {ConectionStat} stat - metadata of the connection. + */ +declare class Connection { + /** + * An implementation of the js-libp2p connection. + * Any libp2p transport should use an upgrader to return this connection. + * + * @class + * @param {ConnectionOptions} options + */ + constructor({ localAddr, remoteAddr, localPeer, remotePeer, newStream, close, getStreams, stat }: ConnectionOptions); + /** + * Connection identifier. + */ + id: string; + /** + * Observed multiaddr of the local peer + */ + localAddr: import("multiaddr"); + /** + * Observed multiaddr of the remote peer + */ + remoteAddr: import("multiaddr"); + /** + * Local peer id. + */ + localPeer: import("peer-id"); + /** + * Remote peer id. + */ + remotePeer: import("peer-id"); + /** + * Connection metadata. + */ + _stat: { + status: string; + /** + * - connection establishment direction ("inbound" or "outbound"). + */ + direction: string; + /** + * - connection relevant events timestamp. + */ + timeline: { + open: string; + upgraded: string; + }; + /** + * - connection multiplexing identifier. + */ + multiplexer?: string; + /** + * - connection encryption method identifier. + */ + encryption?: string; + }; + /** + * Reference to the new stream function of the multiplexer + */ + _newStream: (protocols: string[]) => Promise<{ + stream: any; + protocol: string; + }>; + /** + * Reference to the close function of the raw connection + */ + _close: () => Promise; + /** + * Reference to the getStreams function of the muxer + */ + _getStreams: () => any[]; + /** + * Connection streams registry + */ + registry: Map; + /** + * User provided tags + * + * @type {string[]} + */ + tags: string[]; + /** + * Get connection metadata + * + * @this {Connection} + */ + get stat(): { + status: string; + /** + * - connection establishment direction ("inbound" or "outbound"). + */ + direction: string; + /** + * - connection relevant events timestamp. + */ + timeline: { + open: string; + upgraded: string; + }; + /** + * - connection multiplexing identifier. + */ + multiplexer?: string; + /** + * - connection encryption method identifier. + */ + encryption?: string; + }; + /** + * Get all the streams of the muxer. + * + * @this {Connection} + */ + get streams(): any[]; + /** + * Create a new stream from this connection + * + * @param {string[]|string} protocols - intended protocol for the stream + * @returns {Promise<{stream: Stream, protocol: string}>} with muxed+multistream-selected stream and selected protocol + */ + newStream(protocols: string[] | string): Promise<{ + stream: any; + protocol: string; + }>; + /** + * Add a stream when it is opened to the registry. + * + * @param {*} muxedStream - a muxed stream + * @param {object} properties - the stream properties to be registered + * @param {string} properties.protocol - the protocol used by the stream + * @param {object} properties.metadata - metadata of the stream + * @returns {void} + */ + addStream(muxedStream: any, { protocol, metadata }: { + protocol: string; + metadata: object; + }): void; + /** + * Remove stream registry after it is closed. + * + * @param {string} id - identifier of the stream + */ + removeStream(id: string): void; + /** + * Close the connection. + * + * @returns {Promise} + */ + close(): Promise; + _closing: void; +} +declare namespace Connection { + export { ConectionStat, ConnectionOptions }; +} +type ConnectionOptions = { + /** + * - local multiaddr of the connection if known. + */ + localAddr?: import("multiaddr"); + /** + * - remote multiaddr of the connection. + */ + remoteAddr?: import("multiaddr"); + /** + * - local peer-id. + */ + localPeer: import("peer-id"); + /** + * - remote peer-id. + */ + remotePeer: import("peer-id"); + /** + * - new stream muxer function. + */ + newStream: (protocols: string[]) => Promise<{ + stream: any; + protocol: string; + }>; + /** + * - close raw connection function. + */ + close: () => Promise; + /** + * - get streams from muxer function. + */ + getStreams: () => any[]; + /** + * - metadata of the connection. + */ + stat: ConectionStat; +}; +type ConectionStat = { + /** + * - connection establishment direction ("inbound" or "outbound"). + */ + direction: string; + /** + * - connection relevant events timestamp. + */ + timeline: { + open: string; + upgraded: string; + }; + /** + * - connection multiplexing identifier. + */ + multiplexer?: string; + /** + * - connection encryption method identifier. + */ + encryption?: string; +}; diff --git a/src/connection/index.js b/src/connection/index.js index 38cd616..09088c8 100644 --- a/src/connection/index.js +++ b/src/connection/index.js @@ -1,7 +1,242 @@ 'use strict' +const PeerId = require('peer-id') +const multiaddr = require('multiaddr') +const withIs = require('class-is') +const errCode = require('err-code') +const Status = require('./status') + /** - * @module connection/index - * @type {typeof import('./connection')} + * @typedef {Object} ConectionStat + * @property {string} direction - connection establishment direction ("inbound" or "outbound"). + * @property {object} timeline - connection relevant events timestamp. + * @property {string} timeline.open - connection opening timestamp. + * @property {string} timeline.upgraded - connection upgraded timestamp. + * @property {string} [multiplexer] - connection multiplexing identifier. + * @property {string} [encryption] - connection encryption method identifier. + * + * @typedef {Object} ConnectionOptions + * @property {multiaddr} [localAddr] - local multiaddr of the connection if known. + * @property {multiaddr} [remoteAddr] - remote multiaddr of the connection. + * @property {PeerId} localPeer - local peer-id. + * @property {PeerId} remotePeer - remote peer-id. + * @property {(protocols: string[]) => Promise<{stream: Stream, protocol: string}>} newStream - new stream muxer function. + * @property {() => Promise} close - close raw connection function. + * @property {() => Stream[]} getStreams - get streams from muxer function. + * @property {ConectionStat} stat - metadata of the connection. */ -exports.Connection = require('./connection') + +class Connection { + /** + * An implementation of the js-libp2p connection. + * Any libp2p transport should use an upgrader to return this connection. + * + * @class + * @param {ConnectionOptions} options + */ + constructor ({ localAddr, remoteAddr, localPeer, remotePeer, newStream, close, getStreams, stat }) { + validateArgs(localAddr, localPeer, remotePeer, newStream, close, getStreams, stat) + + /** + * Connection identifier. + */ + this.id = (parseInt(Math.random() * 1e9)).toString(36) + Date.now() + + /** + * Observed multiaddr of the local peer + */ + this.localAddr = localAddr + + /** + * Observed multiaddr of the remote peer + */ + this.remoteAddr = remoteAddr + + /** + * Local peer id. + */ + this.localPeer = localPeer + + /** + * Remote peer id. + */ + this.remotePeer = remotePeer + + /** + * Connection metadata. + */ + this._stat = { + ...stat, + status: Status.OPEN + } + + /** + * Reference to the new stream function of the multiplexer + */ + this._newStream = newStream + + /** + * Reference to the close function of the raw connection + */ + this._close = close + + /** + * Reference to the getStreams function of the muxer + */ + this._getStreams = getStreams + + /** + * Connection streams registry + */ + this.registry = new Map() + + /** + * User provided tags + * + * @type {string[]} + */ + this.tags = [] + } + + /** + * Get connection metadata + * + * @this {Connection} + */ + get stat () { + return this._stat + } + + /** + * Get all the streams of the muxer. + * + * @this {Connection} + */ + get streams () { + return this._getStreams() + } + + /** + * Create a new stream from this connection + * + * @param {string[]|string} protocols - intended protocol for the stream + * @returns {Promise<{stream: Stream, protocol: string}>} with muxed+multistream-selected stream and selected protocol + */ + async newStream (protocols) { + if (this.stat.status === Status.CLOSING) { + throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED') + } + + if (this.stat.status === Status.CLOSED) { + throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED') + } + + if (!Array.isArray(protocols)) protocols = [protocols] + + const { stream, protocol } = await this._newStream(protocols) + + this.addStream(stream, { protocol }) + + return { + stream, + protocol + } + } + + /** + * Add a stream when it is opened to the registry. + * + * @param {*} muxedStream - a muxed stream + * @param {object} properties - the stream properties to be registered + * @param {string} properties.protocol - the protocol used by the stream + * @param {object} properties.metadata - metadata of the stream + * @returns {void} + */ + addStream (muxedStream, { protocol, metadata = {} }) { + // Add metadata for the stream + this.registry.set(muxedStream.id, { + protocol, + ...metadata + }) + } + + /** + * Remove stream registry after it is closed. + * + * @param {string} id - identifier of the stream + */ + removeStream (id) { + this.registry.delete(id) + } + + /** + * Close the connection. + * + * @returns {Promise} + */ + async close () { + if (this.stat.status === Status.CLOSED) { + return + } + + if (this._closing) { + return this._closing + } + + this.stat.status = Status.CLOSING + + // Close raw connection + this._closing = await this._close() + + this._stat.timeline.close = Date.now() + this.stat.status = Status.CLOSED + } +} + +module.exports = Connection + +function validateArgs (localAddr, localPeer, remotePeer, newStream, close, getStreams, stat) { + if (localAddr && !multiaddr.isMultiaddr(localAddr)) { + throw errCode(new Error('localAddr must be an instance of multiaddr'), 'ERR_INVALID_PARAMETERS') + } + + if (!PeerId.isPeerId(localPeer)) { + throw errCode(new Error('localPeer must be an instance of peer-id'), 'ERR_INVALID_PARAMETERS') + } + + if (!PeerId.isPeerId(remotePeer)) { + throw errCode(new Error('remotePeer must be an instance of peer-id'), 'ERR_INVALID_PARAMETERS') + } + + if (typeof newStream !== 'function') { + throw errCode(new Error('new stream must be a function'), 'ERR_INVALID_PARAMETERS') + } + + if (typeof close !== 'function') { + throw errCode(new Error('close must be a function'), 'ERR_INVALID_PARAMETERS') + } + + if (typeof getStreams !== 'function') { + throw errCode(new Error('getStreams must be a function'), 'ERR_INVALID_PARAMETERS') + } + + if (!stat) { + throw errCode(new Error('connection metadata object must be provided'), 'ERR_INVALID_PARAMETERS') + } + + if (stat.direction !== 'inbound' && stat.direction !== 'outbound') { + throw errCode(new Error('direction must be "inbound" or "outbound"'), 'ERR_INVALID_PARAMETERS') + } + + if (!stat.timeline) { + throw errCode(new Error('connection timeline object must be provided in the stat object'), 'ERR_INVALID_PARAMETERS') + } + + if (!stat.timeline.open) { + throw errCode(new Error('connection open timestamp must be provided'), 'ERR_INVALID_PARAMETERS') + } + + if (!stat.timeline.upgraded) { + throw errCode(new Error('connection upgraded timestamp must be provided'), 'ERR_INVALID_PARAMETERS') + } +} diff --git a/src/connection/status.d.ts b/src/connection/status.d.ts index fc476fa..ffd1d75 100644 --- a/src/connection/status.d.ts +++ b/src/connection/status.d.ts @@ -1,3 +1,3 @@ -export declare const OPEN: string; -export declare const CLOSING: string; -export declare const CLOSED: string; +export const OPEN: string; +export const CLOSING: string; +export const CLOSED: string; diff --git a/src/content-routing/types.ts b/src/content-routing/types.ts new file mode 100644 index 0000000..aa88927 --- /dev/null +++ b/src/content-routing/types.ts @@ -0,0 +1,6 @@ +export = ContentRouting; + +declare class ContentRouting { + findProviders(cid); + provide(cid); +} diff --git a/src/crypto/types.ts b/src/crypto/types.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/peer-discovery/types.ts b/src/peer-discovery/types.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/peer-routing/types.ts b/src/peer-routing/types.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/pubsub/errors.d.ts b/src/pubsub/errors.d.ts index 4bbf5b3..b5349d1 100644 --- a/src/pubsub/errors.d.ts +++ b/src/pubsub/errors.d.ts @@ -1,11 +1,11 @@ export namespace codes { - export const ERR_INVALID_SIGNATURE_POLICY: string; - export const ERR_UNHANDLED_SIGNATURE_POLICY: string; - export const ERR_MISSING_SIGNATURE: string; - export const ERR_MISSING_SEQNO: string; - export const ERR_INVALID_SIGNATURE: string; - export const ERR_UNEXPECTED_FROM: string; - export const ERR_UNEXPECTED_SIGNATURE: string; - export const ERR_UNEXPECTED_KEY: string; - export const ERR_UNEXPECTED_SEQNO: string; + const ERR_INVALID_SIGNATURE_POLICY: string; + const ERR_UNHANDLED_SIGNATURE_POLICY: string; + const ERR_MISSING_SIGNATURE: string; + const ERR_MISSING_SEQNO: string; + const ERR_INVALID_SIGNATURE: string; + const ERR_UNEXPECTED_FROM: string; + const ERR_UNEXPECTED_SIGNATURE: string; + const ERR_UNEXPECTED_KEY: string; + const ERR_UNEXPECTED_SEQNO: string; } diff --git a/src/pubsub/index.d.ts b/src/pubsub/index.d.ts index f2a8d1c..a8a05d3 100644 --- a/src/pubsub/index.d.ts +++ b/src/pubsub/index.d.ts @@ -13,27 +13,27 @@ export = PubsubBaseProtocol; * @type import('peer-id') */ /** -* PubsubBaseProtocol handles the peers and connections logic for pubsub routers -* and specifies the API that pubsub routers should have. -*/ + * PubsubBaseProtocol handles the peers and connections logic for pubsub routers + * and specifies the API that pubsub routers should have. + */ declare class PubsubBaseProtocol { /** * @param {Object} props - * @param {String} props.debugName log namespace - * @param {Array|string} props.multicodecs protocol identificers to connect + * @param {string} props.debugName - log namespace + * @param {Array|string} props.multicodecs - protocol identificers to connect * @param {Libp2p} props.libp2p - * @param {SignaturePolicy} [props.globalSignaturePolicy = SignaturePolicy.StrictSign] defines how signatures should be handled - * @param {boolean} [props.canRelayMessage = false] if can relay messages not subscribed - * @param {boolean} [props.emitSelf = false] if publish should emit to self, if subscribed + * @param {SignaturePolicy} [props.globalSignaturePolicy = SignaturePolicy.StrictSign] - defines how signatures should be handled + * @param {boolean} [props.canRelayMessage = false] - if can relay messages not subscribed + * @param {boolean} [props.emitSelf = false] - if publish should emit to self, if subscribed * @abstract */ constructor({ debugName, multicodecs, libp2p, globalSignaturePolicy, canRelayMessage, emitSelf }: { debugName: string; - multicodecs: string | string[]; + multicodecs: Array | string; libp2p: any; - globalSignaturePolicy?: any; - canRelayMessage?: boolean; - emitSelf?: boolean; + globalSignaturePolicy: any; + canRelayMessage: boolean; + emitSelf: boolean; }); log: any; /** @@ -55,6 +55,7 @@ declare class PubsubBaseProtocol { topics: Map>; /** * List of our subscriptions + * * @type {Set} */ subscriptions: Set; @@ -72,16 +73,19 @@ declare class PubsubBaseProtocol { globalSignaturePolicy: string; /** * If router can relay received messages, even if not subscribed + * * @type {boolean} */ canRelayMessage: boolean; /** * if publish should emit to self, if subscribed + * * @type {boolean} */ emitSelf: boolean; /** * Topic validator function + * * @typedef {function(string, InMessage): Promise} validator */ /** @@ -89,73 +93,79 @@ declare class PubsubBaseProtocol { * * Keyed by topic * Topic validators are functions with the following input: + * * @type {Map} */ - topicValidators: Map; + topicValidators: Map Promise>; _registrarId: any; /** * On an inbound stream opened. + * * @private * @param {Object} props * @param {string} props.protocol * @param {DuplexIterableStream} props.stream - * @param {Connection} props.connection connection + * @param {Connection} props.connection - connection */ - _onIncomingStream({ protocol, stream, connection }: { - protocol: string; - stream: any; - connection: any; - }): void; + private _onIncomingStream; /** * Registrar notifies an established connection with pubsub protocol. + * * @private - * @param {PeerId} peerId remote peer-id - * @param {Connection} conn connection to the peer + * @param {PeerId} peerId - remote peer-id + * @param {Connection} conn - connection to the peer */ - _onPeerConnected(peerId: import("peer-id"), conn: any): Promise; + private _onPeerConnected; /** * Registrar notifies a closing connection with pubsub protocol. + * * @private - * @param {PeerId} peerId peerId - * @param {Error} err error for connection end + * @param {PeerId} peerId - peerId + * @param {Error} err - error for connection end */ - _onPeerDisconnected(peerId: import("peer-id"), err: Error): void; + private _onPeerDisconnected; /** * Register the pubsub protocol onto the libp2p node. + * * @returns {void} */ start(): void; /** * Unregister the pubsub protocol and the streams with other peers will be closed. + * * @returns {void} */ stop(): void; /** * Notifies the router that a peer has been connected + * * @private * @param {PeerId} peerId * @param {string} protocol * @returns {PeerStreams} */ - _addPeer(peerId: import("peer-id"), protocol: string): import("./peer-streams"); + private _addPeer; /** * Notifies the router that a peer has been disconnected. + * * @private * @param {PeerId} peerId * @returns {PeerStreams | undefined} */ - _removePeer(peerId: import("peer-id")): import("./peer-streams"); + private _removePeer; /** * Responsible for processing each RPC message received by other peers. - * @param {string} idB58Str peer id string in base58 - * @param {DuplexIterableStream} stream inbound stream - * @param {PeerStreams} peerStreams PubSub peer + * + * @param {string} idB58Str - peer id string in base58 + * @param {DuplexIterableStream} stream - inbound stream + * @param {PeerStreams} peerStreams - PubSub peer * @returns {Promise} */ _processMessages(idB58Str: string, stream: any, peerStreams: import("./peer-streams")): Promise; /** * Handles an rpc request from a peer - * @param {String} idB58Str + * + * @param {string} idB58Str * @param {PeerStreams} peerStreams * @param {RPC} rpc * @returns {boolean} @@ -163,31 +173,36 @@ declare class PubsubBaseProtocol { _processRpc(idB58Str: string, peerStreams: import("./peer-streams"), rpc: any): boolean; /** * Handles a subscription change from a peer + * * @param {string} id * @param {RPC.SubOpt} subOpt */ _processRpcSubOpt(id: string, subOpt: any): void; /** * Handles an message from a peer + * * @param {InMessage} msg * @returns {Promise} */ _processRpcMessage(msg: InMessage): Promise; /** * Emit a message from a peer + * * @param {InMessage} message */ _emitMessage(message: InMessage): void; /** * The default msgID implementation * Child class can override this. - * @param {RPC.Message} msg the message object + * + * @param {RPC.Message} msg - the message object * @returns {Uint8Array} message id as bytes */ getMsgId(msg: any): Uint8Array; /** * Whether to accept a message from a peer * Override to create a graylist + * * @override * @param {string} id * @returns {boolean} @@ -196,6 +211,7 @@ declare class PubsubBaseProtocol { /** * Decode Uint8Array into an RPC object. * This can be override to use a custom router protobuf. + * * @param {Uint8Array} bytes * @returns {RPC} */ @@ -203,28 +219,32 @@ declare class PubsubBaseProtocol { /** * Encode RPC object into a Uint8Array. * This can be override to use a custom router protobuf. + * * @param {RPC} rpc * @returns {Uint8Array} */ _encodeRpc(rpc: any): Uint8Array; /** * Send an rpc object to a peer - * @param {string} id peer id + * + * @param {string} id - peer id * @param {RPC} rpc * @returns {void} */ _sendRpc(id: string, rpc: any): void; /** * Send subscroptions to a peer - * @param {string} id peer id + * + * @param {string} id - peer id * @param {string[]} topics - * @param {boolean} subscribe set to false for unsubscriptions + * @param {boolean} subscribe - set to false for unsubscriptions * @returns {void} */ _sendSubscriptions(id: string, topics: string[], subscribe: boolean): void; /** * Validates the given message. The signature will be checked for authenticity. * Throws an error on invalid messages + * * @param {InMessage} message * @returns {Promise} */ @@ -232,19 +252,22 @@ declare class PubsubBaseProtocol { /** * Normalizes the message and signs it, if signing is enabled. * Should be used by the routers to create the message to send. + * * @private * @param {Message} message * @returns {Promise} */ - _buildMessage(message: any): Promise; + private _buildMessage; /** * Get a list of the peer-ids that are subscribed to one topic. + * * @param {string} topic * @returns {Array} */ - getSubscribers(topic: string): string[]; + getSubscribers(topic: string): Array; /** * Publishes messages to all subscribed peers + * * @override * @param {string} topic * @param {Buffer} message @@ -254,6 +277,7 @@ declare class PubsubBaseProtocol { /** * Overriding the implementation of publish should handle the appropriate algorithms for the publish/subscriber implementation. * For example, a Floodsub implementation might simply publish each message to each topic for every peer + * * @abstract * @param {InMessage} message * @returns {Promise} @@ -262,6 +286,7 @@ declare class PubsubBaseProtocol { _publish(message: InMessage): Promise; /** * Subscribes to a given topic. + * * @abstract * @param {string} topic * @returns {void} @@ -269,6 +294,7 @@ declare class PubsubBaseProtocol { subscribe(topic: string): void; /** * Unsubscribe from the given topic. + * * @override * @param {string} topic * @returns {void} @@ -276,19 +302,16 @@ declare class PubsubBaseProtocol { unsubscribe(topic: string): void; /** * Get the list of topics which the peer is subscribed to. + * * @override - * @returns {Array} + * @returns {Array} */ - getTopics(): string[]; + getTopics(): Array; } declare namespace PubsubBaseProtocol { export { message, utils, SignaturePolicy, InMessage, PeerId }; } type PeerId = import("peer-id"); -/** - * Topic validator function - */ -type validator = (arg0: string, arg1: InMessage) => Promise; type InMessage = { from?: string; receivedFrom: string; diff --git a/src/pubsub/index.js b/src/pubsub/index.js index 6761959..fa20825 100644 --- a/src/pubsub/index.js +++ b/src/pubsub/index.js @@ -36,18 +36,18 @@ const { */ /** -* PubsubBaseProtocol handles the peers and connections logic for pubsub routers -* and specifies the API that pubsub routers should have. -*/ + * PubsubBaseProtocol handles the peers and connections logic for pubsub routers + * and specifies the API that pubsub routers should have. + */ class PubsubBaseProtocol extends EventEmitter { /** * @param {Object} props - * @param {String} props.debugName log namespace - * @param {Array|string} props.multicodecs protocol identificers to connect + * @param {string} props.debugName - log namespace + * @param {Array|string} props.multicodecs - protocol identificers to connect * @param {Libp2p} props.libp2p - * @param {SignaturePolicy} [props.globalSignaturePolicy = SignaturePolicy.StrictSign] defines how signatures should be handled - * @param {boolean} [props.canRelayMessage = false] if can relay messages not subscribed - * @param {boolean} [props.emitSelf = false] if publish should emit to self, if subscribed + * @param {SignaturePolicy} [props.globalSignaturePolicy = SignaturePolicy.StrictSign] - defines how signatures should be handled + * @param {boolean} [props.canRelayMessage = false] - if can relay messages not subscribed + * @param {boolean} [props.emitSelf = false] - if publish should emit to self, if subscribed * @abstract */ constructor ({ @@ -97,6 +97,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * List of our subscriptions + * * @type {Set} */ this.subscriptions = new Set() @@ -122,18 +123,21 @@ class PubsubBaseProtocol extends EventEmitter { /** * If router can relay received messages, even if not subscribed + * * @type {boolean} */ this.canRelayMessage = canRelayMessage /** * if publish should emit to self, if subscribed + * * @type {boolean} */ this.emitSelf = emitSelf /** * Topic validator function + * * @typedef {function(string, InMessage): Promise} validator */ /** @@ -141,6 +145,7 @@ class PubsubBaseProtocol extends EventEmitter { * * Keyed by topic * Topic validators are functions with the following input: + * * @type {Map} */ this.topicValidators = new Map() @@ -155,6 +160,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Register the pubsub protocol onto the libp2p node. + * * @returns {void} */ start () { @@ -184,6 +190,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Unregister the pubsub protocol and the streams with other peers will be closed. + * * @returns {void} */ stop () { @@ -205,11 +212,12 @@ class PubsubBaseProtocol extends EventEmitter { /** * On an inbound stream opened. + * * @private * @param {Object} props * @param {string} props.protocol * @param {DuplexIterableStream} props.stream - * @param {Connection} props.connection connection + * @param {Connection} props.connection - connection */ _onIncomingStream ({ protocol, stream, connection }) { const peerId = connection.remotePeer @@ -222,9 +230,10 @@ class PubsubBaseProtocol extends EventEmitter { /** * Registrar notifies an established connection with pubsub protocol. + * * @private - * @param {PeerId} peerId remote peer-id - * @param {Connection} conn connection to the peer + * @param {PeerId} peerId - remote peer-id + * @param {Connection} conn - connection to the peer */ async _onPeerConnected (peerId, conn) { const idB58Str = peerId.toB58String() @@ -244,9 +253,10 @@ class PubsubBaseProtocol extends EventEmitter { /** * Registrar notifies a closing connection with pubsub protocol. + * * @private - * @param {PeerId} peerId peerId - * @param {Error} err error for connection end + * @param {PeerId} peerId - peerId + * @param {Error} err - error for connection end */ _onPeerDisconnected (peerId, err) { const idB58Str = peerId.toB58String() @@ -257,6 +267,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Notifies the router that a peer has been connected + * * @private * @param {PeerId} peerId * @param {string} protocol @@ -287,6 +298,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Notifies the router that a peer has been disconnected. + * * @private * @param {PeerId} peerId * @returns {PeerStreams | undefined} @@ -317,9 +329,10 @@ class PubsubBaseProtocol extends EventEmitter { /** * Responsible for processing each RPC message received by other peers. - * @param {string} idB58Str peer id string in base58 - * @param {DuplexIterableStream} stream inbound stream - * @param {PeerStreams} peerStreams PubSub peer + * + * @param {string} idB58Str - peer id string in base58 + * @param {DuplexIterableStream} stream - inbound stream + * @param {PeerStreams} peerStreams - PubSub peer * @returns {Promise} */ async _processMessages (idB58Str, stream, peerStreams) { @@ -342,7 +355,8 @@ class PubsubBaseProtocol extends EventEmitter { /** * Handles an rpc request from a peer - * @param {String} idB58Str + * + * @param {string} idB58Str * @param {PeerStreams} peerStreams * @param {RPC} rpc * @returns {boolean} @@ -378,6 +392,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Handles a subscription change from a peer + * * @param {string} id * @param {RPC.SubOpt} subOpt */ @@ -401,6 +416,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Handles an message from a peer + * * @param {InMessage} msg * @returns {Promise} */ @@ -425,6 +441,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Emit a message from a peer + * * @param {InMessage} message */ _emitMessage (message) { @@ -438,7 +455,8 @@ class PubsubBaseProtocol extends EventEmitter { /** * The default msgID implementation * Child class can override this. - * @param {RPC.Message} msg the message object + * + * @param {RPC.Message} msg - the message object * @returns {Uint8Array} message id as bytes */ getMsgId (msg) { @@ -456,6 +474,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Whether to accept a message from a peer * Override to create a graylist + * * @override * @param {string} id * @returns {boolean} @@ -467,6 +486,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Decode Uint8Array into an RPC object. * This can be override to use a custom router protobuf. + * * @param {Uint8Array} bytes * @returns {RPC} */ @@ -477,6 +497,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Encode RPC object into a Uint8Array. * This can be override to use a custom router protobuf. + * * @param {RPC} rpc * @returns {Uint8Array} */ @@ -486,7 +507,8 @@ class PubsubBaseProtocol extends EventEmitter { /** * Send an rpc object to a peer - * @param {string} id peer id + * + * @param {string} id - peer id * @param {RPC} rpc * @returns {void} */ @@ -503,9 +525,10 @@ class PubsubBaseProtocol extends EventEmitter { /** * Send subscroptions to a peer - * @param {string} id peer id + * + * @param {string} id - peer id * @param {string[]} topics - * @param {boolean} subscribe set to false for unsubscriptions + * @param {boolean} subscribe - set to false for unsubscriptions * @returns {void} */ _sendSubscriptions (id, topics, subscribe) { @@ -517,6 +540,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Validates the given message. The signature will be checked for authenticity. * Throws an error on invalid messages + * * @param {InMessage} message * @returns {Promise} */ @@ -563,6 +587,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Normalizes the message and signs it, if signing is enabled. * Should be used by the routers to create the message to send. + * * @private * @param {Message} message * @returns {Promise} @@ -585,6 +610,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Get a list of the peer-ids that are subscribed to one topic. + * * @param {string} topic * @returns {Array} */ @@ -606,6 +632,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Publishes messages to all subscribed peers + * * @override * @param {string} topic * @param {Buffer} message @@ -639,6 +666,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Overriding the implementation of publish should handle the appropriate algorithms for the publish/subscriber implementation. * For example, a Floodsub implementation might simply publish each message to each topic for every peer + * * @abstract * @param {InMessage} message * @returns {Promise} @@ -650,6 +678,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Subscribes to a given topic. + * * @abstract * @param {string} topic * @returns {void} @@ -667,6 +696,7 @@ class PubsubBaseProtocol extends EventEmitter { /** * Unsubscribe from the given topic. + * * @override * @param {string} topic * @returns {void} @@ -684,8 +714,9 @@ class PubsubBaseProtocol extends EventEmitter { /** * Get the list of topics which the peer is subscribed to. + * * @override - * @returns {Array} + * @returns {Array} */ getTopics () { if (!this.started) { diff --git a/src/pubsub/message/sign.d.ts b/src/pubsub/message/sign.d.ts index 3e1bee2..cdecc35 100644 --- a/src/pubsub/message/sign.d.ts +++ b/src/pubsub/message/sign.d.ts @@ -17,7 +17,8 @@ export function signMessage(peerId: import("peer-id"), message: any): Promise} + * @returns {Promise} */ export function verifySignature(message: any): Promise; diff --git a/src/pubsub/message/sign.js b/src/pubsub/message/sign.js index dbb2392..f6be3db 100644 --- a/src/pubsub/message/sign.js +++ b/src/pubsub/message/sign.js @@ -31,8 +31,9 @@ async function signMessage (peerId, message) { /** * Verifies the signature of the given message + * * @param {InMessage} message - * @returns {Promise} + * @returns {Promise} */ async function verifySignature (message) { // Get message sans the signature diff --git a/src/pubsub/peer-streams.d.ts b/src/pubsub/peer-streams.d.ts index 632fe2c..9f8d9cc 100644 --- a/src/pubsub/peer-streams.d.ts +++ b/src/pubsub/peer-streams.d.ts @@ -16,12 +16,12 @@ export = PeerStreams; */ declare class PeerStreams { /** - * @param {object} properties properties of the PeerStreams. + * @param {object} properties - properties of the PeerStreams. * @param {PeerId} properties.id * @param {string} properties.protocol */ constructor({ id, protocol }: { - id: import("peer-id"); + id: PeerId; protocol: string; }); /** @@ -30,34 +30,40 @@ declare class PeerStreams { id: import('peer-id'); /** * Established protocol + * * @type {string} */ protocol: string; /** * The raw outbound stream, as retrieved from conn.newStream + * * @private * @type {DuplexIterableStream} */ - _rawOutboundStream: DuplexIterableStream; + private _rawOutboundStream; /** * The raw inbound stream, as retrieved from the callback from libp2p.handle + * * @private * @type {DuplexIterableStream} */ - _rawInboundStream: DuplexIterableStream; + private _rawInboundStream; /** * An AbortController for controlled shutdown of the inbound stream + * * @private * @type {typeof AbortController} */ - _inboundAbortController: typeof AbortController; + private _inboundAbortController; /** * Write stream -- its preferable to use the write method + * * @type {import('it-pushable').Pushable>} */ outboundStream: import('it-pushable').Pushable; /** * Read stream + * * @type {DuplexIterableStream} */ inboundStream: DuplexIterableStream; @@ -97,6 +103,7 @@ declare class PeerStreams { attachOutboundStream(stream: any): Promise; /** * Closes the open connection to peer + * * @returns {void} */ close(): void; @@ -106,8 +113,7 @@ declare namespace PeerStreams { } type DuplexIterableStream = { sink: Sink; - source: () => AsyncIterator; + source: () => AsyncIterator; }; -declare const AbortController: typeof import("abort-controller"); -type Sink = (source: Uint8Array) => Promise; type PeerId = import("peer-id"); +type Sink = (source: Uint8Array) => Promise; diff --git a/src/pubsub/peer-streams.js b/src/pubsub/peer-streams.js index a41e1d8..1f908bd 100644 --- a/src/pubsub/peer-streams.js +++ b/src/pubsub/peer-streams.js @@ -30,7 +30,7 @@ log.error = debug('libp2p-pubsub:peer-streams:error') */ class PeerStreams extends EventEmitter { /** - * @param {object} properties properties of the PeerStreams. + * @param {object} properties - properties of the PeerStreams. * @param {PeerId} properties.id * @param {string} properties.protocol */ @@ -43,34 +43,40 @@ class PeerStreams extends EventEmitter { this.id = id /** * Established protocol + * * @type {string} */ this.protocol = protocol /** * The raw outbound stream, as retrieved from conn.newStream + * * @private * @type {DuplexIterableStream} */ this._rawOutboundStream = null /** * The raw inbound stream, as retrieved from the callback from libp2p.handle + * * @private * @type {DuplexIterableStream} */ this._rawInboundStream = null /** * An AbortController for controlled shutdown of the inbound stream + * * @private * @type {typeof AbortController} */ this._inboundAbortController = null /** * Write stream -- its preferable to use the write method + * * @type {import('it-pushable').Pushable>} */ this.outboundStream = null /** * Read stream + * * @type {DuplexIterableStream} */ this.inboundStream = null @@ -179,6 +185,7 @@ class PeerStreams extends EventEmitter { /** * Closes the open connection to peer + * * @returns {void} */ close () { diff --git a/src/pubsub/signature-policy.d.ts b/src/pubsub/signature-policy.d.ts index cf04e15..e61bb6f 100644 --- a/src/pubsub/signature-policy.d.ts +++ b/src/pubsub/signature-policy.d.ts @@ -1,4 +1,4 @@ export namespace SignaturePolicy { - export const StrictSign: string; - export const StrictNoSign: string; + const StrictSign: string; + const StrictNoSign: string; } diff --git a/src/pubsub/utils.d.ts b/src/pubsub/utils.d.ts index f0ae093..9906f49 100644 --- a/src/pubsub/utils.d.ts +++ b/src/pubsub/utils.d.ts @@ -1,7 +1,7 @@ export function randomSeqno(): Uint8Array; export function msgId(from: string, seqno: Uint8Array): Uint8Array; export function noSignMsgId(data: Uint8Array): Uint8Array; -export function anyMatch(a: any[] | Set, b: any[] | Set): boolean; +export function anyMatch(a: Set | any[], b: Set | any[]): boolean; export function ensureArray(maybeArray: any): any[]; -export function normalizeInRpcMessage(message: any, peerId: string): any; -export function normalizeOutRpcMessage(message: any): any; +export function normalizeInRpcMessage(message: object, peerId: string): object; +export function normalizeOutRpcMessage(message: object): object; diff --git a/src/pubsub/utils.js b/src/pubsub/utils.js index eab7168..29c9e3c 100644 --- a/src/pubsub/utils.js +++ b/src/pubsub/utils.js @@ -85,9 +85,10 @@ exports.ensureArray = (maybeArray) => { /** * Ensures `message.from` is base58 encoded + * * @param {object} message - * @param {String} peerId - * @return {object} + * @param {string} peerId + * @returns {object} */ exports.normalizeInRpcMessage = (message, peerId) => { const m = Object.assign({}, message) @@ -102,7 +103,7 @@ exports.normalizeInRpcMessage = (message, peerId) => { /** * @param {object} message - * @return {object} + * @returns {object} */ exports.normalizeOutRpcMessage = (message) => { const m = Object.assign({}, message) diff --git a/src/record/index.d.ts b/src/record/index.d.ts index 53007cb..33068ca 100644 --- a/src/record/index.d.ts +++ b/src/record/index.d.ts @@ -4,9 +4,9 @@ export = Record; */ declare class Record { /** - * @constructor - * @param {String} domain signature domain - * @param {Uint8Array} codec identifier of the type of record + * @class + * @param {string} domain - signature domain + * @param {Uint8Array} codec - identifier of the type of record */ constructor(domain: string, codec: Uint8Array); domain: string; @@ -17,6 +17,7 @@ declare class Record { marshal(): void; /** * Verifies if the other provided Record is identical to this one. + * * @param {Record} other */ equals(other: Record): void; diff --git a/src/record/index.js b/src/record/index.js index a49adf8..11a4edb 100644 --- a/src/record/index.js +++ b/src/record/index.js @@ -7,9 +7,9 @@ const errcode = require('err-code') */ class Record { /** - * @constructor - * @param {String} domain signature domain - * @param {Uint8Array} codec identifier of the type of record + * @class + * @param {string} domain - signature domain + * @param {Uint8Array} codec - identifier of the type of record */ constructor (domain, codec) { this.domain = domain @@ -25,6 +25,7 @@ class Record { /** * Verifies if the other provided Record is identical to this one. + * * @param {Record} other */ equals (other) { diff --git a/src/stream-muxer/tests/base-test.js b/src/stream-muxer/tests/base-test.js index f74a64a..11c1c78 100644 --- a/src/stream-muxer/tests/base-test.js +++ b/src/stream-muxer/tests/base-test.js @@ -20,8 +20,9 @@ async function closeAndWait (stream) { /** * A tick is considered valid if it happened between now * and `ms` milliseconds ago - * @param {number} date Time in ticks - * @param {number} ms max milliseconds that should have expired + * + * @param {number} date - Time in ticks + * @param {number} ms - max milliseconds that should have expired * @returns {boolean} */ function isValidTick (date, ms = 5000) { diff --git a/src/stream-muxer/types.ts b/src/stream-muxer/types.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/topology/index.d.ts b/src/topology/index.d.ts index d2e1141..3b6f370 100644 --- a/src/topology/index.d.ts +++ b/src/topology/index.d.ts @@ -1,42 +1,63 @@ declare const _exports: Topology; export = _exports; +export type PeerId = import("peer-id"); +export type TopologyHandlers = { + /** + * - protocol "onConnect" handler + */ + onConnect?: (peerId: PeerId, conn: import('../connection')) => void; + /** + * - protocol "onDisconnect" handler + */ + onDisconnect?: (peerId: PeerId) => void; +}; +export type TopologyOptions = { + /** + * - minimum needed connections + */ + min?: number; + /** + * - maximum needed connections + */ + max?: number; + handlers?: TopologyHandlers; +}; +/** + * @typedef {import('peer-id')} PeerId + */ +/** + * @typedef {Object} TopologyHandlers + * @property {(peerId: PeerId, conn: import('../connection')) => void} [handlers.onConnect] - protocol "onConnect" handler + * @property {(peerId: PeerId) => void} [handlers.onDisconnect] - protocol "onDisconnect" handler + * + * @typedef {Object} TopologyOptions + * @property {number} [props.min = 0] - minimum needed connections + * @property {number} [props.max = Infinity] - maximum needed connections + * @property {TopologyHandlers} [props.handlers] + */ declare class Topology { /** - * @param {Object} props - * @param {number} props.min minimum needed connections (default: 0) - * @param {number} props.max maximum needed connections (default: Infinity) - * @param {Object} [props.handlers] - * @param {function} [props.handlers.onConnect] protocol "onConnect" handler - * @param {function} [props.handlers.onDisconnect] protocol "onDisconnect" handler - * @constructor + * @class + * @param {TopologyHandlers} options */ - constructor({ min, max, handlers }: { - min: number; - max: number; - handlers?: { - onConnect?: Function; - onDisconnect?: Function; - }; - }); - min: number; - max: number; - _onConnect: Function; - _onDisconnect: Function; + constructor({ min, max, handlers }: TopologyHandlers); + min: any; + max: any; + _onConnect: any; + _onDisconnect: any; /** * Set of peers that support the protocol. + * * @type {Set} */ peers: Set; set registrar(arg: any); _registrar: any; - /** - * @typedef PeerId - * @type {import('peer-id')} - */ /** * Notify about peer disconnected event. + * * @param {PeerId} peerId * @returns {void} */ - disconnect(peerId: import("peer-id")): void; + disconnect(peerId: PeerId): void; } diff --git a/src/topology/index.js b/src/topology/index.js index 77af929..d34ff79 100644 --- a/src/topology/index.js +++ b/src/topology/index.js @@ -3,15 +3,25 @@ const withIs = require('class-is') const noop = () => {} +/** + * @typedef {import('peer-id')} PeerId + */ + +/** + * @typedef {Object} TopologyHandlers + * @property {(peerId: PeerId, conn: import('../connection')) => void} [handlers.onConnect] - protocol "onConnect" handler + * @property {(peerId: PeerId) => void} [handlers.onDisconnect] - protocol "onDisconnect" handler + * + * @typedef {Object} TopologyOptions + * @property {number} [props.min = 0] - minimum needed connections + * @property {number} [props.max = Infinity] - maximum needed connections + * @property {TopologyHandlers} [props.handlers] + */ + class Topology { /** - * @param {Object} props - * @param {number} props.min minimum needed connections (default: 0) - * @param {number} props.max maximum needed connections (default: Infinity) - * @param {Object} [props.handlers] - * @param {function} [props.handlers.onConnect] protocol "onConnect" handler - * @param {function} [props.handlers.onDisconnect] protocol "onDisconnect" handler - * @constructor + * @class + * @param {TopologyHandlers} options */ constructor ({ min = 0, @@ -27,22 +37,19 @@ class Topology { /** * Set of peers that support the protocol. + * * @type {Set} */ this.peers = new Set() } - set registrar (registrar) { + set registrar (registrar) { // eslint-disable-line this._registrar = registrar } - /** - * @typedef PeerId - * @type {import('peer-id')} - */ - /** * Notify about peer disconnected event. + * * @param {PeerId} peerId * @returns {void} */ diff --git a/src/topology/multicodec-topology.d.ts b/src/topology/multicodec-topology.d.ts index 8752aff..650ce6c 100644 --- a/src/topology/multicodec-topology.d.ts +++ b/src/topology/multicodec-topology.d.ts @@ -2,38 +2,26 @@ declare const _exports: MulticodecTopology; export = _exports; declare class MulticodecTopology { /** - * @param {Object} props - * @param {number} props.min minimum needed connections (default: 0) - * @param {number} props.max maximum needed connections (default: Infinity) - * @param {Array} props.multicodecs protocol multicodecs - * @param {Object} props.handlers - * @param {function} props.handlers.onConnect protocol "onConnect" handler - * @param {function} props.handlers.onDisconnect protocol "onDisconnect" handler - * @constructor + * @class + * @param {import('./').TopologyOptions} options */ - constructor({ min, max, multicodecs, handlers }: { - min: number; - max: number; - multicodecs: string[]; - handlers: { - onConnect: Function; - onDisconnect: Function; - }; - }); - multicodecs: string[]; + constructor({ min, max, handlers, multicodecs, }: import('./').TopologyOptions); + multicodecs: any[]; _registrar: any; /** * Check if a new peer support the multicodecs for this topology. + * * @param {Object} props * @param {PeerId} props.peerId * @param {Array} props.protocols */ _onProtocolChange({ peerId, protocols }: { peerId: any; - protocols: string[]; + protocols: Array; }): void; /** * Verify if a new connected peer has a topology multicodec and call _onConnect. + * * @param {Connection} connection * @returns {void} */ @@ -41,12 +29,13 @@ declare class MulticodecTopology { set registrar(arg: any); /** * Update topology. + * * @param {Array<{id: PeerId, multiaddrs: Array, protocols: Array}>} peerDataIterable * @returns {void} */ - _updatePeers(peerDataIterable: { + _updatePeers(peerDataIterable: Array<{ id: any; - multiaddrs: any[]; - protocols: string[]; - }[]): void; + multiaddrs: Array; + protocols: Array; + }>): void; } diff --git a/src/topology/multicodec-topology.js b/src/topology/multicodec-topology.js index 2cdc076..93824e2 100644 --- a/src/topology/multicodec-topology.js +++ b/src/topology/multicodec-topology.js @@ -6,20 +6,14 @@ const Topology = require('./index') class MulticodecTopology extends Topology { /** - * @param {Object} props - * @param {number} props.min minimum needed connections (default: 0) - * @param {number} props.max maximum needed connections (default: Infinity) - * @param {Array} props.multicodecs protocol multicodecs - * @param {Object} props.handlers - * @param {function} props.handlers.onConnect protocol "onConnect" handler - * @param {function} props.handlers.onDisconnect protocol "onDisconnect" handler - * @constructor + * @class + * @param {import('./').TopologyOptions} options */ constructor ({ - min, - max, + min = 0, + max = Infinity, + handlers = {}, multicodecs, - handlers }) { super({ min, max, handlers }) @@ -46,7 +40,7 @@ class MulticodecTopology extends Topology { this._onPeerConnect = this._onPeerConnect.bind(this) } - set registrar (registrar) { + set registrar (registrar) { // eslint-disable-line this._registrar = registrar this._registrar.peerStore.on('change:protocols', this._onProtocolChange) this._registrar.connectionManager.on('peer:connect', this._onPeerConnect) @@ -57,6 +51,7 @@ class MulticodecTopology extends Topology { /** * Update topology. + * * @param {Array<{id: PeerId, multiaddrs: Array, protocols: Array}>} peerDataIterable * @returns {void} */ @@ -77,6 +72,7 @@ class MulticodecTopology extends Topology { /** * Check if a new peer support the multicodecs for this topology. + * * @param {Object} props * @param {PeerId} props.peerId * @param {Array} props.protocols @@ -102,6 +98,7 @@ class MulticodecTopology extends Topology { /** * Verify if a new connected peer has a topology multicodec and call _onConnect. + * * @param {Connection} connection * @returns {void} */ diff --git a/src/transport/tests/utils/index.js b/src/transport/tests/utils/index.js index b0f3bf1..532395a 100644 --- a/src/transport/tests/utils/index.js +++ b/src/transport/tests/utils/index.js @@ -4,8 +4,9 @@ module.exports = { /** * A tick is considered valid if it happened between now * and `ms` milliseconds ago - * @param {number} date Time in ticks - * @param {number} ms max milliseconds that should have expired + * + * @param {number} date - Time in ticks + * @param {number} ms - max milliseconds that should have expired * @returns {boolean} */ isValidTick: function isValidTick (date, ms = 5000) { diff --git a/src/transport/types.ts b/src/transport/types.ts new file mode 100644 index 0000000..646673f --- /dev/null +++ b/src/transport/types.ts @@ -0,0 +1,103 @@ +export default Transport; + +declare class Transport implements TransportInterface { + constructor({ upgrader, ...others }: { + upgrader: Upgrader; + others: any; + }); + /** + * Dial a given multiaddr. + * @param {Multiaddr} ma + * @param {Object} [options] + * @returns {Promise} + */ + dial(ma: Multiaddr, options?: Object): Promise; + /** + * Create transport listeners. + * @param {Object} options + * @param {(Connection) => void} handler + */ + createListener(options: Object, handler: Function): Listener; + /** + * Takes a list of `Multiaddr`s and returns only valid addresses for the transport + * @param {Multiaddr[]} multiaddrs + * @returns {Multiaddr[]} + */ + filter(multiaddrs: Multiaddr[]): Multiaddr[]; +} + +/** +* A libp2p transport is understood as something that offers a dial and listen interface to establish connections. +*/ +interface TransportInterface { + /** + * Dial a given multiaddr. + * @param {Multiaddr} ma + * @param {Object} [options] + * @returns {Promise} + */ + dial(ma: Multiaddr, options?: Object): Promise; + /** + * Create transport listeners. + * @param {Object} options + * @param {(Connection) => void} handler + */ + createListener(options: Object, handler: Function): Listener; + /** + * Takes a list of `Multiaddr`s and returns only valid addresses for the transport + * @param {Multiaddr[]} multiaddrs + * @returns {Multiaddr[]} + */ + filter(multiaddrs: Multiaddr[]): Multiaddr[]; +} + +interface Listener { + /** + * Start a listener + * @param {Multiaddr} multiaddr + * @returns {Promise} + */ + listen(multiaddr: Multiaddr): Promise; + /** + * Get listen addresses + * @returns {Multiaddr[]} + */ + getAddrs(): Multiaddr[]; + /** + * Close listener + * @returns {Promise} + */ + close(): Promise; +} + +interface Upgrader { + /** + * Upgrades an outbound connection on `transport.dial`. + * @param {MultiaddrConnection} maConn + * @returns {Promise} + */ + upgradeOutbound(maConn: MultiaddrConnection): Promise; + + /** + * Upgrades an inbound connection on transport listener. + * @param {MultiaddrConnection} maConn + * @returns {Promise} + */ + upgradeInbound(maConn: MultiaddrConnection): Promise; +} + +type MultiaddrConnection = { + connection: any; + remoteAddr: Multiaddr; + sink: Sink; + source: () => AsyncIterator; +} + +type Sink = (source: Uint8Array) => Promise; +type Connection = typeof import('../connection') + +type Multiaddr = import('multiaddr'); + +declare namespace Transport { + export { Upgrader, Listener, MultiaddrConnection }; +} diff --git a/test/connection/compliance.spec.js b/test/connection/compliance.spec.js index cc55f32..e163b87 100644 --- a/test/connection/compliance.spec.js +++ b/test/connection/compliance.spec.js @@ -13,6 +13,7 @@ describe('compliance tests', () => { /** * Test setup. `properties` allows the compliance test to override * certain values for testing. + * * @param {*} properties */ async setup (properties) {