UNPKG

@simplito/privmx-webendpoint

Version:

PrivMX Web Endpoint library

93 lines (92 loc) 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PeerConnectionManager = void 0; class PeerConnectionManager { createPeerConnection; onTrickle; connections = {}; constructor(createPeerConnection, onTrickle) { this.createPeerConnection = createPeerConnection; this.onTrickle = onTrickle; } initialize(room, connectionType, sessionId = -1) { // Prevent re-initialization if it already exists if (room in this.connections && connectionType in this.connections[room] && this.connections[room][connectionType]?.pc) { return; } if (!(room in this.connections)) { this.connections[room] = {}; } // Create the RTCPeerConnection const pc = this.createPeerConnection(room); // Prepare the connection object immediately so we can access the queue in the listener const newConnection = { sessionId: sessionId, hasSubscriptions: false, pc, candidateQueue: [], }; // Assign immediately so the listener has access to the reference this.connections[room][connectionType] = newConnection; pc.addEventListener("icecandidate", (event) => { if (!event.candidate) { return; } const conn = this.connections[room][connectionType]; if (!conn) return; const currentSessionId = conn.sessionId; if (currentSessionId && currentSessionId > -1) { try { this.onTrickle(currentSessionId, event.candidate); } catch (err) { console.warn("Failed to trickle candidate", err); } } else { conn.candidateQueue.push(event.candidate); } }); } updateSessionForConnection(room, connectionType, session) { if (!(room in this.connections) || !(connectionType in this.connections[room])) { this.initialize(room, connectionType); } const conn = this.connections[room][connectionType]; conn.sessionId = session; if (conn.candidateQueue.length > 0) { conn.candidateQueue.forEach((candidate) => { try { this.onTrickle(session, candidate); } catch (err) { console.warn("Failed to trickle buffered candidate", err); } }); conn.candidateQueue = []; } } hasConnection(room, connectionType) { return !!(this.connections[room] && this.connections[room][connectionType]); } getConnectionWithSession(room, connectionType) { if (!this.hasConnection(room, connectionType)) { this.initialize(room, connectionType); } return this.connections[room][connectionType]; } closePeerConnectionBySessionIfExists(room, connectionType) { if (this.hasConnection(room, connectionType)) { const conn = this.connections[room][connectionType]; if (conn?.pc) { conn.pc.close(); } // Optional: Clean up the reference to allow garbage collection delete this.connections[room][connectionType]; } } } exports.PeerConnectionManager = PeerConnectionManager;