diff --git a/LICENSE b/LICENSE index 2071b23..6cdeefe 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) +Copyright (c) <2022> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/package.json b/package.json new file mode 100644 index 0000000..5725f3e --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@lumeweb/peer-discovery", + "version": "0.1.0", + "main": "dist/index.js", + "devDependencies": { + "@types/b4a": "^1.6.0", + "@types/node": "^18.11.17", + "prettier": "^2.8.1", + "typescript": "^4.9.4" + }, + "dependencies": { + "b4a": "^1.6.1" + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..98c6a4f --- /dev/null +++ b/src/index.ts @@ -0,0 +1,47 @@ +import b4a from "b4a"; + +export interface Peer { + host: string; + port: number; +} + +export type PeerSource = (pubkey: Buffer) => Promise; + +export class PeerDiscovery { + private _sources: Map = new Map(); + + public registerSource(name: string, source: PeerSource): boolean { + if (this._sources.has(name)) { + return false; + } + this._sources.set(name, source); + + return true; + } + + public removeSource(name: string): boolean { + if (!this._sources.has(name)) { + return false; + } + + this._sources.delete(name); + + return true; + } + + public async discover(pubkey: string | Buffer): Promise { + if (!b4a.isBuffer(pubkey)) { + pubkey = b4a.from(pubkey, "hex") as Buffer; + } + + for (const source of this._sources.values()) { + const result = await source(pubkey); + + if (result) { + return result; + } + } + + return false; + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..8d1c301 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "esnext", + "sourceMap": true, + "esModuleInterop": true, + "outDir": "dist", + "declaration": true + }, + "include": ["src"], + "exclude": [ + "node_modules" + ] +}