UNPKG

@nostr-relay/wot-guard

Version:
94 lines 2.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Relay = void 0; const common_1 = require("@nostr-relay/common"); const crypto_1 = require("crypto"); const ws_1 = require("ws"); class Relay { constructor(url, { agent } = {}) { this.client = null; this.reqJob = new Map(); this.url = url; this.agent = agent; } async init() { if (this.client) { return; } const client = new ws_1.WebSocket(this.url, { timeout: 3000, agent: this.agent, }); await new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error(`Failed to connect to ${this.url}`)); }, 3000); client.on('open', () => { clearTimeout(timeout); this.client = client; resolve(); }); client.on('message', (data) => { this.handleMessage(data); }); client.on('error', err => { console.error(err); }); }); } destroy() { if (this.client) { if (this.client.readyState === 1) { this.client.terminate(); } this.client = null; } this.reqJob.clear(); } handleMessage(data) { const [type, ...rest] = JSON.parse(data); if (type === 'EVENT') { const [subId, event] = rest; const job = this.reqJob.get(subId); if (job) { const isInvalid = !!common_1.EventUtils.validate(event); if (isInvalid) return; job.eventCb(event); } } else if (type === 'EOSE') { const [subId] = rest; const job = this.reqJob.get(subId); if (job) { job.eoseCb(); } } } async fetchEvents(filter) { if (!this.client || this.client.readyState !== 1) { return []; } return new Promise(resolve => { const subId = (0, crypto_1.randomUUID)(); const events = []; const timeout = setTimeout(() => { this.reqJob.delete(subId); resolve(events); }, 5000); this.reqJob.set(subId, { eventCb: (event) => { events.push(event); }, eoseCb: () => { this.reqJob.delete(subId); clearTimeout(timeout); resolve(events); }, }); this.client.send(JSON.stringify(['REQ', subId, filter])); }); } } exports.Relay = Relay; //# sourceMappingURL=relay.js.map