Compare commits

..

1 Commits

Author SHA1 Message Date
30c2343605 Update multicodec-topology.d.ts 2020-11-27 12:38:53 -08:00
21 changed files with 234 additions and 389 deletions

View File

@ -13,7 +13,7 @@
"lint": "aegir lint",
"build": "aegir build",
"pregenerate:types": "rimraf './src/**/*.d.ts'",
"generate:types": "tsc --build",
"generate:types": "tsc",
"test": "aegir test",
"test:node": "aegir test --target node",
"test:browser": "aegir test --target browser",
@ -41,6 +41,7 @@
"abortable-iterator": "^3.0.0",
"chai": "^4.2.0",
"chai-checkmark": "^1.0.1",
"class-is": "^1.1.0",
"debug": "^4.1.1",
"delay": "^4.3.0",
"detect-node": "^2.0.4",
@ -69,7 +70,7 @@
"aegir": "^25.0.0",
"it-handshake": "^1.0.1",
"rimraf": "^3.0.2",
"typescript": "^4.0.5"
"typescript": "3.7.5"
},
"contributors": [
"Alan Shaw <alan.shaw@protocol.ai>",

View File

@ -1,16 +1,10 @@
export = Connection;
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 {
/**
* Checks if the given value is a `Connection` instance.
*
* @param {any} other
* @returns {other is Connection}
*/
static isConnection(other: any): other is Connection;
/**
* Creates an instance of Connection.
* @param {object} properties properties of the connection.
@ -30,10 +24,10 @@ declare class Connection {
* @param {string} [properties.stat.encryption] connection encryption method identifier.
*/
constructor({ localAddr, remoteAddr, localPeer, remotePeer, newStream, close, getStreams, stat }: {
localAddr: multiaddr | undefined;
remoteAddr: multiaddr | undefined;
localPeer: PeerId;
remotePeer: PeerId;
localAddr?: import("multiaddr");
remoteAddr?: import("multiaddr");
localPeer: import("peer-id");
remotePeer: import("peer-id");
newStream: Function;
close: Function;
getStreams: () => any[];
@ -43,42 +37,42 @@ declare class Connection {
open: string;
upgraded: string;
};
multiplexer: string | undefined;
encryption: string | undefined;
multiplexer?: string;
encryption?: string;
};
});
/**
* Connection identifier.
*/
id: string;
id: any;
/**
* Observed multiaddr of the local peer
*/
localAddr: multiaddr | undefined;
localAddr: import("multiaddr");
/**
* Observed multiaddr of the remote peer
*/
remoteAddr: multiaddr | undefined;
remoteAddr: import("multiaddr");
/**
* Local peer id.
*/
localPeer: PeerId;
localPeer: import("peer-id");
/**
* Remote peer id.
*/
remotePeer: PeerId;
remotePeer: import("peer-id");
/**
* Connection metadata.
*/
_stat: {
status: "open";
status: string;
direction: string;
timeline: {
open: string;
upgraded: string;
};
multiplexer?: string | undefined;
encryption?: string | undefined;
multiplexer?: string;
encryption?: string;
};
/**
* Reference to the new stream function of the multiplexer
@ -101,20 +95,19 @@ declare class Connection {
* @type {string[]}
*/
tags: string[];
get [Symbol.toStringTag](): string;
/**
* Get connection metadata
* @this {Connection}
*/
get stat(): {
status: "open";
status: string;
direction: string;
timeline: {
open: string;
upgraded: string;
};
multiplexer?: string | undefined;
encryption?: string | undefined;
multiplexer?: string;
encryption?: string;
};
/**
* Get all the streams of the muxer.
@ -140,7 +133,7 @@ declare class Connection {
*/
addStream(muxedStream: any, { protocol, metadata }: {
protocol: string;
metadata: object;
metadata: any;
}): void;
/**
* Remove stream registry after it is closed.
@ -153,8 +146,4 @@ declare class Connection {
*/
close(): Promise<void>;
_closing: any;
get [connectionSymbol](): boolean;
}
import multiaddr = require("multiaddr");
import PeerId = require("peer-id");
declare const connectionSymbol: unique symbol;

