class Store {
    sessions = new Map();
    schedules = new Map();
    online = true;
    listeners = new Set();
    upsertSessions(rows) {
        for (const r of rows)
            this.sessions.set(r.sessionId, r);
        this.emit();
    }
    upsertSchedules(rows) {
        for (const r of rows)
            this.schedules.set(r.id, r);
        this.emit();
    }
    applySse(type, body) {
        if (type === 'session.spawned') {
            this.sessions.set(body.session.sessionId, body.session);
        }
        else if (type === 'session.update') {
            const cur = this.sessions.get(body.sessionId);
            if (cur)
                this.sessions.set(body.sessionId, { ...cur, ...body.patch });
        }
        else if (type === 'session.exited') {
            const cur = this.sessions.get(body.sessionId);
            if (cur)
                this.sessions.set(body.sessionId, { ...cur, status: 'closed' });
        }
        else if (type === 'schedule.created') {
            this.schedules.set(body.schedule.id, body.schedule);
        }
        else if (type === 'schedule.updated') {
            const cur = this.schedules.get(body.id);
            if (cur)
                this.schedules.set(body.id, { ...cur, ...body.patch });
        }
        else if (type === 'schedule.deleted') {
            this.schedules.delete(body.id);
        }
        else {
            return; // heartbeat / schedule.fired — no cache mutation
        }
        this.emit();
    }
    setOnline(v) {
        if (this.online !== v) {
            this.online = v;
            this.emit();
        }
    }
    on(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
    emit() { for (const fn of this.listeners)
        fn(); }
}
export const store = new Store();
export async function bootstrap() {
    const [s, sch] = await Promise.all([
        fetch('/api/sessions').then(r => r.json()),
        fetch('/api/schedules').then(r => r.json()),
    ]);
    store.upsertSessions(s.sessions ?? []);
    store.upsertSchedules(sch.schedules ?? []);
    const es = new EventSource('/events');
    const types = [
        'session.spawned', 'session.update', 'session.exited',
        'schedule.created', 'schedule.updated', 'schedule.deleted',
        'schedule.fired', 'heartbeat',
    ];
    for (const t of types) {
        es.addEventListener(t, e => {
            try {
                const data = JSON.parse(e.data);
                store.applySse(t, data.body ?? data);
            }
            catch { /* skip malformed */ }
        });
    }
    es.onerror = () => store.setOnline(false);
    es.onopen = () => store.setOnline(true);
}
//# sourceMappingURL=store.js.map