/** * Notification storage. JSON packageStorage, capped at 200 notifications. */ import { loadJson, saveJson } from '../lib/storage.ts' import type { Notification, NotificationRules } from './types.ts' import { defaultNotificationRules } from './types.ts' const NOTIFICATIONS_KEY = 'factory:notifications:v1' const RULES_KEY = 'factory:notification-rules:v1' const MAX_NOTIFICATIONS = 200 type NotificationStore = { notifications: Notification[] } function emptyStore(): NotificationStore { return { notifications: [] } } export async function loadNotifications(): Promise { return (await loadJson(NOTIFICATIONS_KEY, emptyStore())).notifications } export async function saveNotification(notification: Notification): Promise { const store = await loadJson(NOTIFICATIONS_KEY, emptyStore()) store.notifications.unshift(notification) if (store.notifications.length > MAX_NOTIFICATIONS) { store.notifications = store.notifications.slice(0, MAX_NOTIFICATIONS) } await saveJson(NOTIFICATIONS_KEY, store) } export async function markRead(ids: string[]): Promise { const store = await loadJson(NOTIFICATIONS_KEY, emptyStore()) let count = 0 const idSet = new Set(ids) for (const n of store.notifications) { if (idSet.has(n.id) && n.status === 'unread') { n.status = 'read' count++ } } if (count > 0) await saveJson(NOTIFICATIONS_KEY, store) return count } export async function markAllRead(projectId?: string): Promise { const store = await loadJson(NOTIFICATIONS_KEY, emptyStore()) let count = 0 for (const n of store.notifications) { if (n.status === 'unread' && (!projectId || n.projectId === projectId)) { n.status = 'read' count++ } } if (count > 0) await saveJson(NOTIFICATIONS_KEY, store) return count } export async function countUnread(projectId?: string): Promise { const notifications = await loadNotifications() return notifications.filter((n) => n.status === 'unread' && (!projectId || n.projectId === projectId)).length } export async function loadRules(): Promise { return loadJson(RULES_KEY, defaultNotificationRules()) } export async function saveRules(rules: NotificationRules): Promise { await saveJson(RULES_KEY, rules) }