View File

@ -1,13 +1,11 @@
'use strict'
/* eslint-disable valid-jsdoc */
const PeerId = require('peer-id')
const multiaddr = require('multiaddr')
const withIs = require('class-is')
const errCode = require('err-code')
const Status = require('./status')
const connectionSymbol = Symbol.for('@libp2p/interface-connection/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')
@ -140,24 +138,6 @@ class Connection {
this.tags = []
}
get [Symbol.toStringTag] () {
return 'Connection'
}
get [connectionSymbol] () {
return true
}
/**
* Checks if the given value is a `Connection` instance.
*
* @param {any} other
* @returns {other is Connection}
*/
static isConnection (other) {
return Boolean(other && other[connectionSymbol])
}
/**
* Get connection metadata
* @this {Connection}
@ -247,4 +227,8 @@ class Connection {
}
}
module.exports = Connection
/**
* @module
* @type {typeof Connection}
*/
module.exports = withIs(Connection, { className: 'Connection', symbolName: '@libp2p/interface-connection/connection' })

View File

@ -1,3 +1,3 @@
export const OPEN: 'open';
export const CLOSING: 'closing';
export const CLOSED: 'closed';
export declare const OPEN: string;
export declare const CLOSING: string;
export declare const CLOSED: string;

View File

@ -1,7 +1,7 @@
'use strict'
module.exports = {
OPEN: /** @type {'open'} */('open'),
CLOSING: /** @type {'closing'} */('closing'),
CLOSED: /** @type {'closed'} */('closed')
OPEN: 'open',
CLOSING: 'closing',
CLOSED: 'closed'
}

View File

@ -1,11 +1,11 @@
export namespace codes {
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;
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;
}

116
src/pubsub/index.d.ts vendored
View File

