import EventEmitter from "node:events"; export class KnotEventListener extends EventEmitter { constructor({ knotDomain, reconnectTimeout = 10000 }) { super(); this.knotDomain = knotDomain; this.reconnectTimeout = reconnectTimeout; this.connection = null; } async start() { this.connection = new WebSocket(`wss://${this.knotDomain}/events`); this.connection.onmessage = (event) => this.handleMessage(event); this.connection.onerror = (event) => this.handleError(event); this.connection.onclose = () => this.handleClose(); return new Promise((resolve) => { this.connection.onopen = () => { console.log("Knot event listener connected to:", this.knotDomain); resolve(); }; }); } async handleMessage(event) { const data = JSON.parse(event.data); if (data.nsid === "sh.tangled.git.refUpdate") { const event = { details: { ownerDid: data.event.repoDid, repoName: data.event.repoName, }, }; this.emit("refUpdate", event); } } handleError(event) { console.error("Knot event listener error:", event); this.emit("error", event); } handleClose() { console.log("Knot event listener closed"); this.emit("close"); if (this.reconnectTimeout) { setTimeout(() => { console.log("Knot event listener reconnecting..."); this.start(); }, this.reconnectTimeout).unref(); } } }