Something went wrong. Try again.
Private notes, end to end encrypted, on atproto. wholebit.studio/stones
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271import { keyringKeyId, type KeyringRecord, type NoteCodec } from './crypto'import type { ImportEntry } from './export'import { archive as archiveState, emptyNote, normalizeContent, orderBetween, pin as pinState, restore as restoreState, trash as trashState, unarchive as unarchiveState, unpin as unpinState, type LocalNote, type NoteContent, type StatePatch,} from './model'import type { Remote, StorageUsage } from './remote'import type { NoteStore } from './store'import { SyncEngine, type SyncResult } from './sync'
export type SyncStatus = | { state: 'idle'; at: number | null; last: SyncResult | null } | { state: 'syncing' } | { state: 'error'; error: string; at: number }
const TRASH_TTL_MS = 7 * 24 * 60 * 60 * 1000const SYNC_DEBOUNCE_MS = 1500
export interface ImportResult { added: number updated: number skipped: number}
export type NotePatch = Partial<Omit<NoteContent, 'createdAt' | 'modifiedAt'>>
export class Notebook { private readonly engine: SyncEngine private readonly listeners = new Set<() => void>() private running: Promise<void> | null = null private syncAgain = false private stopped = false private timer: ReturnType<typeof setTimeout> | null = null private version = 0 status: SyncStatus = { state: 'idle', at: null, last: null } loaded: boolean
constructor( private readonly remote: Remote, private readonly store: NoteStore, private codec: NoteCodec, private readonly now: () => number = Date.now, private readonly onKeyringChange?: (keyring: KeyringRecord) => void, ) { this.engine = new SyncEngine(remote, store, codec, now, () => this.emit()) this.loaded = store.all().length > 0 }
// ---- Events ---- subscribe(listener: () => void): () => void { this.listeners.add(listener) return () => this.listeners.delete(listener) }
getVersion(): number { return this.version }
private emit() { this.version++ for (const listener of this.listeners) listener() }
// ---- Notes ---- notes(): LocalNote[] { return this.store.all().filter((note) => !note.deleted) }
get(id: string): LocalNote | undefined { const note = this.store.get(id) return note && !note.deleted ? note : undefined }
async create(patch: NotePatch): Promise<string> { const id = this.codec.newId() const content = { ...emptyNote(this.now()), ...patch } await this.store.put({ id, content, version: null, dirty: true, deleted: false }) this.changed() return id }
async update(id: string, patch: NotePatch): Promise<void> { const note = this.get(id) if (!note) return const modifiedAt = Math.max(this.now(), note.content.modifiedAt + 1) await this.store.put({ ...note, content: { ...note.content, ...patch, modifiedAt }, dirty: true }) this.changed() }
move(id: string, above: LocalNote | undefined, below: LocalNote | undefined) { return this.update(id, { order: orderBetween(above?.content.order, below?.content.order, this.now()) }) }
pin(id: string) { return this.transition(id, pinState) }
unpin(id: string) { return this.transition(id, unpinState) }
archive(id: string) { return this.transition(id, archiveState) }
unarchive(id: string) { return this.transition(id, unarchiveState) }
trash(id: string) { return this.transition(id, (content) => trashState(content, this.now())) }
restore(id: string) { return this.transition(id, restoreState) }
private async transition(id: string, makePatch: (content: NoteContent) => StatePatch): Promise<void> { const note = this.get(id) if (!note) return const patch = makePatch(note.content) if (Object.keys(patch).length > 0) await this.update(id, patch) }
async deleteForever(id: string): Promise<void> { const note = this.store.get(id) if (!note) return if (note.version === null) await this.store.remove(id) else await this.store.put({ ...note, deleted: true, dirty: true }) this.changed() }
// An entry without id is skipped if a note with the same text exists. // An entry with id replaces the note only if the entry is newer. async importNotes(entries: ImportEntry[]): Promise<ImportResult> { const result: ImportResult = { added: 0, updated: 0, skipped: 0 } const textKey = (content: NoteContent) => `${content.title}\u0000${content.body}` const texts = new Set(this.notes().map((note) => textKey(note.content))) await this.store.batch(async () => { for (const entry of entries) { const id = entry.id const content = normalizeContent(entry.content) if (!id && texts.has(textKey(content))) { result.skipped++ continue } texts.add(textKey(content)) const local = id ? this.store.get(id) : undefined if (id && local && !local.deleted) { if (local.content.modifiedAt >= content.modifiedAt) { result.skipped++ continue } await this.store.put({ ...local, content, dirty: true }) result.updated++ continue } await this.store.put({ id: id ?? this.codec.newId(), content, version: local?.version ?? null, dirty: true, deleted: false, }) result.added++ } }) if (result.added || result.updated) this.changed() return result }
async emptyTrash(): Promise<void> { for (const note of this.notes()) if (note.content.trashedAt !== null) await this.deleteForever(note.id) }
// ---- Encryption ---- get encrypted(): boolean { return this.codec.keyId !== null }
setCodec(codec: NoteCodec): void { this.codec = codec this.engine.codec = codec this.changed() }
// ---- Sync ---- // One sync at a time. A request during a sync runs one more sync after it. private changed() { this.emit() this.requestSync() }
requestSync(delay = SYNC_DEBOUNCE_MS): void { if (this.stopped) return if (this.timer) clearTimeout(this.timer) this.timer = setTimeout(() => { this.timer = null void this.syncNow() }, delay) }
async syncNow(): Promise<void> { if (this.stopped) return if (this.running) { this.syncAgain = true return this.running } this.running = this.run().finally(() => { this.running = null if (this.syncAgain) { this.syncAgain = false void this.syncNow() } }) return this.running }
private async run(): Promise<void> { this.status = { state: 'syncing' } this.emit() try { const keyring = await this.remote.getKeyring() if (keyring && keyringKeyId(keyring) !== this.codec.keyId) { this.status = { state: 'error', error: 'Encryption settings changed on another device', at: this.now() } this.onKeyringChange?.(keyring) } else { await this.purgeTrash() const last = await this.engine.sync() this.status = { state: 'idle', at: this.now(), last } } } catch (err) { this.status = { state: 'error', error: err instanceof Error ? err.message : String(err), at: this.now() } } this.loaded = true this.emit() }
private async purgeTrash(): Promise<void> { const cutoff = this.now() - TRASH_TTL_MS for (const note of this.notes()) { if (note.content.trashedAt !== null && note.content.trashedAt < cutoff) await this.deleteForever(note.id) } }
storageUsage(): Promise<StorageUsage> { return this.remote.usage() }
async stop(): Promise<void> { this.stopped = true this.dispose() await this.running }
dispose(): void { if (this.timer) clearTimeout(this.timer) this.listeners.clear() }}