UNPKG

@synet/realtime

Version:

Realtime Communication server/client implementations

88 lines (87 loc) 3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GunRealtimeProvider = void 0; const gun_channel_1 = require("./gun-channel"); const gun_1 = __importDefault(require("gun")); const chalk_1 = __importDefault(require("chalk")); /** * GUN implementation of RealtimeProvider */ class GunRealtimeProvider { /** * Create a new GUN provider * @param url URL of the GUN server (e.g., http://localhost:8765) * @param options Provider configuration options */ constructor(url, options = {}) { this.url = url; this.options = options; this.channels = new Map(); // Initialize GUN with the provided URL this.url = url; // Configure Gun with explicit peer and disable local storage this.gun = (0, gun_1.default)({ peers: [url], localStorage: false, radisk: false, web: false, multicast: false, axe: false }); console.log(`GUN initialized with peer: ${url}`); } /** * Create a channel for real-time communication */ createChannel(topic, options) { // Check if we already have a channel for this topic const existingChannel = Array.from(this.channels.values()) .find(channel => channel instanceof gun_channel_1.GunRealtimeChannel && channel.topic === topic); if (existingChannel) { // Return the existing channel with the correct type console.log(chalk_1.default.red(`Reusing existing channel for topic: ${topic}`)); return existingChannel; } // Create a GUN node for this topic const topicNode = this.gun.get(topic); // Create a channel wrapper around the GUN node const channel = new gun_channel_1.GunRealtimeChannel(topicNode, topic, { ...options, authToken: this.options.authToken }); // Store and return the channel this.channels.set(channel.id, channel); return channel; } /** * Remove a channel and stop receiving events * @param channel The channel to remove */ async removeChannel(channel) { if (this.channels.has(channel.id)) { await channel.close(); this.channels.delete(channel.id); } } /** * Get all active channels */ getChannels() { return Array.from(this.channels.values()); } /** * Close all channels and clean up resources */ async disconnect() { // Close all channels const closePromises = Array.from(this.channels.values()).map(channel => channel.close()); await Promise.all(closePromises); // Clear channels map this.channels.clear(); } } exports.GunRealtimeProvider = GunRealtimeProvider;