UNPKG

openraas

Version:

Open Robot-as-a-Service Protocol - A comprehensive TypeScript library for building and consuming RaaS applications with X402 payment support on Solana

69 lines (68 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRTCAdapter = void 0; const werift_1 = require("werift"); const events_1 = require("events"); class WebRTCAdapter extends events_1.EventEmitter { constructor() { super(...arguments); this.pc = null; this.dataChannel = null; } async connect(url, options) { // WebRTC connection logic is different from WS. // Usually involves signaling over another channel (like WS). // For this adapter, 'connect' might initiate the offer/answer flow if url is provided, // or we might need a separate 'signal' method. // For simplicity, we'll assume 'options' contains the signaling channel or logic. // This is a simplified placeholder for the comprehensive plan. // In a real scenario, we'd need a signaling server. this.pc = new werift_1.RTCPeerConnection(options?.config || {}); this.dataChannel = this.pc.createDataChannel('chat'); this.setupDataChannel(this.dataChannel); // Placeholder: In a real app, we would exchange SDPs here. // For now, we just emit open to simulate connection if in a test env, // or wait for the data channel to open. } setupDataChannel(dc) { dc.onopen = () => this.emit('open'); dc.onmessage = (event) => { let data = event.data; try { data = JSON.parse(data); } catch (e) { // keep as is } this.emit('message', data); }; dc.onclose = () => this.emit('close'); dc.onerror = (err) => this.emit('error', err); } send(message) { if (this.dataChannel && this.dataChannel.readyState === 'open') { const data = typeof message === 'string' ? message : JSON.stringify(message); this.dataChannel.send(data); } else { // Buffer or throw throw new Error('DataChannel is not open'); } } close() { if (this.pc) { this.pc.close(); this.pc = null; } } // Helper to handle signaling manually if needed async handleOffer(offer) { if (!this.pc) throw new Error('PC not initialized'); await this.pc.setRemoteDescription(offer); const answer = await this.pc.createAnswer(); await this.pc.setLocalDescription(answer); return answer; } } exports.WebRTCAdapter = WebRTCAdapter;