import { and, eq, inArray, isNull, sql } from 'drizzle-orm'; import { db, tables } from './db/index.ts'; import { canWriteProject, chapterInProject as liveChapterInProject, sceneInProject as liveSceneInProject } from './access.ts'; import { recordProjectCheckpoint } from './checkpoints.ts'; import { isDocEnvelope, prepareDocumentBody } from './document.ts'; import { insertIndexedScene, refreshSceneSubtreeIndex } from './manuscript.ts'; import { indexScene, unindexScene } from './search.ts'; import { recordStructuralSnapshot } from './snapshots.ts'; import { isMatterPosition, type MatterPosition } from '#lib/matter.ts'; import { chapterScope, listOrderedSiblings as siblings, orderedTable, writeOrder, type ManuscriptNodeKind, type SiblingScope as Scope } from './ordered-siblings.ts'; export class StructureError extends Error {} /** A write named a resource outside the writer's live project or permissions. */ export class StructureMissingError extends StructureError {} /** A write named a revision older than the one the scene holds. */ export class StructureConflict extends StructureError {} export type NodeKind = ManuscriptNodeKind; function requireProject(projectId: string) { const project = db .select({ id: tables.project.id }) .from(tables.project) .where(and(eq(tables.project.id, projectId), isNull(tables.project.deletedAt))) .get(); if (!project) throw new StructureError('No such project.'); } function bookInProject(projectId: string, bookId: string) { requireProject(projectId); return db .select() .from(tables.book) .where( and( eq(tables.book.id, bookId), eq(tables.book.projectId, projectId), isNull(tables.book.deletedAt) ) ) .get(); } function partInProject(projectId: string, partId: string) { requireProject(projectId); return db .select({ row: tables.part }) .from(tables.part) .innerJoin(tables.book, eq(tables.book.id, tables.part.bookId)) .where( and( eq(tables.part.id, partId), eq(tables.book.projectId, projectId), isNull(tables.part.deletedAt), isNull(tables.book.deletedAt) ) ) .get()?.row; } function chapterInProject(projectId: string, chapterId: string) { if (!liveChapterInProject(projectId, chapterId)) return undefined; return db.select().from(tables.chapter).where(eq(tables.chapter.id, chapterId)).get(); } function sceneInProject(projectId: string, sceneId: string) { if (!liveSceneInProject(projectId, sceneId)) return undefined; return db.select().from(tables.scene).where(eq(tables.scene.id, sceneId)).get(); } function nodeInProject(projectId: string, kind: NodeKind, id: string) { switch (kind) { case 'book': return bookInProject(projectId, id); case 'part': return partInProject(projectId, id); case 'chapter': return chapterInProject(projectId, id); case 'scene': return sceneInProject(projectId, id); } } function siblingScope(projectId: string, kind: NodeKind, id: string): Scope { switch (kind) { case 'book': return eq(tables.book.projectId, projectId); case 'part': { const part = partInProject(projectId, id)!; return eq(tables.part.bookId, part.bookId); } case 'chapter': { const chapter = chapterInProject(projectId, id)!; return chapterScope(chapter.bookId, chapter.partId, chapter.matter); } case 'scene': { const scene = sceneInProject(projectId, id)!; return eq(tables.scene.chapterId, scene.chapterId); } } } function normalize(kind: NodeKind, scope: Scope) { writeOrder( kind, siblings(kind, scope).map((row) => row.id) ); } function checkedTitle(title: string, kind: string) { const trimmed = title.trim(); if (!trimmed) throw new StructureError(`A ${kind} needs a name.`); return trimmed; } /** * A body arriving from a split or a merge. The document envelope is validated * and both plain text and word count are derived from the normalised document. */ function checkedBody(body: unknown) { if (!isDocEnvelope(body)) { throw new StructureError('The scene text was not readable.'); } return prepareDocumentBody(body); } export function createBook(projectId: string, title: string): string { const trimmed = checkedTitle(title, 'book'); return db.transaction(() => { requireProject(projectId); const id = crypto.randomUUID(); const scope = eq(tables.book.projectId, projectId); recordProjectCheckpoint(projectId, 'Before adding a book'); db.insert(tables.book).values({ id, projectId, title: trimmed }).run(); writeOrder('book', [ ...siblings('book', scope) .map((row) => row.id) .filter((rowId) => rowId !== id), id ]); return id; }); } export function createPart(projectId: string, bookId: string, title: string): string { const trimmed = checkedTitle(title, 'part'); return db.transaction(() => { if (!bookInProject(projectId, bookId)) throw new StructureError('No such book.'); const id = crypto.randomUUID(); const ids = siblings('part', eq(tables.part.bookId, bookId)).map((row) => row.id); recordProjectCheckpoint(projectId, 'Before adding a part'); db.insert(tables.part).values({ id, bookId, title: trimmed, ordinal: ids.length }).run(); writeOrder('part', [...ids, id]); return id; }); } export function createChapter( projectId: string, target: { bookId: string; partId?: string | null; matter?: MatterPosition }, title: string ): { chapterId: string; sceneId: string } { const trimmed = checkedTitle(title, 'chapter'); if (target.matter !== undefined && !isMatterPosition(target.matter)) { throw new StructureError('Choose front matter or back matter.'); } if (target.matter && target.partId) throw new StructureError('A matter page belongs to a book, not a part.'); return db.transaction(() => { if (!bookInProject(projectId, target.bookId)) throw new StructureError('No such book.'); if (target.partId) { const part = partInProject(projectId, target.partId); if (!part || part.bookId !== target.bookId) throw new StructureError('No such part.'); } const chapterId = crypto.randomUUID(); const sceneId = crypto.randomUUID(); const ids = siblings( 'chapter', chapterScope(target.bookId, target.partId ?? null, target.matter ?? null) ).map((row) => row.id); recordProjectCheckpoint(projectId, 'Before adding a chapter'); db.insert(tables.chapter) .values({ id: chapterId, bookId: target.bookId, partId: target.partId ?? null, matter: target.matter ?? null, kind: target.matter ? 'section' : 'chapter', title: trimmed, ordinal: ids.length }) .run(); writeOrder('chapter', [...ids, chapterId]); // An empty scene gives a new chapter a place where the writer can type. insertIndexedScene(db, { id: sceneId, chapterId, title: target.matter ? trimmed : 'Scene 1', ordinal: 0 }); return { chapterId, sceneId }; }); } export function createMatterPage( projectId: string, bookId: string, title: string, matter: MatterPosition ) { if (!isMatterPosition(matter)) throw new StructureError('Choose front matter or back matter.'); return createChapter(projectId, { bookId, matter }, checkedTitle(title, 'page')); } export function setChapterMatter( projectId: string, chapterId: string, matter: MatterPosition | null ) { if (matter !== null && !isMatterPosition(matter)) throw new StructureError('Choose front matter or back matter.'); db.transaction(() => { const chapter = chapterInProject(projectId, chapterId); if (!chapter) throw new StructureError('No such chapter.'); if (chapter.matter === matter) return; const source = siblingScope(projectId, 'chapter', chapterId); const partId = matter ? null : chapter.partId; const destination = chapterScope(chapter.bookId, partId, matter); const ids = siblings('chapter', destination).map((row) => row.id); recordProjectCheckpoint(projectId, 'Before changing page placement'); db.update(tables.chapter) .set({ matter, partId, kind: matter ? 'section' : 'chapter' }) .where(eq(tables.chapter.id, chapterId)) .run(); normalize('chapter', source); writeOrder('chapter', [...ids, chapterId]); refreshSceneSubtreeIndex(projectId, 'chapter', chapterId); }); } export function createScene(projectId: string, chapterId: string, title: string): string { const trimmed = checkedTitle(title, 'scene'); return db.transaction(() => { if (!chapterInProject(projectId, chapterId)) throw new StructureError('No such chapter.'); const id = crypto.randomUUID(); const ids = siblings('scene', eq(tables.scene.chapterId, chapterId)).map((row) => row.id); recordProjectCheckpoint(projectId, 'Before adding a scene'); insertIndexedScene(db, { id, chapterId, title: trimmed, ordinal: ids.length }); writeOrder('scene', [...ids, id]); return id; }); } export function renameNode(projectId: string, kind: NodeKind, id: string, title: string) { parseKind(kind); const trimmed = checkedTitle(title, 'node'); db.transaction(() => { const row = nodeInProject(projectId, kind, id); if (!row) throw new StructureError(`No such ${kind}.`); if (row.title === trimmed) return; const table = orderedTable(kind); recordProjectCheckpoint(projectId, `Before renaming a ${kind}`); db.update(table).set({ title: trimmed, updatedAt: new Date() }).where(eq(table.id, id)).run(); if (kind === 'chapter' && chapterInProject(projectId, id)?.matter) { const scenes = siblings('scene', eq(tables.scene.chapterId, id)); if (scenes.length === 1) { db.update(tables.scene) .set({ title: trimmed }) .where(eq(tables.scene.id, scenes[0].id)) .run(); indexScene(scenes[0].id); } } if (kind === 'scene') refreshSceneSubtreeIndex(projectId, kind, id); }); } export function deleteNode(projectId: string, kind: NodeKind, id: string) { parseKind(kind); db.transaction(() => { const row = nodeInProject(projectId, kind, id); if (!row) throw new StructureError(`No such ${kind}.`); const scope = siblingScope(projectId, kind, id); const rows = siblings(kind, scope); if (kind === 'book' && rows.length <= 1) { throw new StructureError('A project keeps at least one book.'); } if (kind === 'scene' && rows.length <= 1) { throw new StructureError('A chapter keeps at least one scene.'); } const table = orderedTable(kind); recordProjectCheckpoint(projectId, `Before deleting a ${kind}`); db.update(table).set({ deletedAt: new Date() }).where(eq(table.id, id)).run(); normalize(kind, scope); refreshSceneSubtreeIndex(projectId, kind, id); }); } export function moveNode( projectId: string, kind: NodeKind, id: string, toParentId: string | null, toIndex: number ) { parseKind(kind); if (!Number.isFinite(toIndex) || !Number.isInteger(toIndex)) { throw new StructureError('The position must be a whole number.'); } db.transaction(() => { const row = nodeInProject(projectId, kind, id); if (!row) throw new StructureError(`No such ${kind}.`); const source = siblingScope(projectId, kind, id); let destination = source; let changedParent = false; let writeParent = () => {}; if (kind === 'part') { const part = partInProject(projectId, id)!; const bookId = toParentId ?? part.bookId; if (!bookInProject(projectId, bookId)) throw new StructureError('No such book.'); changedParent = bookId !== part.bookId; destination = eq(tables.part.bookId, bookId); const chapters = db .select({ id: tables.chapter.id, projectId: tables.book.projectId }) .from(tables.chapter) .innerJoin(tables.book, eq(tables.book.id, tables.chapter.bookId)) .where(eq(tables.chapter.partId, id)) .all(); if (chapters.some((chapter) => chapter.projectId !== projectId)) { throw new StructureError('The part contains a chapter from another project.'); } writeParent = () => { db.update(tables.part).set({ bookId }).where(eq(tables.part.id, id)).run(); if (chapters.length > 0) { db.update(tables.chapter) .set({ bookId }) .where( inArray( tables.chapter.id, chapters.map((chapter) => chapter.id) ) ) .run(); } }; } else if (kind === 'chapter') { const chapter = chapterInProject(projectId, id)!; const parentId = toParentId ?? chapter.partId ?? chapter.bookId; const part = partInProject(projectId, parentId); const bookId = part?.bookId ?? parentId; const partId = part?.id ?? null; if (chapter.matter && partId) throw new StructureError('A matter page belongs to a book, not a part.'); if (!bookInProject(projectId, bookId)) throw new StructureError('No such parent.'); changedParent = bookId !== chapter.bookId || partId !== chapter.partId; destination = chapterScope(bookId, partId, chapter.matter); writeParent = () => { db.update(tables.chapter).set({ bookId, partId }).where(eq(tables.chapter.id, id)).run(); }; } else if (kind === 'scene') { const scene = sceneInProject(projectId, id)!; const chapterId = toParentId ?? scene.chapterId; if (!chapterInProject(projectId, chapterId)) throw new StructureError('No such chapter.'); changedParent = chapterId !== scene.chapterId; if (changedParent && siblings(kind, source).length <= 1) { throw new StructureError('A chapter keeps at least one scene.'); } destination = eq(tables.scene.chapterId, chapterId); writeParent = () => { db.update(tables.scene).set({ chapterId }).where(eq(tables.scene.id, id)).run(); }; } else if (toParentId !== null && toParentId !== projectId) { throw new StructureError('No such parent.'); } const rows = siblings(kind, destination); const ids = rows.map((sibling) => sibling.id).filter((siblingId) => siblingId !== id); ids.splice(Math.max(0, Math.min(toIndex, ids.length)), 0, id); if ( !changedParent && rows.every((sibling, index) => sibling.id === ids[index] && sibling.ordinal === index) ) return; recordProjectCheckpoint(projectId, `Before moving a ${kind}`); if (changedParent) writeParent(); if (changedParent) normalize(kind, source); writeOrder(kind, ids); refreshSceneSubtreeIndex(projectId, kind, id); }); } export function parseKind(value: string): NodeKind { if (value === 'book' || value === 'part' || value === 'chapter' || value === 'scene') return value; throw new StructureError('Unknown item type.'); } /** * Splits one scene into two at the point the writer chose. * * The browser cuts its document in two and sends both halves. The server names * the revision it replaces, so a split from a stale tab is refused rather than * written over newer words. The second half lands directly after the first, and * both halves reach history first, through the project checkpoint and a snapshot. */ export function splitScene( projectId: string, sceneId: string, baseRevision: number, before: unknown, after: unknown, title?: string, actorUserId?: string ): { sceneId: string; revision: number } { if (!Number.isInteger(baseRevision)) { throw new StructureError('The split did not say which version it was built on.'); } return db.transaction(() => { if (actorUserId !== undefined && !canWriteProject(actorUserId, projectId)) { throw new StructureMissingError('No such scene.'); } const scene = sceneInProject(projectId, sceneId); if (!scene) throw new StructureMissingError('No such scene.'); if (scene.revision !== baseRevision) { throw new StructureConflict( 'This scene changed since it was opened. Reload before splitting.' ); } const first = checkedBody(before); const second = checkedBody(after); const name = title === undefined ? `${scene.title} (continued)` : checkedTitle(title, 'scene'); const id = crypto.randomUUID(); const ids = siblings('scene', eq(tables.scene.chapterId, scene.chapterId)).map((row) => row.id); const at = ids.indexOf(sceneId); if (at < 0) throw new StructureMissingError('No such scene.'); recordProjectCheckpoint(projectId, 'Before splitting a scene'); recordStructuralSnapshot(sceneId, scene, 'Before splitting the scene'); db.update(tables.scene) .set({ ...first, revision: sql`${tables.scene.revision} + 1`, updatedAt: new Date() }) .where(eq(tables.scene.id, sceneId)) .run(); insertIndexedScene(db, { id, chapterId: scene.chapterId, title: name, body: second.body, ordinal: at + 1, revision: 1 }); const order = [...ids]; order.splice(at + 1, 0, id); writeOrder('scene', order); indexScene(sceneId); return { sceneId: id, revision: scene.revision + 1 }; }); } /** * Joins a scene with the one directly after it. * * The kept scene must be named at the revision the writer has open, so a merge * cannot swallow words saved after the page loaded. The next scene is named * explicitly and must be next, because deleting a neighbour is not something to * guess at from an ordinal. Its words reach the checkpoint and a snapshot first. */ export function mergeScenes( projectId: string, keepId: string, absorbId: string, baseRevision: number, actorUserId?: string ): { revision: number } { if (!Number.isInteger(baseRevision)) { throw new StructureError('The merge did not say which version it was built on.'); } return db.transaction(() => { if (actorUserId !== undefined && !canWriteProject(actorUserId, projectId)) { throw new StructureMissingError('No such scene.'); } const keep = sceneInProject(projectId, keepId); const absorb = sceneInProject(projectId, absorbId); if (!keep || !absorb) throw new StructureMissingError('No such scene.'); if (keep.chapterId !== absorb.chapterId) { throw new StructureError('Only scenes in the same chapter can merge.'); } if (keep.revision !== baseRevision) { throw new StructureConflict('This scene changed since it was opened. Reload before merging.'); } const ids = siblings('scene', eq(tables.scene.chapterId, keep.chapterId)).map((row) => row.id); const keepAt = ids.indexOf(keepId); if (keepAt < 0 || ids[keepAt + 1] !== absorbId) { throw new StructureError('Only the next scene can be merged.'); } const keepDoc = checkedBody(keep.body).body; const absorbDoc = checkedBody(absorb.body).body; const merged = prepareDocumentBody({ type: 'doc', content: [...keepDoc.content, ...absorbDoc.content] }); recordProjectCheckpoint(projectId, 'Before merging scenes'); recordStructuralSnapshot(keepId, keep, 'Before merging the next scene'); recordStructuralSnapshot(absorbId, absorb, 'Merged into the previous scene'); db.update(tables.scene) .set({ ...merged, revision: sql`${tables.scene.revision} + 1`, updatedAt: new Date() }) .where(eq(tables.scene.id, keepId)) .run(); db.update(tables.scene) .set({ deletedAt: new Date() }) .where(eq(tables.scene.id, absorbId)) .run(); writeOrder( 'scene', ids.filter((id) => id !== absorbId) ); indexScene(keepId); unindexScene(absorbId); return { revision: keep.revision + 1 }; }); }