export class SonoClient {
constructor(url) {
this.ws = new WebSocket(url); this.validCallbacks = {}; this.subscribedEvents ={};
} onconnection(callback){ this.ws.onopen = callback; } directmessage(message, client, event = 'message') { this.ws.send(JSON.stringify({ protocol: 'directmessage', event, payload: { message, to:client, }, })); } broadcast(message, event = 'message') { this.ws.send(JSON.stringify({ protocol: 'broadcast', event, payload: { message }, }));
} message(message, event='message'){ this.ws.send(JSON.stringify({ protocol: 'message', event, payload: { message }, })); }
changeChannel(targetChannel){ this.ws.send(JSON.stringify({ protocol: 'changeChannel', payload: { to: targetChannel }, })); } grab(request, event='grab') { this.ws.send(JSON.stringify({ protocol: 'grab', event, payload: { message: request } })); }
trigger(eventName) {
if(this.subscribedEvents[eventName]){ this.subscribedEvents[eventName](); }
}
on(eventParam, callback){ this.subscribedEvents[eventParam] = callback;
this.ws.onmessage = (event) => {
const payload = JSON.parse(event.data).payload; const eventName = JSON.parse(event.data).protocol;
if(eventName && this.subscribedEvents[eventName]) this.subscribedEvents[eventName](payload)
} }}