/** * rSocials Local-First Client * * Wraps the shared local-first stack for thread and campaign data. * One Automerge doc per space stores all threads and campaigns. */ import { DocumentManager } from '../../shared/local-first/document'; import type { DocumentId } from '../../shared/local-first/document'; import { EncryptedDocStore } from '../../shared/local-first/storage'; import { DocSyncManager } from '../../shared/local-first/sync'; import { DocCrypto } from '../../shared/local-first/crypto'; import { socialsSchema, socialsDocId } from './schemas'; import type { SocialsDoc, ThreadData, Campaign } from './schemas'; export class SocialsLocalFirstClient { #space: string; #documents: DocumentManager; #store: EncryptedDocStore; #sync: DocSyncManager; #initialized = false; constructor(space: string, docCrypto?: DocCrypto) { this.#space = space; this.#documents = new DocumentManager(); this.#store = new EncryptedDocStore(space, docCrypto); this.#sync = new DocSyncManager({ documents: this.#documents, store: this.#store, }); this.#documents.registerSchema(socialsSchema); } get isConnected(): boolean { return this.#sync.isConnected; } async init(): Promise { if (this.#initialized) return; await this.#store.open(); const cachedIds = await this.#store.listByModule('socials', 'data'); const cached = await this.#store.loadMany(cachedIds); for (const [docId, binary] of cached) { this.#documents.open(docId, socialsSchema, binary); } await this.#sync.preloadSyncStates(cachedIds); const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${proto}//${location.host}/ws/${this.#space}`; try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[SocialsClient] Working offline'); } this.#initialized = true; } async subscribe(): Promise { const docId = socialsDocId(this.#space) as DocumentId; let doc = this.#documents.get(docId); if (!doc) { const binary = await this.#store.load(docId); doc = binary ? this.#documents.open(docId, socialsSchema, binary) : this.#documents.open(docId, socialsSchema); } await this.#sync.subscribe([docId]); return doc ?? null; } // ── Reads ── getDoc(): SocialsDoc | undefined { return this.#documents.get(socialsDocId(this.#space) as DocumentId); } listThreads(): ThreadData[] { const doc = this.getDoc(); if (!doc?.threads) return []; return Object.values(doc.threads).sort((a, b) => b.updatedAt - a.updatedAt); } getThread(id: string): ThreadData | undefined { const doc = this.getDoc(); return doc?.threads?.[id]; } listCampaigns(): Campaign[] { const doc = this.getDoc(); if (!doc?.campaigns) return []; return Object.values(doc.campaigns).sort((a, b) => b.updatedAt - a.updatedAt); } getCampaign(id: string): Campaign | undefined { const doc = this.getDoc(); return doc?.campaigns?.[id]; } // ── Thread writes ── saveThread(thread: ThreadData): void { const docId = socialsDocId(this.#space) as DocumentId; this.#sync.change(docId, `Save thread ${thread.title || thread.id}`, (d) => { if (!d.threads) d.threads = {} as any; thread.updatedAt = Date.now(); if (!thread.createdAt) thread.createdAt = Date.now(); d.threads[thread.id] = thread; }); } deleteThread(id: string): void { const docId = socialsDocId(this.#space) as DocumentId; this.#sync.change(docId, `Delete thread ${id}`, (d) => { if (d.threads?.[id]) delete d.threads[id]; }); } // ── Campaign writes ── saveCampaign(campaign: Campaign): void { const docId = socialsDocId(this.#space) as DocumentId; this.#sync.change(docId, `Save campaign ${campaign.title || campaign.id}`, (d) => { if (!d.campaigns) d.campaigns = {} as any; campaign.updatedAt = Date.now(); if (!campaign.createdAt) campaign.createdAt = Date.now(); d.campaigns[campaign.id] = campaign; }); } deleteCampaign(id: string): void { const docId = socialsDocId(this.#space) as DocumentId; this.#sync.change(docId, `Delete campaign ${id}`, (d) => { if (d.campaigns?.[id]) delete d.campaigns[id]; }); } // ── Events ── onChange(cb: (doc: SocialsDoc) => void): () => void { return this.#sync.onChange(socialsDocId(this.#space) as DocumentId, cb as (doc: any) => void); } onConnect(cb: () => void): () => void { return this.#sync.onConnect(cb); } onDisconnect(cb: () => void): () => void { return this.#sync.onDisconnect(cb); } async disconnect(): Promise { await this.#sync.flush(); this.#sync.disconnect(); } }