import { and, asc, eq, isNull, sql } from 'drizzle-orm'; import { db, tables } from './db/index.ts'; import { countWords } from '../words.ts'; import { canWriteProject, noteTypeInProject, projectIdOfNote } from './access.ts'; import { prepareDocumentBody, sameDocument } from './document.ts'; import { RecoveryError, recordNoteVersion } from './item-history.ts'; import { indexNote, unindexNote } from './search.ts'; import { loadNoteType } from './note-types.ts'; import { getInstance } from './instance.ts'; import { removeImage, storeImage } from './uploads.ts'; import type { DocumentVersion, SaveOutcome, SavePrecondition } from './save-request.ts'; export type NoteImage = { noteId: string; imageId: string | null; mime: string; bytes: number; width: number; height: number; alt: string; originalName: string; createdAt: Date; }; export type NoteCard = { id: string; title: string; summary: string; typeId: string | null; typeName: string | null; accent: string; body: unknown; bodyText: string; /** A save must name the revision it was built on. */ revision: number; image: NoteImage | null; }; export function listNotes(projectId: string): NoteCard[] { const rows = db .select({ id: tables.note.id, title: tables.note.title, summary: tables.note.summary, body: tables.note.body, bodyText: tables.note.bodyText, revision: tables.note.revision, typeId: tables.note.noteTypeId, typeName: tables.noteType.name, accent: tables.noteType.accent, image: { noteId: tables.noteImage.noteId, imageId: tables.noteImage.imageId, mime: tables.noteImage.mime, bytes: tables.noteImage.bytes, width: tables.noteImage.width, height: tables.noteImage.height, alt: tables.noteImage.alt, originalName: tables.noteImage.originalName, createdAt: tables.noteImage.createdAt } }) .from(tables.note) .leftJoin(tables.noteType, eq(tables.noteType.id, tables.note.noteTypeId)) .leftJoin(tables.noteImage, eq(tables.noteImage.noteId, tables.note.id)) .where(and(eq(tables.note.projectId, projectId), isNull(tables.note.deletedAt))) .orderBy(asc(tables.note.ordinal), asc(tables.note.title)) .all(); return rows.map((row) => ({ id: row.id, title: row.title, summary: row.summary, typeId: row.typeId, typeName: row.typeName, accent: row.accent ?? 'blue-screen', body: row.body, bodyText: row.bodyText, revision: row.revision, image: row.image?.noteId ? row.image : null })); } export function createNote(projectId: string, title: string, typeId: string | null): string { const id = crypto.randomUUID(); /* * The type id arrives in a form. One from another project belongs to a bible * the writer cannot see, so it is dropped rather than kept, and the note is * still created: a missing type is a cosmetic loss, not a broken row. */ const type = typeId ? loadNoteType(projectId, typeId) : null; /* * The text is derived from the template document rather than stored beside it, * so search finds the starter words and the two can never disagree. */ const { body, bodyText } = prepareDocumentBody(type?.template ?? null); db.transaction(() => { db.insert(tables.note) .values({ id, projectId, noteTypeId: type?.id ?? null, title, summary: '', body, bodyText }) .run(); // An empty note is still findable by its name. indexNote(id); }); return id; } export function updateNoteDetails( projectId: string, noteId: string, title: string, typeId: string | null ): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); const next = title.trim(); if (!note || !next || (typeId && !noteTypeInProject(projectId, typeId))) return false; if (note.title === next && note.noteTypeId === typeId) return true; recordNoteVersion(projectId, noteId); db.update(tables.note) .set({ title: next, noteTypeId: typeId, updatedAt: new Date() }) .where(eq(tables.note.id, noteId)) .run(); indexNote(noteId); return true; }); } /** * Saves a note's words only while the note is at the revision the caller built * them on. A stale save writes nothing and returns the current version. */ export function saveNoteBody( noteId: string, rawBody: unknown, precondition: SavePrecondition, summary?: string, actorUserId?: string ): SaveOutcome { const prepared = prepareDocumentBody(rawBody); const { body: stored, bodyText } = prepared; try { return db.transaction((): SaveOutcome => { const existing = db .select() .from(tables.note) .where(and(eq(tables.note.id, noteId), isNull(tables.note.deletedAt))) .get(); const liveProjectId = projectIdOfNote(noteId); if ( !existing || liveProjectId !== existing.projectId || (actorUserId !== undefined && !canWriteProject(actorUserId, liveProjectId)) ) { return { ok: false, reason: 'gone' }; } if (existing.revision !== precondition.baseRevision) { return { ok: false, reason: 'conflict', current: toVersion(existing) }; } if ( sameDocument(existing, prepared) && (summary === undefined || existing.summary === summary) ) { return { ok: true, revision: existing.revision }; } recordNoteVersion(existing.projectId, noteId, precondition.replace ? 'conflict' : 'edit'); const written = db .update(tables.note) .set({ body: stored, bodyText, summary: summary ?? existing.summary, revision: sql`${tables.note.revision} + 1`, updatedAt: new Date() }) .where( and( eq(tables.note.id, noteId), eq(tables.note.revision, precondition.baseRevision), isNull(tables.note.deletedAt) ) ) .returning({ revision: tables.note.revision }) .get(); if (!written) throw new NoteSaveRefused(toVersion(existing)); indexNote(noteId); return { ok: true, revision: written.revision }; }); } catch (error) { if (error instanceof NoteSaveRefused) { return { ok: false, reason: 'conflict', current: error.current }; } throw error; } } class NoteSaveRefused extends Error { constructor(public readonly current: DocumentVersion) { super('The note changed before the save.'); } } function toVersion(row: typeof tables.note.$inferSelect): DocumentVersion { return { revision: row.revision, body: row.body, text: row.bodyText, words: countWords(row.bodyText), savedAt: row.updatedAt }; } function liveNote(projectId: string, noteId: string) { const note = db .select() .from(tables.note) .where( and( eq(tables.note.id, noteId), eq(tables.note.projectId, projectId), isNull(tables.note.deletedAt) ) ) .get(); if (!note) return null; // `projectIdOfNote` also refuses a note whose project has been deleted. return projectIdOfNote(noteId) === projectId ? note : null; } /** * The project comes first and the note id is checked inside it, because the id * arrives in a form: one from another project reads as a note that never existed. * * The revision counts the words, not the name, so a rename does not move it. * Bumping it would refuse the next save from an editor already open on the note. */ export function renameNote(projectId: string, noteId: string, title: string): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); if (!note) return false; const next = title.trim(); if (next.length === 0 || next === note.title) return false; recordNoteVersion(projectId, noteId); const written = db .update(tables.note) .set({ title: next, updatedAt: new Date() }) .where(eq(tables.note.id, noteId)) .returning({ id: tables.note.id }) .get(); if (!written) throw new RecoveryError('The note could not be renamed.', 'blocked'); indexNote(noteId); return true; }); } /** * A type id from another project is refused rather than dropped: the writer asked * for that type, and filing the note somewhere else hides the mistake. * * Like a rename, this moves no revision: the words did not change and an open * editor must still be able to save them. */ export function setNoteType(projectId: string, noteId: string, typeId: string | null): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); if (!note) return false; if (typeId !== null && !noteTypeInProject(projectId, typeId)) { throw new NoteTypeRefused(); } if (note.noteTypeId === typeId) return true; recordNoteVersion(projectId, noteId); const written = db .update(tables.note) .set({ noteTypeId: typeId, updatedAt: new Date() }) .where(eq(tables.note.id, noteId)) .returning({ id: tables.note.id }) .get(); if (!written) throw new RecoveryError('The note could not be reclassified.', 'blocked'); // The type is not indexed, but reindexing keeps the row current in case a // result starts showing it. indexNote(noteId); return true; }); } export class NoteTypeRefused extends Error { constructor() { super('No such note type.'); this.name = 'NoteTypeRefused'; } } /** Recovery trash restores a deleted note. */ export function deleteNote(projectId: string, noteId: string): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); if (!note) return false; recordNoteVersion(projectId, noteId); const written = db .update(tables.note) .set({ deletedAt: new Date(), revision: sql`${tables.note.revision} + 1` }) .where(eq(tables.note.id, noteId)) .returning({ id: tables.note.id }) .get(); if (!written) throw new RecoveryError('The note could not be deleted.', 'blocked'); unindexNote(noteId); return true; }); } /** * Goes through `saveNoteBody`, which gives the fill a revision check, a version * in history and a fresh index entry. A note with any words refuses: a template * never replaces text. */ export function applyTemplateToNote( projectId: string, noteId: string ): { ok: true; revision: number; body: unknown; bodyText: string } | { ok: false; message: string } { const note = liveNote(projectId, noteId); if (!note) return { ok: false, message: 'No such note.' }; if (note.bodyText.trim().length > 0) { return { ok: false, message: 'This note already has words. The template will not replace them.' }; } const type = note.noteTypeId ? loadNoteType(projectId, note.noteTypeId) : null; if (!type?.template) return { ok: false, message: 'That note’s type has no template.' }; const prepared = prepareDocumentBody(type.template); const saved = saveNoteBody(noteId, prepared.body, { baseRevision: note.revision }); if (!saved.ok) { return { ok: false, message: saved.reason === 'conflict' ? 'The note changed before the template could be applied.' : 'No such note.' }; } return { ok: true, revision: saved.revision, body: prepared.body, bodyText: prepared.bodyText }; } /** * Replaces any existing `note_image` row. The revision does not move and no note * version is recorded, so an editor open on the note can still save its words. */ export async function attachNoteImage( projectId: string, noteId: string, bytes: Uint8Array, options: { originalName?: string; alt?: string; preserveOriginal: boolean; actorUserId?: string; } ): Promise { const note = liveNote(projectId, noteId); if ( !note || (options.actorUserId !== undefined && !canWriteProject(options.actorUserId, projectId)) ) { throw new RecoveryError('No such note.', 'not_found'); } const instance = getInstance(); const preserveOriginal = Boolean(instance.preserveOriginals && options.preserveOriginal); const facts = await storeImage(bytes, { preserveOriginal }); try { return db.transaction(() => { if ( !liveNote(projectId, noteId) || (options.actorUserId !== undefined && !canWriteProject(options.actorUserId, projectId)) ) { throw new RecoveryError('No such note.', 'not_found'); } db.delete(tables.noteImage).where(eq(tables.noteImage.noteId, noteId)).run(); const row = db .insert(tables.noteImage) .values({ noteId, imageId: facts.imageId, mime: facts.mime, bytes: facts.bytes, width: facts.width, height: facts.height, alt: options.alt ?? '', originalName: options.originalName ?? '' }) .returning() .get(); return row; }); } catch (error) { removeImage(facts.imageId); throw error; } } /** Removes the image record. The files stay on disk for the sweep. */ export function removeNoteImage(projectId: string, noteId: string, actorUserId?: string): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); if (!note) return false; if (actorUserId !== undefined && !canWriteProject(actorUserId, projectId)) return false; db.delete(tables.noteImage).where(eq(tables.noteImage.noteId, noteId)).run(); return true; }); } /** Updates the image alt text without moving note.revision. */ export function updateNoteImageAlt(projectId: string, noteId: string, alt: string): boolean { return db.transaction(() => { const note = liveNote(projectId, noteId); if (!note) return false; const existing = db .select() .from(tables.noteImage) .where(eq(tables.noteImage.noteId, noteId)) .get(); if (!existing) return false; db.update(tables.noteImage).set({ alt }).where(eq(tables.noteImage.noteId, noteId)).run(); return true; }); }