import { SSEClient, SSEClientOptions, SSEvent } from './sse-client'; import { unpackMultiple } from 'msgpackr'; /** * SSEClientMsgpackr is a subclass of SSEClient that uses msgpackr to parse the events. */ export class SSEClientMsgpackr extends SSEClient { /** * Creates a new SSEClientMsgpackr instance. * @param {string} url The URL to connect to * @param {SSEClientOptions} options The options for the SSEClient * @returns {SSEClientMsgpackr} A new SSEClientMsgpackr instance */ public static async from(url: string, options: SSEClientOptions) { const client = new SSEClientMsgpackr(url, options); await client.connect(); return client; } /** * Parses the events from the msgpackr message buffer. * @param {Uint8Array} chunk The chunk to parse * @returns {SSEvent[]} The parsed events */ protected parseEvents(chunk: Uint8Array): SSEvent[] { // Append new chunk to existing buffer this.messageBuffer = new Uint8Array([...this.messageBuffer, ...chunk]); // Create an array to store the parsed events const events: SSEvent[] = []; try { // Try to decode the entire buffer as msgPackr messages unpackMultiple(this.messageBuffer, (value, start, end) => { // Remove the event from the buffer this.messageBuffer = this.messageBuffer.slice(end); // Add the event to the events array events.push(value); }); } catch (error) { // If we can't decode the buffer, it might be incomplete // Keep the entire buffer for next time } finally { // Update buffer with any remaining unprocessed content this.messageBuffer = new Uint8Array(this.messageBuffer); // Return the events return events; } } }