@ -1,14 +1,40 @@
export = PubsubBaseProtocol;
/**
* @typedef {Object} InMessage
* @property {string} [from]
* @property {string} receivedFrom
* @property {string[]} topicIDs
* @property {Uint8Array} [seqno]
* @property {Uint8Array} data
* @property {Uint8Array} [signature]
* @property {Uint8Array} [key]
*
* @typedef PeerId
* @type import('peer-id')
*/
/**
* 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>|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
* @abstract
* @param {Options} options
*/
constructor({ debugName, multicodecs, libp2p, globalSignaturePolicy, canRelayMessage, emitSelf }: Options);
constructor({ debugName, multicodecs, libp2p, globalSignaturePolicy, canRelayMessage, emitSelf }: {
debugName: string;
multicodecs: string | string[];
libp2p: any;
globalSignaturePolicy?: any;
canRelayMessage?: boolean;
emitSelf?: boolean;
});
log: any;
/**
* @type {Array<string>}
@ -65,38 +91,35 @@ declare class PubsubBaseProtocol {
* Topic validators are functions with the following input:
* @type {Map<string, validator>}
*/
topicValidators: Map<string, (arg0: string, arg1: InMessage) => Promise<void>>;
topicValidators: Map<string, validator>;
_registrarId: any;
/**
* On an inbound stream opened.
*
* @protected
* @private
* @param {Object} props
* @param {string} props.protocol
* @param {DuplexIterableStream} props.stream
* @param {Connection} props.connection connection
*/
protected _onIncomingStream({ protocol, stream, connection }: {
_onIncomingStream({ protocol, stream, connection }: {
protocol: string;
stream: any;
connection: any;
}): void;
/**
* Registrar notifies an established connection with pubsub protocol.
*
* @protected
* @private
* @param {PeerId} peerId remote peer-id
* @param {Connection} conn connection to the peer
*/
protected _onPeerConnected(peerId: PeerId, conn: any): Promise<void>;
_onPeerConnected(peerId: import("peer-id"), conn: any): Promise<void>;
/**
* Registrar notifies a closing connection with pubsub protocol.
*
* @protected
* @private
* @param {PeerId} peerId peerId
* @param {Error} err error for connection end
*/
protected _onPeerDisconnected(peerId: PeerId, err: Error): void;
_onPeerDisconnected(peerId: import("peer-id"), err: Error): void;
/**
* Register the pubsub protocol onto the libp2p node.
* @returns {void}
@ -109,21 +132,19 @@ declare class PubsubBaseProtocol {
stop(): void;
/**
* Notifies the router that a peer has been connected
*
* @protected
* @private
* @param {PeerId} peerId
* @param {string} protocol
* @returns {PeerStreams}
*/
protected _addPeer(peerId: PeerId, protocol: string): PeerStreams;
_addPeer(peerId: import("peer-id"), protocol: string): import("./peer-streams");
/**
* Notifies the router that a peer has been disconnected.
*
* @protected
* @private
* @param {PeerId} peerId
* @returns {PeerStreams | undefined}
*/
protected _removePeer(peerId: PeerId): PeerStreams | undefined;
_removePeer(peerId: import("peer-id")): import("./peer-streams");
/**
* Responsible for processing each RPC message received by other peers.
* @param {string} idB58Str peer id string in base58
@ -131,7 +152,7 @@ declare class PubsubBaseProtocol {
* @param {PeerStreams} peerStreams PubSub peer
* @returns {Promise<void>}
*/
_processMessages(idB58Str: string, stream: any, peerStreams: PeerStreams): Promise<void>;
_processMessages(idB58Str: string, stream: any, peerStreams: import("./peer-streams")): Promise<void>;
/**
* Handles an rpc request from a peer
* @param {String} idB58Str
@ -139,7 +160,7 @@ declare class PubsubBaseProtocol {
* @param {RPC} rpc
* @returns {boolean}
*/
_processRpc(idB58Str: string, peerStreams: PeerStreams, rpc: any): boolean;
_processRpc(idB58Str: string, peerStreams: import("./peer-streams"), rpc: any): boolean;
/**
* Handles a subscription change from a peer
* @param {string} id
@ -211,18 +232,17 @@ 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.
*
* @protected
* @private
* @param {Message} message
* @returns {Promise<Message>}
*/
protected _buildMessage(message: any): Promise<any>;
_buildMessage(message: any): Promise<any>;
/**
* Get a list of the peer-ids that are subscribed to one topic.
* @param {string} topic
* @returns {Array<string>}
*/
getSubscribers(topic: string): Array<string>;
getSubscribers(topic: string): string[];
/**
* Publishes messages to all subscribed peers
* @override
@ -259,49 +279,31 @@ declare class PubsubBaseProtocol {
* @override
* @returns {Array<String>}
*/
getTopics(): Array<string>;
getTopics(): string[];
}
declare namespace PubsubBaseProtocol {
export { message, utils, SignaturePolicy, Options, InMessage, PeerId, SignaturePolicyType };
export { message, utils, SignaturePolicy, InMessage, PeerId };
}
type PeerId = import("peer-id");
/**
* Topic validator function
*/
type validator = (arg0: string, arg1: InMessage) => Promise<void>;
type InMessage = {
from?: string | undefined;
from?: string;
receivedFrom: string;
topicIDs: string[];
seqno?: Uint8Array | undefined;
seqno?: Uint8Array;
data: Uint8Array;
signature?: Uint8Array | undefined;
key?: Uint8Array | undefined;
};
import PeerStreams = require("./peer-streams");
type Options = {
/**
* - log namespace
*/
debugName?: string | undefined;
/**
* - protocol identificers to connect
*/
multicodecs?: string | string[] | undefined;
libp2p: any;
/**
* - defines how signatures should be handled
*/
globalSignaturePolicy?: "StrictSign" | "StrictNoSign" | undefined;
/**
* - if can relay messages not subscribed
*/
canRelayMessage?: boolean | undefined;
/**
* - if publish should emit to self, if subscribed
*/
emitSelf?: boolean | undefined;
signature?: Uint8Array;
key?: Uint8Array;
};
/**
* @type {typeof import('./message')}
*/
declare const message: typeof import('./message');
import utils = require("./utils");
import { SignaturePolicy } from "./signature-policy";
type SignaturePolicyType = "StrictSign" | "StrictNoSign";
declare const utils: typeof import("./utils");
declare const SignaturePolicy: {
StrictSign: string;
StrictNoSign: string;
};

View File

@ -1,5 +1,4 @@
'use strict'
/* eslint-disable valid-jsdoc */
const debug = require('debug')
const EventEmitter = require('events')
@ -22,14 +21,34 @@ const {
verifySignature
} = require('./message/sign')
/**
* @typedef {Object} InMessage
* @property {string} [from]
* @property {string} receivedFrom
* @property {string[]} topicIDs
* @property {Uint8Array} [seqno]
* @property {Uint8Array} data
* @property {Uint8Array} [signature]
* @property {Uint8Array} [key]
*
* @typedef PeerId
* @type import('peer-id')
*/
/**
* 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>|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
* @abstract
* @param {Options} options
*/
constructor ({
debugName,
@ -186,8 +205,7 @@ class PubsubBaseProtocol extends EventEmitter {
/**
* On an inbound stream opened.
*
* @protected
* @private
* @param {Object} props
* @param {string} props.protocol
* @param {DuplexIterableStream} props.stream
@ -204,8 +222,7 @@ class PubsubBaseProtocol extends EventEmitter {
/**
* Registrar notifies an established connection with pubsub protocol.
*
* @protected
* @private
* @param {PeerId} peerId remote peer-id
* @param {Connection} conn connection to the peer
*/
@ -227,8 +244,7 @@ class PubsubBaseProtocol extends EventEmitter {
/**
* Registrar notifies a closing connection with pubsub protocol.
*
* @protected
* @private
* @param {PeerId} peerId peerId
* @param {Error} err error for connection end
*/
@ -241,8 +257,7 @@ class PubsubBaseProtocol extends EventEmitter {
/**
* Notifies the router that a peer has been connected
*
* @protected
* @private
* @param {PeerId} peerId
* @param {string} protocol
* @returns {PeerStreams}
@ -272,8 +287,7 @@ class PubsubBaseProtocol extends EventEmitter {
/**
* Notifies the router that a peer has been disconnected.
*
* @protected
* @private
* @param {PeerId} peerId
* @returns {PeerStreams | undefined}
*/
@ -549,8 +563,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.
*
* @protected
* @private
* @param {Message} message
* @returns {Promise<Message>}
*/
@ -683,27 +696,6 @@ class PubsubBaseProtocol extends EventEmitter {
}
}
/**
* @typedef {Object} Options
* @property {string} [debugName] - log namespace
* @property {string[]|string} [multicodecs] - protocol identificers to connect
* @property {Libp2p} libp2p
* @property {SignaturePolicyType} [globalSignaturePolicy = SignaturePolicy.StrictSign] - defines how signatures should be handled
* @property {boolean} [canRelayMessage = false] - if can relay messages not subscribed
* @property {boolean} [emitSelf = false] - if publish should emit to self, if subscribed
*
* @typedef {Object} InMessage
* @property {string} [from]
* @property {string} receivedFrom
* @property {string[]} topicIDs
* @property {Uint8Array} [seqno]
* @property {Uint8Array} data
* @property {Uint8Array} [signature]
* @property {Uint8Array} [key]
*
* @typedef {import('peer-id')} PeerId
* @typedef {import('./signature-policy').SignaturePolicyType} SignaturePolicyType
*/
module.exports = PubsubBaseProtocol
module.exports.message = message
module.exports.utils = utils

View File

@ -1,4 +1,5 @@
declare const rpcProto: any;
declare const topicDescriptorProto: any;
export const RPC: any;
export { rpcProto as rpc, topicDescriptorProto as td };
export var rpc: any;
export var td: any;
export var RPC: any;
export var Message: any;
export var SubOpts: any;

View File

@ -13,7 +13,7 @@ export function messagePublicKey(message: any): Promise<any>;
* @param {Message} message
* @returns {Promise<Message>}
*/
export function signMessage(peerId: PeerId, message: any): Promise<any>;
export function signMessage(peerId: import("peer-id"), message: any): Promise<any>;
export const SignPrefix: any;
/**
* Verifies the signature of the given message
@ -21,4 +21,3 @@ export const SignPrefix: any;
* @returns {Promise<Boolean>}
*/
export function verifySignature(message: any): Promise<boolean>;
import PeerId = require("peer-id");

View File

@ -21,7 +21,7 @@ declare class PeerStreams {
* @param {string} properties.protocol
*/
constructor({ id, protocol }: {
id: PeerId;
id: import("peer-id");
protocol: string;
});
/**
@ -35,25 +35,22 @@ declare class PeerStreams {
protocol: string;
/**
* The raw outbound stream, as retrieved from conn.newStream
*
* @protected
* @private
* @type {DuplexIterableStream}
*/
protected _rawOutboundStream: DuplexIterableStream;
_rawOutboundStream: DuplexIterableStream;
/**
* The raw inbound stream, as retrieved from the callback from libp2p.handle
*
* @protected
* @private
* @type {DuplexIterableStream}
*/
protected _rawInboundStream: DuplexIterableStream;
_rawInboundStream: DuplexIterableStream;
/**
* An AbortController for controlled shutdown of the inbound stream
*
* @protected
* @private
* @type {typeof AbortController}
*/
protected _inboundAbortController: typeof AbortController;
_inboundAbortController: typeof AbortController;
/**
* Write stream -- its preferable to use the write method
* @type {import('it-pushable').Pushable<Uint8Array>>}
@ -109,8 +106,8 @@ declare namespace PeerStreams {
}
type DuplexIterableStream = {
sink: Sink;
source: () => AsyncIterator<Uint8Array>;
source: () => AsyncIterator<Uint8Array, any, undefined>;
};
import AbortController = require("abort-controller");
type PeerId = import("peer-id");
declare const AbortController: typeof import("abort-controller");
type Sink = (source: Uint8Array) => Promise<Uint8Array>;
type PeerId = import("peer-id");

View File

@ -48,22 +48,19 @@ class PeerStreams extends EventEmitter {
this.protocol = protocol
/**
* The raw outbound stream, as retrieved from conn.newStream
*
* @protected
* @private
* @type {DuplexIterableStream}
*/
this._rawOutboundStream = null
/**
* The raw inbound stream, as retrieved from the callback from libp2p.handle
*
* @protected
* @private
* @type {DuplexIterableStream}
*/
this._rawInboundStream = null
/**
* An AbortController for controlled shutdown of the inbound stream
*
* @protected
* @private
* @type {typeof AbortController}
*/
this._inboundAbortController = null

View File

@ -1,5 +1,4 @@
export type SignaturePolicyType = "StrictSign" | "StrictNoSign";
export namespace SignaturePolicy {
const StrictSign: 'StrictSign';
const StrictNoSign: 'StrictNoSign';
export const StrictSign: string;
export const StrictNoSign: string;
}

View File

@ -4,7 +4,7 @@
* Enum for Signature Policy
* Details how message signatures are produced/consumed
*/
const SignaturePolicy = {
exports.SignaturePolicy = {
/**
* On the producing side:
* * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.
@ -13,7 +13,7 @@ const SignaturePolicy = {
* * Enforce the fields to be present, reject otherwise.
* * Propagate only if the fields are valid and signature can be verified, reject otherwise.
*/
StrictSign: /** @type {'StrictSign'} */ ('StrictSign'),
StrictSign: 'StrictSign',
/**
* On the producing side:
* * Build messages without the signature, key, from and seqno fields.
@ -24,10 +24,5 @@ const SignaturePolicy = {
* * Propagate only if the fields are absent, reject otherwise.
* * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.
*/
StrictNoSign: /** @type {'StrictNoSign'} */ ('StrictNoSign')
StrictNoSign: 'StrictNoSign'
}
exports.SignaturePolicy = SignaturePolicy
/**
* @typedef {SignaturePolicy[keyof SignaturePolicy]} SignaturePolicyType
*/

14
src/pubsub/utils.d.ts vendored
View File

@ -1,13 +1,7 @@
export function randomSeqno(): Uint8Array;
export function msgId(from: string, seqno: Uint8Array): Uint8Array;
export function noSignMsgId(data: Uint8Array): Uint8Array;
export function anyMatch(a: Set<any> | any[], b: Set<any> | any[]): boolean;
export function ensureArray<T>(maybeArray: T | T[]): T[];
export function normalizeInRpcMessage<T extends unknown>(message: T, peerId?: string | undefined): T & {
from?: string | undefined;
peerId?: string | undefined;
};
export function normalizeOutRpcMessage<T extends unknown>(message: T): T & {
from?: Uint8Array | undefined;
data?: Uint8Array | undefined;
};
export function anyMatch(a: any[] | Set<any>, b: any[] | Set<any>): boolean;
export function ensureArray(maybeArray: any): any[];
export function normalizeInRpcMessage(message: any, peerId: string): any;
export function normalizeOutRpcMessage(message: any): any;

View File

@ -1,5 +1,4 @@
'use strict'
/* eslint-disable valid-jsdoc */
const randomBytes = require('libp2p-crypto/src/random-bytes')
const uint8ArrayToString = require('uint8arrays/to-string')
@ -72,9 +71,8 @@ exports.anyMatch = (a, b) => {
/**
* Make everything an array.
*
* @template T
* @param {T|T[]} maybeArray
* @returns {T[]}
* @param {any} maybeArray
* @returns {Array}
* @private
*/
exports.ensureArray = (maybeArray) => {
@ -87,11 +85,9 @@ exports.ensureArray = (maybeArray) => {
/**
* Ensures `message.from` is base58 encoded
*
* @template {Object} T
* @param {T} message
* @param {string} [peerId]
* @return {T & {from?: string, peerId?: string }}
* @param {object} message
* @param {String} peerId
* @return {object}
*/
exports.normalizeInRpcMessage = (message, peerId) => {
const m = Object.assign({}, message)
@ -105,10 +101,8 @@ exports.normalizeInRpcMessage = (message, peerId) => {
}
/**
* @template {Object} T
*
* @param {T} message
* @return {T & {from?: Uint8Array, data?: Uint8Array}}
* @param {object} message
* @return {object}
*/
exports.normalizeOutRpcMessage = (message) => {
const m = Object.assign({}, message)

View File

@ -1,16 +1,23 @@
export = Topology;
declare const _exports: Topology;
export = _exports;
declare class Topology {
/**
* Checks if the given value is a Topology instance.
*
* @param {any} other
* @returns {other is 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
*/
static isTopology(other: any): other is Topology;
/**
* @param {Options} options
*/
constructor({ min, max, handlers }: Options);
constructor({ min, max, handlers }: {
min: number;
max: number;
handlers?: {
onConnect?: Function;
onDisconnect?: Function;
};
});
min: number;
max: number;
_onConnect: Function;
@ -20,7 +27,6 @@ declare class Topology {
* @type {Set<string>}
*/
peers: Set<string>;
get [Symbol.toStringTag](): string;
set registrar(arg: any);
_registrar: any;
/**
@ -33,30 +39,4 @@ declare class Topology {
* @returns {void}
*/
disconnect(peerId: import("peer-id")): void;
get [topologySymbol](): boolean;
}
declare namespace Topology {
export { Options, Handlers };
}
declare const topologySymbol: unique symbol;
type Options = {
/**
* - minimum needed connections.
*/
min?: number | undefined;
/**
* - maximum needed connections.
*/
max?: number | undefined;
handlers?: Handlers | undefined;
};
type Handlers = {
/**
* - protocol "onConnect" handler
*/
onConnect?: Function | undefined;
/**
* - protocol "onDisconnect" handler
*/
onDisconnect?: Function | undefined;
};

View File

@ -1,12 +1,17 @@
'use strict'
/* eslint-disable valid-jsdoc */
const withIs = require('class-is')
const noop = () => {}
const topologySymbol = Symbol.for('@libp2p/js-interfaces/topology')
class Topology {
/**
* @param {Options} options
* @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
*/
constructor ({
min = 0,
@ -27,24 +32,6 @@ class Topology {
this.peers = new Set()
}
get [Symbol.toStringTag] () {
return 'Topology'
}
get [topologySymbol] () {
return true
}
/**
* Checks if the given value is a Topology instance.
*
* @param {any} other
* @returns {other is Topology}
*/
static isTopology (other) {
return Boolean(other && other[topologySymbol])
}
set registrar (registrar) {
this._registrar = registrar
}
@ -65,14 +52,7 @@ class Topology {
}
/**
* @typedef {Object} Options
* @property {number} [min=0] - minimum needed connections.
* @property {number} [max=Infinity] - maximum needed connections.
* @property {Handlers} [handlers]
*
* @typedef {Object} Handlers
* @property {Function} [onConnect] - protocol "onConnect" handler
* @property {Function} [onDisconnect] - protocol "onDisconnect" handler
* @module
* @type {Topology}
*/
module.exports = Topology
module.exports = withIs(Topology, { className: 'Topology', symbolName: '@libp2p/js-interfaces/topology' })

View File

@ -1,17 +1,26 @@
export = MulticodecTopology;
declare class MulticodecTopology extends Topology {
declare class MulticodecTopology {
/**
* Checks if the given value is a `MulticodecTopology` instance.
*
* @param {any} other
* @returns {other is MulticodecTopology}
* @param {Object} props
* @param {number} props.min minimum needed connections (default: 0)
* @param {number} props.max maximum needed connections (default: Infinity)
* @param {Array<string>} 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
*/
static isMulticodecTopology(other: any): other is MulticodecTopology;
/**
* @param {TopologyOptions & MulticodecOptions} props
*/
constructor({ min, max, multicodecs, handlers }: TopologyOptions & MulticodecOptions);
constructor({ min, max, multicodecs, handlers }: {
min: number;
max: number;
multicodecs: string[];
handlers: {
onConnect: Function;
onDisconnect: Function;
};
});
multicodecs: string[];
_registrar: any;
/**
* Check if a new peer support the multicodecs for this topology.
* @param {Object} props
@ -19,60 +28,24 @@ declare class MulticodecTopology extends Topology {
* @param {Array<string>} props.protocols
*/
_onProtocolChange({ peerId, protocols }: {
peerId: PeerId;
protocols: Array<string>;
peerId: any;
protocols: string[];
}): void;
/**
* Verify if a new connected peer has a topology multicodec and call _onConnect.
* @param {Connection} connection
* @returns {void}
*/
_onPeerConnect(connection: Connection): void;
_onPeerConnect(connection: any): void;
set registrar(arg: any);
/**
* Update topology.
* @param {Array<{id: PeerId, multiaddrs: Array<Multiaddr>, protocols: Array<string>}>} peerDataIterable
* @returns {void}
*/
_updatePeers(peerDataIterable: Array<{
id: PeerId;
multiaddrs: Array<Multiaddr>;
protocols: Array<string>;
}>): void;
get [multicodecTopologySymbol](): boolean;
_updatePeers(peerDataIterable: {
id: any;
multiaddrs: any[];
protocols: string[];
}[]): void;
}
declare namespace MulticodecTopology {
export { PeerId, Multiaddr, Connection, TopologyOptions, MulticodecOptions, Handlers };
}
import Topology = require(".");
type PeerId = import("peer-id");
type Connection = typeof import("../connection");
type Multiaddr = import("multiaddr");
declare const multicodecTopologySymbol: unique symbol;
type TopologyOptions = {
/**
* - minimum needed connections.
*/
min?: number | undefined;
/**
* - maximum needed connections.
*/
max?: number | undefined;
handlers?: Topology.Handlers | undefined;
};
type MulticodecOptions = {
/**
* - protocol multicodecs
*/
multicodecs: string[];
handlers: Required<Handlers>;
};
type Handlers = {
/**
* - protocol "onConnect" handler
*/
onConnect?: Function | undefined;
/**
* - protocol "onDisconnect" handler
*/
onDisconnect?: Function | undefined;
};

View File

@ -1,12 +1,19 @@
'use strict'
/* eslint-disable valid-jsdoc */
const withIs = require('class-is')
const Topology = require('./index')
const multicodecTopologySymbol = Symbol.for('@libp2p/js-interfaces/topology/multicodec-topology')
class MulticodecTopology extends Topology {
/**
* @param {TopologyOptions & MulticodecOptions} props
* @param {Object} props
* @param {number} props.min minimum needed connections (default: 0)
* @param {number} props.max maximum needed connections (default: Infinity)
* @param {Array<string>} 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
*/
constructor ({
min,
@ -39,24 +46,6 @@ class MulticodecTopology extends Topology {
this._onPeerConnect = this._onPeerConnect.bind(this)
}
get [Symbol.toStringTag] () {
return 'Topology'
}
get [multicodecTopologySymbol] () {
return true
}
/**
* Checks if the given value is a `MulticodecTopology` instance.
*
* @param {any} other
* @returns {other is MulticodecTopology}
*/
static isMulticodecTopology (other) {
return Boolean(other && other[multicodecTopologySymbol])
}
set registrar (registrar) {
this._registrar = registrar
this._registrar.peerStore.on('change:protocols', this._onProtocolChange)
@ -117,7 +106,6 @@ class MulticodecTopology extends Topology {
* @returns {void}
*/
_onPeerConnect (connection) {
// @ts-ignore - remotePeer does not existist on Connection
const peerId = connection.remotePeer
const protocols = this._registrar.peerStore.protoBook.get(peerId)
@ -133,13 +121,7 @@ class MulticodecTopology extends Topology {
}
/**
* @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} Multiaddr
* @typedef {import('../connection')} Connection
* @typedef {import('.').Options} TopologyOptions
* @typedef {Object} MulticodecOptions
* @property {string[]} multicodecs - protocol multicodecs
* @property {Required<Handlers>} handlers
* @typedef {import('.').Handlers} Handlers
* @module
* @type {MulticodecTopology}
*/
module.exports = MulticodecTopology
module.exports = withIs(MulticodecTopology, { className: 'MulticodecTopology', symbolName: '@libp2p/js-interfaces/topology/multicodec-topology' })

View File

@ -6,20 +6,6 @@
// Tells TypeScript to read JS files, as
// normally they are ignored as source files
"allowJs": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": false,
"noImplicitAny": false,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"strictFunctionTypes": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"strict": true,
"alwaysStrict": true,
"stripInternal": true,
// Generate d.ts files
"declaration": true,
// This compiler run should