import type { UiCommandInfo, UiConnectionStatus, UiEvent, UiEventInput, UiSnapshot, } from "./protocol"; export type EventStoreOptions = { maxEvents?: number; now?: () => number; }; export type SnapshotOptions = { status: UiConnectionStatus; sessionPath?: string; commands?: UiCommandInfo[]; }; export class EventStore { readonly #maxEvents: number; readonly #now: () => number; #nextId = 1; #events: UiEvent[] = []; constructor(options: EventStoreOptions = {}) { this.#maxEvents = Math.max(1, options.maxEvents ?? 500); this.#now = options.now ?? Date.now; } append(input: UiEventInput): UiEvent { const event = { id: this.#nextId++, at: this.#now(), ...input } as UiEvent; this.#events.push(event); if (this.#events.length > this.#maxEvents) { this.#events.splice(0, this.#events.length - this.#maxEvents); } return event; } replayAfter(lastEventId: number): UiEvent[] { return this.#events.filter((event) => event.id > lastEventId); } snapshot(options: SnapshotOptions): UiSnapshot { return { version: 1, lastEventId: this.lastEventId(), status: options.status, sessionPath: options.sessionPath, commands: options.commands ?? [], events: [...this.#events], }; } lastEventId(): number { return this.#nextId - 1; } }