From 9552e1cadced245954bb1e6d5dbf0a6a60208341 Mon Sep 17 00:00:00 2001 From: Robert Kiel Date: Sun, 23 Feb 2020 13:32:13 +0100 Subject: [PATCH 1/3] =?UTF-8?q?=E2=99=BB=EF=B8=8E=20make=20defaults=20impl?= =?UTF-8?q?icit=20and=20implicit=20custom=20options=20explicit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tsconfig.json | 52 ++++++++++++++++----------------------------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/tsconfig.json b/tsconfig.json index 68ec1c02..f53c6d6a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,38 +1,18 @@ - { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "target": "ES5", - "noImplicitAny": false, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "esModuleInterop": true, - "resolveJsonModule": true, - "allowJs": true, - "checkJs": true, - "baseUrl": ".", - "paths": { - "multiaddr": [ - "./src", - "../src", - ] - }, - "types": [ - "node", - "mocha", - "chai" - ], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "./src/index.d.ts", - ], - "include": [ - "./test/**/*.spec.js" - ] + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "target": "ES5", + "noImplicitAny": false, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "allowJs": true, + "checkJs": true, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src/index.d.ts", "test/**/*.spec.js"], } From c425223858541038e4bf6790b2479884f76eb86a Mon Sep 17 00:00:00 2001 From: Robert Kiel Date: Sun, 23 Feb 2020 13:43:48 +0100 Subject: [PATCH 2/3] fix types and add type tests --- src/index.d.ts | 82 ++++++++++++++++++++++++++-------------------- src/index.js | 12 ++++++- test/index.spec.js | 9 +++++ test/types.spec.ts | 22 +++++++++++++ tsconfig.json | 2 +- 5 files changed, 90 insertions(+), 37 deletions(-) create mode 100644 test/types.spec.ts diff --git a/src/index.d.ts b/src/index.d.ts index 56a02e5e..f33073cf 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -1,34 +1,44 @@ -/// - -declare interface NetOptions { - family: 'ipv4' | 'ipv6'; +declare type NetOptions = { + family: "ipv4" | "ipv6"; host: string; - transport: string; + transport: "tcp" | "udp"; port: number; -} +}; -declare interface Protocol { +declare type Protocol = { code: number; size: number; name: string; - resolvable: boolean; - path: boolean; -} + resolvable: boolean | undefined; + path: boolean | undefined; +}; declare interface Protocols { - table: [number, number, string, boolean?, boolean?][]; - names: Record; - codes: Record; - object(code: number, size: number, name: string, resolvable?: any, path?: any): Protocol; + table: { + [index: number]: Protocol; + }; + names: { + [index: string]: Protocol; + }; + codes: { + [index: number]: Protocol; + }; + object( + code: number, + size: number, + name: string, + resolvable?: any, + path?: any + ): Protocol; } -declare interface NodeAddress { - family: 4 | 6; +declare type NodeAddress = { + family: "IPv4" | "IPv6"; address: string; - port: number; -} + port: string; +}; -declare type MultiaddrInput = string | Buffer | Multiaddr; +declare type MultiaddrInput = string | Buffer | Multiaddr | null; declare class Multiaddr { /** @@ -40,6 +50,8 @@ declare class Multiaddr { */ constructor(addr?: MultiaddrInput); + buffer: Buffer; + /** * Returns Multiaddr as a String */ @@ -142,20 +154,11 @@ declare class Multiaddr { isThinWaistAddress(addr?: Multiaddr): boolean; } -declare interface MultiaddrClass { - /** - * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from - * a Buffer, String or another Multiaddr instance - * public key. - * @param addr - If String or Buffer, needs to adhere - * to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format) - */ - (addr?: MultiaddrInput): Multiaddr; - +declare namespace Multiaddr { /** * Creates a Multiaddr from a node-friendly address object */ - fromNodeAddress(addr: NodeAddress, transport: string): Multiaddr; + function fromNodeAddress(addr: NodeAddress, transport: string): Multiaddr; /** * Object containing table, names and codes of all supported protocols. @@ -164,22 +167,31 @@ declare interface MultiaddrClass { * [`.protoCodes()`](#multiaddrprotocodes) or * [`.protoNames()`](#multiaddrprotonames) */ - protocols: Protocols; + const protocols: Protocols; /** * Returns if something is a Multiaddr */ - isMultiaddr(addr: unknown): addr is Multiaddr; + function isMultiaddr(addr: unknown): addr is Multiaddr; /** * Returns if something is a Multiaddr that is a name */ - isName(addr: Multiaddr): boolean; + function isName(addr: Multiaddr): boolean; /** * Returns an array of multiaddrs, by resolving the multiaddr that is a name */ - resolve(addr: Multiaddr): Promise + function resolve(addr: Multiaddr): Promise; } -export = MultiaddrClass; +/** + * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from + * a Buffer, String or another Multiaddr instance + * public key. + * @param addr - If String or Buffer, needs to adhere + * to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format) + */ +declare function Multiaddr(input?: MultiaddrInput): Multiaddr; + +export = Multiaddr; diff --git a/src/index.js b/src/index.js index dd82807f..c0c61006 100644 --- a/src/index.js +++ b/src/index.js @@ -413,7 +413,17 @@ Multiaddr.prototype.nodeAddress = function nodeAddress () { Multiaddr.fromNodeAddress = function fromNodeAddress (addr, transport) { if (!addr) throw new Error('requires node address object') if (!transport) throw new Error('requires transport protocol') - const ip = (addr.family === 'IPv6') ? 'ip6' : 'ip4' + let ip + switch (addr.family) { + case 'IPv4': + ip = 'ip4' + break + case 'IPv6': + ip = 'ip6' + break + default: + throw Error(`Invalid addr family. Got '${addr.family}' instead of 'IPv4' or 'IPv6'`) + } return Multiaddr('/' + [ip, addr.address, transport, addr.port].join('/')) } diff --git a/test/index.spec.js b/test/index.spec.js index 0cf6b34d..f9b9f5f5 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -53,16 +53,23 @@ describe('construction', () => { it('throws on truthy non string or buffer', () => { const errRegex = /addr must be a string/ + // @ts-ignore expect(() => multiaddr({})).to.throw(errRegex) + // @ts-ignore expect(() => multiaddr([])).to.throw(errRegex) + // @ts-ignore expect(() => multiaddr(138)).to.throw(errRegex) + // @ts-ignore expect(() => multiaddr(true)).to.throw(errRegex) }) it('throws on falsy non string or buffer', () => { const errRegex = /addr must be a string/ + // @ts-ignore expect(() => multiaddr(NaN)).to.throw(errRegex) + // @ts-ignore expect(() => multiaddr(false)).to.throw(errRegex) + // @ts-ignore expect(() => multiaddr(0)).to.throw(errRegex) }) }) @@ -694,6 +701,7 @@ describe('helpers', () => { describe('.fromNodeAddress', () => { it('throws on missing address object', () => { expect( + // @ts-ignore () => multiaddr.fromNodeAddress() ).to.throw( /requires node address/ @@ -702,6 +710,7 @@ describe('helpers', () => { it('throws on missing transport', () => { expect( + // @ts-ignore () => multiaddr.fromNodeAddress({ address: '0.0.0.0' }) ).to.throw( /requires transport protocol/ diff --git a/test/types.spec.ts b/test/types.spec.ts new file mode 100644 index 00000000..df921420 --- /dev/null +++ b/test/types.spec.ts @@ -0,0 +1,22 @@ +import Multiaddr from "../src"; + +const testStr: string = "/ip4/127.0.0.1"; + +const maFromFunctionConstructor: Multiaddr = Multiaddr(testStr); + +const maFromClassConstructor: Multiaddr = new Multiaddr(testStr); + +const maFromMa: Multiaddr = Multiaddr(new Multiaddr(testStr)); + +const maFromConstructorFunction: Multiaddr = Multiaddr.fromNodeAddress( + { + family: "IPv4", + address: "127.0.0.1", + port: "12345" + }, + "udp" +); + +function doSthWithMa(ma: Multiaddr): void { + ma.toOptions(); +} diff --git a/tsconfig.json b/tsconfig.json index f53c6d6a..82565fd6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,5 +14,5 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": ["src/index.d.ts", "test/**/*.spec.js"], + "include": ["src/index.d.ts", "test/**/*.spec.js", "test/**/*.spec.ts"], } From 621839515f3f7612d141b88c44a572c78be44db9 Mon Sep 17 00:00:00 2001 From: Robert Kiel Date: Sat, 2 Jan 2021 17:52:44 +0100 Subject: [PATCH 3/3] * fix .toOptions meaningful error on non thinwaiste addresses * .getPeerId() returns string or null * NodeAddress port from string -> number --- package.json | 4 ++-- src/index.d.ts | 12 ++++++------ src/index.js | 13 +++++++++++-- src/resolvers/dns.d.ts | 7 +++++++ test/index.spec.js | 5 ++++- test/types.spec.ts | 4 ++-- 6 files changed, 32 insertions(+), 13 deletions(-) create mode 100644 src/resolvers/dns.d.ts diff --git a/package.json b/package.json index 637dae53..bc709274 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "@types/node": "^14.0.11", "aegir": "^29.0.1", "sinon": "^9.2.0", - "typescript": "^3.9.5" + "typescript": "^4.1" }, "contributors": [ "David Dias ", @@ -66,7 +66,7 @@ "Richard Littauer ", "Dmitriy Ryajov ", "Marcin Rataj ", - "Robert Kiel ", + "Robert Kiel ", "Maciej Krüger ", "Oli Evans ", "Alan Shaw ", diff --git a/src/index.d.ts b/src/index.d.ts index 0fca50e3..ceb22821 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -35,7 +35,7 @@ declare interface Protocols { declare type NodeAddress = { family: "IPv4" | "IPv6"; address: string; - port: string; + port: number; }; declare type MultiaddrInput = string | Uint8Array | Multiaddr | null; @@ -95,12 +95,12 @@ declare class Multiaddr { /** * Returns a tuple of parts */ - tuples(): [number, Uint8Array][]; + tuples(): [code: number, value: Uint8Array][]; /** * Returns a tuple of string/number parts */ - stringTuples(): [number, string | number][]; + stringTuples(): [code: number, value: string | number][]; /** * Encapsulates a Multiaddr in another Multiaddr @@ -123,7 +123,7 @@ declare class Multiaddr { /** * Extract the peerId if the multiaddr contains one */ - getPeerId(): string; + getPeerId(): string | null; /** * Extract the path if the multiaddr contains one @@ -156,11 +156,11 @@ declare class Multiaddr { /** * Resolve multiaddr if containing resolvable hostname. */ - resolve(): Promise> + resolve(): Promise } declare namespace Multiaddr { - const resolvers: Map < string, (addr: Multiaddr) => Promise < Array < string >>> + const resolvers: Map Promise> /** * Creates a Multiaddr from a node-friendly address object diff --git a/src/index.js b/src/index.js index fc464bd6..9e9d454c 100644 --- a/src/index.js +++ b/src/index.js @@ -84,7 +84,16 @@ Multiaddr.prototype.toJSON = Multiaddr.prototype.toString Multiaddr.prototype.toOptions = function toOptions () { const opts = {} const parsed = this.toString().split('/') - opts.family = parsed[1] === 'ip4' ? 'ipv4' : 'ipv6' + switch (parsed[1]) { + case 'ip4': + opts.family = 'ipv4' + break + case 'ip6': + opts.family = 'ipv6' + break + default: + throw new Error(`Invalid addr family. Got '${parsed[1]}' instead of 'ip4' or 'ip6'`) + } opts.host = parsed[2] opts.transport = parsed[3] opts.port = parseInt(parsed[4]) @@ -462,7 +471,7 @@ Multiaddr.fromNodeAddress = function fromNodeAddress (addr, transport) { ip = 'ip6' break default: - throw Error(`Invalid addr family. Got '${addr.family}' instead of 'IPv4' or 'IPv6'`) + throw new Error(`Invalid addr family. Got '${addr.family}' instead of 'IPv4' or 'IPv6'`) } return Multiaddr('/' + [ip, addr.address, transport, addr.port].join('/')) } diff --git a/src/resolvers/dns.d.ts b/src/resolvers/dns.d.ts new file mode 100644 index 00000000..7f3da17b --- /dev/null +++ b/src/resolvers/dns.d.ts @@ -0,0 +1,7 @@ +// Explains to Typescript that 'dns.js' exports +// a class that has the same properties as Resolver +type DNSResolver = typeof import('dns').promises.Resolver + +declare var Resolver: DNSResolver + +export { Resolver } \ No newline at end of file diff --git a/test/index.spec.js b/test/index.spec.js index c154eb4a..27f9682b 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -486,6 +486,9 @@ describe('helpers', () => { transport: 'tcp', port: 1234 }) + + const errRegex = /Invalid addr family/ + expect(() => multiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC').toOptions()).to.throw(errRegex) }) }) @@ -745,7 +748,7 @@ describe('helpers', () => { multiaddr.fromNodeAddress({ address: '192.168.0.1', family: 'IPv4', - port: '1234' + port: 1234 }, 'tcp').toString() ).to.be.eql( '/ip4/192.168.0.1/tcp/1234' diff --git a/test/types.spec.ts b/test/types.spec.ts index ba9129c9..72ee02e8 100644 --- a/test/types.spec.ts +++ b/test/types.spec.ts @@ -12,11 +12,11 @@ export const maFromConstructorFunction: Multiaddr = Multiaddr.fromNodeAddress( { family: 'IPv4', address: '127.0.0.1', - port: '12345' + port: 12345 }, 'udp' ) -export function doSthWithMa (ma: Multiaddr): void { +export function doSthWithMa(ma: Multiaddr): void { ma.toOptions() }